"use client";

import React, { useState, useCallback } from "react";
import { useDropzone } from "react-dropzone";
import { PRIMARY_COLOR } from "@/lib/common";

interface FileUploaderProps {
  label?: string;
  onFileChange: (file: File | null) => void;
  maxSizeMB?: number;
  allowedTypes?: string[];
  referenceLink?: string;
  containerClass?: string;
}

const defaultAllowedTypes = ["application/pdf", "image/png", "image/jpg", "image/jpeg"];

export const FileUploader: React.FC<FileUploaderProps> = ({
  label,
  onFileChange,
  maxSizeMB = 1,
  allowedTypes = defaultAllowedTypes,
  referenceLink,
  containerClass = "",
}) => {
  const [error, setError] = useState<string | null>(null);
  const [fileName, setFileName] = useState<string | null>(null);

  const onDrop = useCallback(
    (acceptedFiles: File[]) => {
      const file = acceptedFiles[0];

      if (!file) return;

      // Validate type
      if (!allowedTypes.includes(file.type)) {
        setError(`Invalid file type. Allowed: ${allowedTypes.join(", ")}`);
        setFileName(null);
        onFileChange(null);
        return;
      }

      // Validate size
      const maxBytes = maxSizeMB * 1024 * 1024;
      if (file.size > maxBytes) {
        setError(`File too large. Max size: ${maxSizeMB} MB`);
        setFileName(null);
        onFileChange(null);
        return;
      }

      setError(null);
      setFileName(file.name);
      onFileChange(file);
    },
    [allowedTypes, maxSizeMB, onFileChange]
  );

  const { getRootProps, getInputProps, isDragActive } = useDropzone({
    onDrop,
    multiple: false,
    accept: allowedTypes.reduce((acc, type) => ({ ...acc, [type]: [] }), {}), // required by react-dropzone
  });

  return (
    <div className={`flex flex-col ${containerClass}`}>
      {label && <label className="mb-2 font-medium text-gray-700">{label}</label>}

      <div
        {...getRootProps()}
        className={`border-2 border-dashed rounded-lg p-6 text-center cursor-pointer transition-colors
          ${isDragActive ? "bg-opacity-10" : "border-gray-300 bg-gray-50"}`}
        style={isDragActive ? {
          borderColor: PRIMARY_COLOR,
          backgroundColor: `${PRIMARY_COLOR}1A`,
        } : {}}
      >
        <input {...getInputProps()} />
        {isDragActive ? (
          <p className="text-gray-700">Drop the file here...</p>
        ) : (
          <p className="text-gray-600">
            Drag & drop a file here, or click to select
            <br />
            <span className="text-sm text-gray-500">(Max {maxSizeMB} MB, {allowedTypes.map(t => t.split("/")[1]).join(", ")})</span>
          </p>
        )}
      </div>

      {fileName && !error && <p className="mt-2 text-green-600 text-sm">Selected file: {fileName}</p>}
      {error && <p className="mt-2 text-red-500 text-sm">{error}</p>}

      {referenceLink && (
        <a
          href={referenceLink}
          target="_blank"
          rel="noopener noreferrer"
          className="mt-2 text-sm text-blue-600 hover:underline"
        >
          Reference Link
        </a>
      )}
    </div>
  );
};
