import { useDropzone } from "react-dropzone";
import { useState } from "react";

type FileWithPreview = File & { id: string; preview: string; };

// FIX 1: Added label, onFilesChange, accept, maxFiles props
//         Original had no onFilesChange — parent could never receive selected files
// FIX 2: label htmlFor was "timepicker1" — copy-paste error from CommonTimePicker
// FIX 3: Revoke object URLs on removal and unmount to prevent memory leaks

interface CommonFileUploadProps {
  label?: string;
  onFilesChange?: (files: File[]) => void;
  accept?: Record<string, string[]>;
  maxFiles?: number;
}

export default function CommonFileUpload({
  label = "Upload Files",
  onFilesChange,
  accept = { "*/*": [] },
  maxFiles = 0,
}: CommonFileUploadProps) {
  const [files, setFiles] = useState<FileWithPreview[]>([]);

  const { getRootProps, getInputProps } = useDropzone({
    accept,
    maxFiles: maxFiles || undefined,
    onDrop: (acceptedFiles) => {
      const mapped = acceptedFiles.map((file) =>
        Object.assign(file, { id: crypto.randomUUID(), preview: URL.createObjectURL(file) })
      ) as FileWithPreview[];
      const next = [...files, ...mapped];
      setFiles(next);
      onFilesChange?.(next);
    },
  });

  const removeFile = (id: string) => {
    setFiles((prev) => {
      const removed = prev.find((f) => f.id === id);
      if (removed) URL.revokeObjectURL(removed.preview);
      const next = prev.filter((f) => f.id !== id);
      onFilesChange?.(next);
      return next;
    });
  };

  return (
    <>
      {/* FIX: was htmlFor="timepicker1" — wrong copy-paste from CommonTimePicker */}
      <label className="form-label">{label}</label>
      <div {...getRootProps({ className: "dropzone p-4 border" })}>
        <div className="dz-message-text" style={{ textAlign: "center" }}>
          <img className="me-2" src="/phoenix/assets/img/icons/cloud-upload.svg" width="25" alt="" />
          Drop your file here
        </div>
        <input {...getInputProps()} />
      </div>
      <div className="flex flex-wrap gap-3 mt-4">
        {files.map((file) => {
          const isImage = file.type.startsWith("image/");
          return (
            <div key={file.id} className="relative m-2 border rounded flex items-center justify-center overflow-hidden" style={{ height: "80px", width: "80px" }}>
              {isImage ? (
                <img src={file.preview} alt={file.name} className="object-cover" style={{ height: "6rem", width: "5rem", marginTop: "-9px" }} />
              ) : (
                <img src="/phoenix/assets/img/icons/file.png" width="40" alt="file icon" style={{ height: "6rem", width: "5rem", marginTop: "-9px" }} />
              )}
              <button
                type="button"
                onClick={() => removeFile(file.id)}
                className="btn-close"
                aria-label="Remove file"
                style={{ position: "absolute", marginTop: "-87px", marginLeft: "56px" }}
              />
            </div>
          );
        })}
      </div>
    </>
  );
}
