"use client";

import React, { useRef, useState } from "react";
import { UploadCloud, FileSpreadsheet, X, Download } from "lucide-react";
import { cn } from "@/lib/utils";
import { toast } from "sonner";

interface FileDropzoneProps {
  onFileSelect: (file: File) => void;
  selectedFile?: File | null;
  onClearFile?: () => void;
  accept?: string;
  maxSizeBytes?: number; // default: 10MB
  sampleTemplateUrl?: string;
  title?: string;
  description?: string;
  className?: string;
}

export function FileDropzone({
  onFileSelect,
  selectedFile,
  onClearFile,
  accept = ".xlsx, .xls, .csv",
  maxSizeBytes = 10 * 1024 * 1024, // 10MB
  sampleTemplateUrl,
  title = "Upload Student Roster Spreadsheet",
  description = "Drag and drop your .xlsx or .csv file here, or click to browse",
  className,
}: FileDropzoneProps) {
  const [isDragging, setIsDragging] = useState(false);
  const inputRef = useRef<HTMLInputElement>(null);

  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault();
    setIsDragging(true);
  };

  const handleDragLeave = (e: React.DragEvent) => {
    e.preventDefault();
    setIsDragging(false);
  };

  const validateAndSelect = (file: File) => {
    if (file.size > maxSizeBytes) {
      toast.error(`File size exceeds maximum limit of ${(maxSizeBytes / (1024 * 1024)).toFixed(0)}MB.`);
      return;
    }
    const ext = file.name.split(".").pop()?.toLowerCase();
    if (!["xlsx", "xls", "csv"].includes(ext || "")) {
      toast.error("Invalid file format. Please upload an Excel (.xlsx/.xls) or CSV file.");
      return;
    }
    onFileSelect(file);
  };

  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault();
    setIsDragging(false);
    if (e.dataTransfer.files && e.dataTransfer.files[0]) {
      validateAndSelect(e.dataTransfer.files[0]);
    }
  };

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files[0]) {
      validateAndSelect(e.target.files[0]);
    }
  };

  return (
    <div className={cn("space-y-3", className)}>
      <div
        onDragOver={handleDragOver}
        onDragLeave={handleDragLeave}
        onDrop={handleDrop}
        onClick={() => inputRef.current?.click()}
        className={cn(
          "cursor-pointer rounded-lg border-2 border-dashed p-8 text-center transition-colors flex flex-col items-center justify-center gap-2",
          isDragging
            ? "border-blue-500 bg-blue-50/50 dark:bg-blue-950/20"
            : "border-slate-200 bg-slate-50/50 hover:bg-slate-50 hover:border-slate-300 dark:border-slate-800 dark:bg-slate-900/50 dark:hover:border-slate-700"
        )}
      >
        <input
          ref={inputRef}
          type="file"
          accept={accept}
          onChange={handleInputChange}
          className="hidden"
        />

        <div className="w-10 h-10 rounded-full bg-white border border-slate-200 flex items-center justify-center text-slate-700 shadow-sm dark:bg-slate-800 dark:border-slate-700 dark:text-slate-200">
          <UploadCloud className="w-5 h-5" />
        </div>

        <div>
          <h4 className="text-xs font-semibold text-slate-800 tracking-tight dark:text-slate-100">
            {title}
          </h4>
          <p className="text-[11px] text-slate-500 mt-0.5 max-w-sm">
            {description}
          </p>
        </div>
      </div>

      {/* Selected File Feedback & Sample Download */}
      <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-2 text-xs">
        {selectedFile ? (
          <div className="flex items-center gap-2 px-3 py-1.5 rounded border border-slate-200 bg-white dark:border-slate-800 dark:bg-slate-900">
            <FileSpreadsheet className="w-4 h-4 text-emerald-600" />
            <span className="font-medium text-slate-800 dark:text-slate-200 truncate max-w-xs">
              {selectedFile.name}
            </span>
            <span className="text-[10px] text-slate-400">
              ({(selectedFile.size / 1024).toFixed(1)} KB)
            </span>
            {onClearFile && (
              <button
                type="button"
                onClick={(e) => {
                  e.stopPropagation();
                  onClearFile();
                  if (inputRef.current) inputRef.current.value = "";
                }}
                className="text-slate-400 hover:text-rose-600 transition-colors p-0.5 rounded"
                aria-label="Remove selected file"
              >
                <X className="w-3.5 h-3.5" />
              </button>
            )}
          </div>
        ) : (
          <span className="text-[11px] text-slate-400">
            Supported formats: .xlsx, .xls, .csv (Max 10MB)
          </span>
        )}

        {sampleTemplateUrl && (
          <a
            href={sampleTemplateUrl}
            download
            className="inline-flex items-center gap-1.5 text-xs text-blue-600 hover:text-blue-800 font-medium transition-colors"
          >
            <Download className="w-3.5 h-3.5" />
            Download Excel Template
          </a>
        )}
      </div>
    </div>
  );
}
