import React, { useMemo, useRef } from 'react';
import { useLocale } from '../../hooks/useLocale';
import './style.scss';

type DragAndDropUploadProps = {
  filesUploaded?: Array<File | { file?: File; data?: File; name?: string }>;
  onAdd?: (files: File[]) => void;
  isDisabled?: boolean;
  dropzoneText?: string;
};

export const DragAndDropUpload = ({ ...props }: DragAndDropUploadProps & Record<string, unknown>) => {
  const inputRef = useRef<HTMLInputElement>(null);
  const disabled = Boolean(props?.isDisabled);
  const dropzoneText = props?.dropzoneText || useLocale('draganddrop');

  const fileNames = useMemo(() => {
    const files = props?.filesUploaded || [];
    return files
      .map((item) => {
        if (item instanceof File) return item.name;
        if (item?.file instanceof File) return item.file.name;
        if (item?.data instanceof File) return item.data.name;
        return item?.name || '';
      })
      .filter(Boolean);
  }, [props?.filesUploaded]);

  const handleFiles = (files: FileList | null) => {
    if (!files || disabled) return;
    props?.onAdd?.(Array.from(files));
  };

  return (
    <div>
      <div
        className='draganddrop_gtc_controls'
        onClick={() => !disabled && inputRef.current?.click()}
        onDragOver={(event) => event.preventDefault()}
        onDrop={(event) => {
          event.preventDefault();
          handleFiles(event.dataTransfer.files);
        }}
      >
        {dropzoneText}
      </div>
      <input
        ref={inputRef}
        type='file'
        multiple
        style={{ display: 'none' }}
        disabled={disabled}
        onChange={(event) => handleFiles(event.target.files)}
      />
      {fileNames.length > 0 && (
        <ul className='draganddrop-file-list'>
          {fileNames.map((name) => (
            <li key={name}>{name}</li>
          ))}
        </ul>
      )}
    </div>
  );
};
