import { useState, useEffect, useRef } from "react";
import { RefreshCw, Download, ChevronDown } from "lucide-react";
import { useDownload } from "@/hooks/useDownload";

const btnClass = (disabled = false) =>
  disabled
    ? "inline-flex items-center gap-2 rounded-lg border border-gray-200 bg-gray-100 px-3 py-1.5 text-xs font-medium text-gray-500 cursor-not-allowed shadow-sm"
    : "inline-flex items-center gap-2 rounded-lg border border-[#428B4D]/40 bg-white px-3 py-1.5 text-xs font-semibold text-slate-700 shadow-sm hover:-translate-y-0.5 hover:border-[#428B4D] hover:bg-[#428B4D] hover:text-white active:scale-95 transition-all duration-200";

interface DownloadButtonProps {
  endpoint: string;
  filenamePrefix?: string;
  body?: Record<string, unknown>;
  className?: string;
}

export function DownloadButton({ endpoint, filenamePrefix = "OXYFINZ-Report", body, className = "mt-8 mb-4" }: DownloadButtonProps) {
  const [isDropdownOpen, setIsDropdownOpen] = useState(false);
  const dropdownRef = useRef<HTMLDivElement>(null);
  const { downloadingFormat, handleDownload } = useDownload();

  useEffect(() => {
    const handleClickOutside = (e: MouseEvent) => {
      if (dropdownRef.current && !dropdownRef.current.contains(e.target as Node)) {
        setIsDropdownOpen(false);
      }
    };
    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);

  const onDownload = (format: "pdf" | "excel") => {
    setIsDropdownOpen(false);
    handleDownload(format, `${endpoint}/${format}`, filenamePrefix, body);
  };

  return (
    <div className={`${className} flex justify-end`}>
      <div className="relative" ref={dropdownRef}>
        <button
          type="button"
          onClick={() => setIsDropdownOpen(v => !v)}
          disabled={!!downloadingFormat}
          className={btnClass(!!downloadingFormat)}
        >
          {downloadingFormat ? (
            <>
              <RefreshCw className="h-4 w-4 animate-spin" />
              Downloading {downloadingFormat.toUpperCase()}...
            </>
          ) : (
            <>
              <Download className="h-4 w-4" />
              Download
              <ChevronDown className={`h-4 w-4 ml-1 transition-transform ${isDropdownOpen ? "rotate-180" : ""}`} />
            </>
          )}
        </button>

        {isDropdownOpen && !downloadingFormat && (
          <div className="absolute right-0 top-full mt-2 w-48 rounded-lg border border-slate-200 bg-white shadow-xl z-50">
            <button
              onClick={() => onDownload("pdf")}
              className="flex w-full items-center gap-3 px-4 py-3 text-sm text-slate-700 hover:bg-[#428B4D]/10 hover:text-[#428B4D] transition-colors border-b border-slate-100 first:rounded-t-lg"
            >
              <Download className="h-4 w-4" />
              Download as PDF
            </button>
            <button
              onClick={() => onDownload("excel")}
              className="flex w-full items-center gap-3 px-4 py-3 text-sm text-slate-700 hover:bg-[#428B4D]/10 hover:text-[#428B4D] transition-colors last:rounded-b-lg"
            >
              <Download className="h-4 w-4" />
              Download as Excel
            </button>
          </div>
        )}
      </div>
    </div>
  );
}
