import { Controller, Control, FieldError } from "react-hook-form";
import { useState } from "react";

interface FormMultipleFileUploadProps {
  name: string;
  control: Control<any>;
  label: string;
  required?: boolean;
  disabled?: boolean;
  error?: FieldError;
  accept?: string;
  maxFiles?: number;
  className?: string;
}

export default function FormMultipleFileUpload({
  name,
  control,
  label,
  required,
  disabled,
  error,
  accept = ".pdf,.doc,.docx,.jpg,.jpeg,.png",
  maxFiles = 10,
  className = "",
}: FormMultipleFileUploadProps) {
  const [fileNames, setFileNames] = useState<string[]>([]);

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>, field: any) => {
    const files = e.target.files;
    if (files) {
      const newFiles = Array.from(files);
      const currentFiles = field.value || [];
      const totalFiles = currentFiles.length + newFiles.length;

      if (totalFiles > maxFiles) {
        alert(`Maximum ${maxFiles} files allowed`);
        return;
      }

      const updatedFiles = [...currentFiles, ...newFiles];
      field.onChange(updatedFiles);
      setFileNames(updatedFiles.map((f: File) => f.name));
    }
  };

  const removeFile = (index: number, field: any) => {
    const updatedFiles = field.value.filter((_: File, i: number) => i !== index);
    field.onChange(updatedFiles);
    setFileNames(updatedFiles.map((f: File) => f.name));
  };

  return (
    <div>
      <label className="text-sm font-medium text-gray-700 mb-1 block">
        {label}
        {required && <span className="text-red-500">*</span>}
      </label>
      <Controller
        name={name}
        control={control}
        render={({ field }) => (
          <>
            <label
              className={`flex items-center justify-between cursor-pointer rounded-lg border-2 border-dashed px-4 py-6 text-sm transition-colors ${
                disabled
                  ? "bg-gray-50 border-gray-200 cursor-not-allowed"
                  : error
                    ? "border-red-300 bg-red-50 hover:border-red-400"
                    : "border-gray-300 bg-gray-50 hover:border-teal-500"
              } ${className}`}
            >
              <span className={disabled ? "text-gray-500" : "text-teal-600"}>
                {field.value?.length > 0
                  ? `${field.value.length} file(s) selected`
                  : "Upload Documents"}
              </span>
              <svg
                className={`w-5 h-5 ${disabled ? "text-gray-400" : "text-teal-600"}`}
                fill="none"
                stroke="currentColor"
                strokeWidth="2"
                viewBox="0 0 24 24"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  d="M12 16v-8m0 0l-3 3m3-3l3 3M4 16v2a2 2 0 002 2h12a2 2 0 002-2v-2"
                />
              </svg>
              <input
                type="file"
                className="hidden"
                disabled={disabled}
                accept={accept}
                multiple
                onChange={(e) => handleFileChange(e, field)}
              />
            </label>

            {field.value?.length > 0 && (
              <div className="mt-4 space-y-2">
                <p className="text-sm font-medium text-gray-700">
                  Selected Files ({field.value.length}/{maxFiles}):
                </p>
                <div className="space-y-2">
                  {field.value.map((file: File, index: number) => (
                    <div
                      key={index}
                      className="flex items-center justify-between bg-gray-50 p-3 rounded-lg border border-gray-200"
                    >
                      <div className="flex items-center gap-2 flex-1 min-w-0">
                        <svg
                          className="w-4 h-4 text-gray-400 flex-shrink-0"
                          fill="currentColor"
                          viewBox="0 0 20 20"
                        >
                          <path
                            fillRule="evenodd"
                            d="M8 16.5a1 1 0 01-1-1V9.707l-2.146 2.147a1 1 0 01-1.414-1.414l4-4a1 1 0 011.414 0l4 4a1 1 0 01-1.414 1.414L9 9.707V15.5a1 1 0 01-1 1z"
                            clipRule="evenodd"
                          />
                        </svg>
                        <div className="flex-1 min-w-0">
                          <p className="text-sm text-gray-700 truncate">
                            {file.name}
                          </p>
                          <p className="text-xs text-gray-500">
                            {(file.size / 1024 / 1024).toFixed(2)} MB
                          </p>
                        </div>
                      </div>
                      <button
                        type="button"
                        onClick={() => removeFile(index, field)}
                        className="ml-2 text-red-500 hover:text-red-700 flex-shrink-0"
                      >
                        <svg
                          className="w-4 h-4"
                          fill="currentColor"
                          viewBox="0 0 20 20"
                        >
                          <path
                            fillRule="evenodd"
                            d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z"
                            clipRule="evenodd"
                          />
                        </svg>
                      </button>
                    </div>
                  ))}
                </div>
              </div>
            )}
          </>
        )}
      />
      {error && (
        <p className="text-red-500 text-xs mt-1">{error.message}</p>
      )}
    </div>
  );
}
