import { cn } from '@/lib/utils';
import { ImageIcon } from '@phosphor-icons/react';
import { useState } from 'react';
import { useDropzone } from 'react-dropzone';
import { useTranslation } from 'react-i18next';

export function FileInput({
  defaultValue,
  onChange,
  className,
  disabled = false,
  id,
}: {
  defaultValue?: string;
  onChange: (file: File) => void;
  className?: string;
  disabled?: boolean;
  id?: string;
}) {
  const [localPreview, setLocalPreview] = useState<string>();
  const [prevDefault, setPrevDefault] = useState(defaultValue);
  const { t } = useTranslation();

  if (prevDefault !== defaultValue) {
    setPrevDefault(defaultValue);
    // Only clear local preview when the parent sets a new explicit URL.
    // When defaultValue becomes undefined (field changed to a File), keep the local preview.
    if (defaultValue !== undefined) {
      setLocalPreview(undefined);
    }
  }

  const preview = localPreview ?? defaultValue;

  const { getRootProps, getInputProps, isDragActive } = useDropzone({
    onDrop: (files: File[]) => {
      const file = files?.[0];
      if (file) {
        onChange(file);
        setLocalPreview(URL.createObjectURL(file));
      }
    },
    disabled,
  });

  return (
    <div
      {...getRootProps({
        className: cn(
          'relative h-40 w-full flex-col overflow-hidden rounded-md border border-black/5 bg-black/5 p-4',
          isDragActive && 'ring-1 ring-ring outline-none',
          className,
        ),
      })}
    >
      {!!preview && (
        <img
          src={preview}
          alt="preview"
          className="pointer-events-none absolute inset-0 top-0 left-0 h-full w-full object-contain"
        />
      )}
      <input id={id} {...getInputProps()} />
      {!preview && (
        <div className="flex h-full flex-col items-center justify-center gap-2.5">
          <ImageIcon
            weight="fill"
            className="size-10 text-black/50 dark:text-white/30"
          />
          <p className="text-sm font-medium text-wrap">
            {t('Drag and drop file here or upload')}
          </p>
        </div>
      )}
    </div>
  );
}
