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

const btnClass = (disabled = false) =>
  disabled
    ? "inline-flex items-center gap-2 rounded-lg border border-border bg-muted px-3 py-1.5 text-xs font-medium text-muted-foreground cursor-not-allowed shadow-sm"
    : "inline-flex items-center gap-2 rounded-lg border border-primary/40 bg-card px-3 py-1.5 text-xs font-semibold text-foreground shadow-sm hover:-translate-y-0.5 hover:border-primary hover:bg-primary 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, error, 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: DownloadFormat) => {
    setIsDropdownOpen(false);
    handleDownload(format, endpoint, filenamePrefix, body);
  };

  return (
    <div className={`${className} flex flex-col items-end gap-2`}>
      {error && (
        <p role="alert" className="text-xs font-medium text-destructive">
          {error}
        </p>
      )}
      <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-border bg-card shadow-xl z-50">
            <button
              onClick={() => onDownload("pdf")}
              className="flex w-full items-center gap-3 px-4 py-3 text-sm text-foreground hover:bg-primary/10 hover:text-primary transition-colors border-b border-border 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-foreground hover:bg-primary/10 hover:text-primary transition-colors last:rounded-b-lg"
            >
              <Download className="h-4 w-4" />
              Download as Excel
            </button>
          </div>
        )}
      </div>
    </div>
  );
}
