'use client';

import * as DropdownMenu from '@radix-ui/react-dropdown-menu';
import { useRef, useState } from 'react';

import Button, { ButtonShape, ButtonVariant } from '@/components/button/Button';
import { ImageIcon, PhotoGalleryIcon, SparklesIcon, UploadIcon } from '@/icons';

interface ImageSelectionMenuProps {
  /** Display mode: 'video' shows interactive menu, 'image' shows static placeholder */
  mode: 'video' | 'image';
  isLoading: boolean;
  loadingType?: 'uploading' | 'generating';
  onGenerateFromSong: () => void;
  onUseExistingCover: () => void;
  onUploadImage: (file: File) => void;
}

export const ImageSelectionMenu = ({
  mode,
  isLoading,
  onGenerateFromSong,
  onUseExistingCover,
  onUploadImage,
  loadingType = 'generating',
}: ImageSelectionMenuProps) => {
  const [showMenu, setShowMenu] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const handleFileSelect = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (file) {
      // Normalize file extension to lowercase to handle uppercase extensions like .PNG, .JPEG
      const lastDotIndex = file.name.lastIndexOf('.');
      if (lastDotIndex !== -1) {
        const baseName = file.name.substring(0, lastDotIndex);
        const extension = file.name.substring(lastDotIndex + 1).toLowerCase();
        // Create a new File object with normalized extension
        const normalizedFile = new File([file], `${baseName}.${extension}`, {
          type: file.type,
          lastModified: file.lastModified,
        });
        onUploadImage(normalizedFile);
      } else {
        onUploadImage(file);
      }
      setShowMenu(false);
      // Reset input so same file can be selected again
      event.target.value = '';
    }
  };

  // IMAGE MODE: Static placeholder with no interaction
  if (mode === 'image') {
    return (
      <div className='flex h-[250px] w-[146px] flex-col items-center justify-center gap-4 rounded-lg border border-dashed border-foreground-inactive bg-background-secondary p-4'>
        <SparklesIcon className='h-10 w-10 text-foreground-inactive' />
        <p className='text-center text-xs text-foreground-inactive'>
          Enter a prompt below to create an image
        </p>
      </div>
    );
  }

  // VIDEO MODE: Interactive dropdown menu
  return (
    <>
      <DropdownMenu.Root
        open={showMenu}
        onOpenChange={setShowMenu}
        modal={false}
      >
        <DropdownMenu.Trigger asChild disabled={isLoading}>
          <Button
            variant={ButtonVariant.Standard}
            shape={ButtonShape.Rounded}
            disabled={isLoading}
            className='h-[250px] w-[146px] border border-dashed border-foreground-inactive bg-background-secondary'
            contentClassName='h-full flex-col gap-4 justify-center items-center'
            aria-label='Add image'
          >
            {isLoading ? (
              <>
                <SparklesIcon className='h-10 w-10 animate-pulse2 text-foreground-inactive' />
                <p className='text-center text-xs text-foreground-inactive'>
                  {loadingType === 'uploading'
                    ? 'Uploading image...'
                    : 'Generating image...'}
                </p>
              </>
            ) : (
              <>
                <PhotoGalleryIcon className='h-10 w-10 text-foreground-inactive' />
                <p className='text-center text-xs text-foreground-inactive'>
                  Add an image as your first frame or enter a prompt to create a
                  video
                </p>
              </>
            )}
          </Button>
        </DropdownMenu.Trigger>
        <DropdownMenu.Portal>
          <DropdownMenu.Content
            align='center'
            side='bottom'
            sideOffset={8}
            className='z-[1401] w-[280px] overflow-hidden rounded-xl border border-border-primary bg-background-tertiary p-2 shadow-2xl'
          >
            <DropdownMenu.Item
              onSelect={() => {
                fileInputRef.current?.click();
              }}
              className='flex cursor-pointer items-center gap-3 rounded-lg px-2 py-2 text-sm text-foreground-secondary outline-none hover:bg-background-secondary'
            >
              <div className='flex h-8 w-8 items-center justify-center'>
                <UploadIcon className='h-5 w-5' />
              </div>
              <div className='flex flex-col'>
                <span className='font-medium'>Upload from Device</span>
                <span className='text-xs text-foreground-inactive'>
                  Choose an image from your device
                </span>
              </div>
            </DropdownMenu.Item>

            <DropdownMenu.Item
              onSelect={onUseExistingCover}
              className='flex cursor-pointer items-center gap-3 rounded-lg px-2 py-2 text-sm text-foreground-secondary outline-none hover:bg-background-secondary'
            >
              <div className='flex h-8 w-8 items-center justify-center'>
                <ImageIcon className='h-5 w-5' />
              </div>
              <div className='flex flex-col'>
                <span className='font-medium'>Use Existing Cover Art</span>
                <span className='text-xs text-foreground-inactive'>
                  Use your song's current cover as the first frame
                </span>
              </div>
            </DropdownMenu.Item>

            <DropdownMenu.Item
              onSelect={onGenerateFromSong}
              className='flex cursor-pointer items-center gap-3 rounded-lg px-2 py-2 text-sm text-foreground-secondary outline-none hover:bg-background-secondary'
            >
              <div className='flex h-8 w-8 items-center justify-center'>
                <SparklesIcon className='h-5 w-5' />
              </div>
              <div className='flex flex-col'>
                <span className='font-medium'>Generate Image from Song</span>
                <span className='text-xs text-foreground-inactive'>
                  Use your song lyrics to generate the first frame
                </span>
              </div>
            </DropdownMenu.Item>
          </DropdownMenu.Content>
        </DropdownMenu.Portal>
      </DropdownMenu.Root>

      <input
        ref={fileInputRef}
        type='file'
        accept='image/jpeg,image/jpg,image/png,image/webp,image/bmp'
        onChange={handleFileSelect}
        className='hidden'
      />
    </>
  );
};
