"use client";

import React, { useCallback, useState } from "react";
import { useDropzone } from "react-dropzone";

interface FileUploadProps {
  onFilesAdded: (files: File[]) => void;
  accept?: Record<string, string[]>;
  maxSize?: number;
  label?: string;
  maxFiles?: number;
}

export function FileUpload({
  onFilesAdded,
  accept = {
    "image/*": [".jpeg", ".png", ".jpg", ".webp"],
    "application/pdf": [".pdf"],
  },
  maxSize = 5242880, // 5MB
  label = "Arrastra y suelta tus archivos aquí, o haz clic para seleccionar",
  maxFiles = 1,
}: FileUploadProps) {
  const [files, setFiles] = useState<File[]>([]);

  const onDrop = useCallback(
    (acceptedFiles: File[]) => {
      setFiles(acceptedFiles);
      onFilesAdded(acceptedFiles);
    },
    [onFilesAdded]
  );

  const { getRootProps, getInputProps, isDragActive, isDragReject } = useDropzone({
    onDrop,
    accept,
    maxSize,
    maxFiles,
  });

  return (
    <div className="w-full">
      <div
        {...getRootProps()}
        className={`relative flex flex-col items-center justify-center w-full h-40 border-2 border-dashed rounded-lg cursor-pointer transition-colors
          ${isDragActive ? "border-blue-500 bg-blue-50" : "border-gray-300 bg-gray-50"}
          ${isDragReject ? "border-red-500 bg-red-50" : ""}
          hover:bg-gray-100 hover:border-gray-400`}
      >
        <input {...getInputProps()} />
        <div className="flex flex-col items-center justify-center pt-5 pb-6 text-gray-500">
          <svg className="w-8 h-8 mb-4" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 20 16">
            <path stroke="currentColor" strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M13 13h3a3 3 0 0 0 0-6h-.025A5.56 5.56 0 0 0 16 6.5 5.5 5.5 0 0 0 5.207 5.021C5.137 5.017 5.071 5 5 5a4 4 0 0 0 0 8h2.167M10 15V6m0 0L8 8m2-2 2 2" />
          </svg>
          <p className="mb-2 text-sm font-semibold">
            {isDragActive ? "Suelta los archivos aquí..." : label}
          </p>
          <p className="text-xs text-gray-400">
            Imágenes (PNG, JPG) o PDFs (Máx {(maxSize / 1024 / 1024).toFixed(0)}MB)
          </p>
        </div>
      </div>

      {files.length > 0 && (
        <div className="mt-4">
          <h4 className="text-sm font-medium text-gray-700 mb-2">Archivos seleccionados:</h4>
          <ul className="space-y-2">
            {files.map((file, idx) => (
              <li key={idx} className="text-sm text-gray-600 bg-white p-2 border border-gray-200 rounded flex justify-between items-center shadow-sm">
                <span className="truncate max-w-[80%]">{file.name}</span>
                <span className="text-xs font-semibold">{(file.size / 1024).toFixed(1)} KB</span>
              </li>
            ))}
          </ul>
        </div>
      )}
    </div>
  );
}
