import { useCallback } from 'react';

import { toast } from '@/components/toast/Toast';
import type { GenerationCarouselItem } from '@/hooks/useSongModal';

import { GenerationHistoryItem } from './GenerationHistoryItem';
import type {
  HistoryEntity,
  MediaType,
  ToggleFavoriteHandler,
} from './generationHistoryTypes';

interface GenerationHistoryEntityProps {
  entity: HistoryEntity;
  onToggleFavorite: ToggleFavoriteHandler;
  setImageToVideoPrompt: (prompt: string) => void;
  setMediaType: (mediaType: MediaType) => void;
  handleUploadImage: (file: File) => void;
  navigateToGenerationCarousel: (
    items: GenerationCarouselItem[],
    initialIndex: number
  ) => void;

  allCarouselItems: GenerationCarouselItem[];
}

export const GenerationHistoryEntity = ({
  setImageToVideoPrompt,
  setMediaType,
  handleUploadImage,
  entity,
  onToggleFavorite,
  navigateToGenerationCarousel,
  allCarouselItems,
}: GenerationHistoryEntityProps) => {
  const handleItemClick = useCallback(
    (itemId: string) => {
      if (navigateToGenerationCarousel) {
        // Find the index of the clicked item in the FULL flattened list
        const initialIndex = allCarouselItems.findIndex((i) => i.id === itemId);
        navigateToGenerationCarousel(allCarouselItems, initialIndex);
      }
    },
    [allCarouselItems, navigateToGenerationCarousel]
  );

  const handleGenerateVideoFromImage = useCallback(
    async (itemId: string) => {
      const item = entity.items.find((i) => i.id === itemId);
      if (!item || !item.url || item.type !== 'image') {
        return;
      }

      try {
        // Fetch the image from the URL
        const response = await fetch(item.url);
        if (!response.ok) {
          throw new Error(`Failed to fetch image: ${response.status}`);
        }

        const blob = await response.blob();
        // Create a File object from the blob with appropriate name
        const file = new File([blob], 'image.jpg', {
          type: blob.type || 'image/jpeg',
        });

        // Set media type to image-to-video and upload the image file
        setMediaType('image-to-video');
        handleUploadImage(file);

        // Optionally set the prompt if available
        if (entity.prompt) {
          setImageToVideoPrompt(entity.prompt);
        }

        toast({
          title: 'Image loaded',
          description: 'Ready to generate video from image',
          status: 'success',
          duration: 2000,
          isClosable: true,
        });
      } catch (error) {
        console.error('Failed to generate video from image:', error);
        toast({
          title: 'Failed to load image',
          description:
            'Unable to load the image for video generation. Please try again.',
          status: 'error',
          duration: 3000,
          isClosable: true,
        });
      }
    },
    [entity, setMediaType, handleUploadImage, setImageToVideoPrompt]
  );
  return (
    <div className='flex flex-col gap-3'>
      <div className='flex items-center justify-between'>
        <div className='flex items-center gap-2'>
          <span
            className={`text-xs font-semibold ${entity.type === 'video' ? 'text-accent-pink' : 'text-accent-blue'}`}
          >
            {entity.type === 'video' ? 'Video' : 'Image'}
          </span>
          {entity.type === 'video' && entity.videoModelDisplayName && (
            <>
              <span className='text-xs text-foreground-inactive'>
                {entity.videoModelDisplayName}
              </span>
              <span className='text-xs text-foreground-inactive'>•</span>
            </>
          )}
          <span className='text-xs text-foreground-inactive'>
            {new Date(entity.createdAt).toLocaleString()}
          </span>
        </div>
      </div>
      <p className='text-xs text-foreground-secondary'>{entity.prompt}</p>

      <div className='flex gap-2 overflow-x-auto pb-2'>
        {entity.items.map((item) => (
          <div key={item.id} className='flex-shrink-0'>
            <GenerationHistoryItem
              item={item}
              onToggleFavorite={onToggleFavorite}
              handleGenerateVideoFromImage={() =>
                handleGenerateVideoFromImage(item.id)
              }
              onClick={(e: React.MouseEvent | React.KeyboardEvent) => {
                handleItemClick(item.id);
                e.stopPropagation();
              }}
            />
          </div>
        ))}
      </div>
    </div>
  );
};
