'use client';

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

import Button, {
  ButtonShape,
  ButtonSize,
  ButtonVariant,
} from '@/components/button/Button';
import ImageWithFallback from '@/components/image/ImageWithFallback';
import { Tooltip } from '@/components/tooltip/Tooltip';
import { CloseIcon, PhotoGalleryIcon, SparklesIcon, UploadIcon } from '@/icons';
import { LARGE_IMAGE, SMALL_IMAGE } from '@/utils/constants';

interface ImageStartFrameButtonProps {
  imageUrl: string | null;
  isLoading: boolean;
  loadingType?: 'uploading' | 'generating';
  onGenerateFromSong: () => void;
  onUseExistingCover: () => void;
  onUploadImage: (file: File) => void;
  onRemoveImage: () => void;
}

export const ImageStartFrameButton = ({
  imageUrl,
  isLoading,
  onGenerateFromSong,
  onUseExistingCover,
  onUploadImage,
  onRemoveImage,
  loadingType = 'generating',
}: ImageStartFrameButtonProps) => {
  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
      const lastDotIndex = file.name.lastIndexOf('.');
      if (lastDotIndex !== -1) {
        const baseName = file.name.substring(0, lastDotIndex);
        const extension = file.name.substring(lastDotIndex + 1).toLowerCase();
        const normalizedFile = new File([file], `${baseName}.${extension}`, {
          type: file.type,
          lastModified: file.lastModified,
        });
        onUploadImage(normalizedFile);
      } else {
        onUploadImage(file);
      }
      setShowMenu(false);
      event.target.value = '';
    }
  };

  // Show loading state (prioritize this over showing image during generation)
  if (isLoading && !!loadingType) {
    return (
      <div className='flex h-[80px] w-[48px] flex-shrink-0 flex-col items-center justify-center gap-2 rounded-lg bg-background-secondary'>
        <div className='h-6 w-6 animate-spin rounded-full border-2 border-foreground-inactive border-t-transparent' />
      </div>
    );
  }

  // Show image preview when image is loaded
  if (imageUrl) {
    return (
      <div className='relative h-[80px] w-[48px] flex-shrink-0'>
        <Tooltip
          label={
            <ImageWithFallback
              className='h-[360px] w-[203px] object-cover'
              src={imageUrl}
              alt='Start frame preview'
              imageSize={LARGE_IMAGE}
            />
          }
          placement='top'
          hasArrow
        >
          <ImageWithFallback
            className='h-full w-full object-cover'
            src={imageUrl}
            alt='Start frame preview'
            imageSize={SMALL_IMAGE}
          />
        </Tooltip>

        <Button
          className='absolute -top-2 -right-2'
          variant={ButtonVariant.Fog}
          size={ButtonSize.Micro}
          shape={ButtonShape.Pill}
          icon={CloseIcon}
          iconOnly
          onClick={onRemoveImage}
          aria-label='Remove start frame'
        />
      </div>
    );
  }

  // Show add button with dropdown menu
  return (
    <>
      <DropdownMenu.Root
        open={showMenu}
        onOpenChange={setShowMenu}
        modal={false}
      >
        <DropdownMenu.Trigger asChild>
          <button className='flex h-[80px] w-[48px] flex-shrink-0 flex-col items-center justify-center gap-2 rounded-lg bg-background-fog-thin transition-colors hover:bg-background-secondary'>
            <div className='relative'>
              <PhotoGalleryIcon className='h-8 w-8 text-foreground-inactive' />
              {/* Red plus badge */}
              <div className='absolute -top-1 -right-1 m-2 flex h-0 w-0 items-center justify-center rounded-full text-strawberry-600'>
                <span className='text-[20px] leading-none font-bold'>+</span>
              </div>
            </div>
          </button>
        </DropdownMenu.Trigger>

        <DropdownMenu.Portal>
          <DropdownMenu.Content
            className='z-[1401] min-w-[200px] rounded-lg border border-border-primary bg-background-tertiary p-2 shadow-2xl'
            sideOffset={5}
            align='start'
            side='top'
          >
            <p className='px-3 py-2 text-left text-sm font-medium text-foreground-secondary'>
              Add a starting frame
            </p>
            {/* Upload from Device */}
            <DropdownMenu.Item
              className='flex cursor-pointer items-center gap-2 rounded-lg px-3 py-2 text-sm text-foreground-primary outline-none hover:bg-background-secondary'
              onSelect={() => {
                fileInputRef.current?.click();
              }}
            >
              <UploadIcon className='h-4 w-4' />
              <span>Upload from device</span>
            </DropdownMenu.Item>
            {/* Use Existing Cover Art */}
            <DropdownMenu.Item
              className='flex cursor-pointer items-center gap-2 rounded-lg px-3 py-2 text-sm text-foreground-primary outline-none hover:bg-background-secondary'
              onSelect={onUseExistingCover}
            >
              <PhotoGalleryIcon className='h-4 w-4' />
              <span>Use existing cover art</span>
            </DropdownMenu.Item>
            {/* Generate Image from Song */}
            <DropdownMenu.Item
              className='flex cursor-pointer items-center gap-2 rounded-lg px-3 py-2 text-sm text-foreground-primary outline-none hover:bg-background-secondary'
              onSelect={onGenerateFromSong}
            >
              <SparklesIcon className='h-4 w-4' />
              <span>Generate image from song</span>
            </DropdownMenu.Item>
          </DropdownMenu.Content>
        </DropdownMenu.Portal>
      </DropdownMenu.Root>

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