"use client";

import { useEffect, useRef, useState } from "react";
import { Button } from "@/components/ui/Button";
import { ExportScopeDialog } from "@/components/export/ExportScopeDialog";
import {
  downloadListExport,
  hasUserFilters,
  type ExportFormat,
} from "@/lib/export";

export function ListExportActions({
  exportPath,
  filters = {},
  contextKeys = [],
  filenameBase,
  disabled = false,
  onError,
}: {
  exportPath: string;
  filters?: Record<string, string | number | boolean | null | undefined>;
  contextKeys?: string[];
  filenameBase: string;
  disabled?: boolean;
  onError?: (message: string) => void;
}) {
  const [loadingFormat, setLoadingFormat] = useState<ExportFormat | null>(null);
  const [pendingFormat, setPendingFormat] = useState<ExportFormat | null>(null);
  const [menuOpen, setMenuOpen] = useState(false);
  const rootRef = useRef<HTMLDivElement>(null);
  const filtered = hasUserFilters(filters, contextKeys);

  useEffect(() => {
    if (!menuOpen) return;
    const onDocClick = (e: MouseEvent) => {
      if (!rootRef.current?.contains(e.target as Node)) setMenuOpen(false);
    };
    const onKey = (e: KeyboardEvent) => {
      if (e.key === "Escape") setMenuOpen(false);
    };
    document.addEventListener("mousedown", onDocClick);
    document.addEventListener("keydown", onKey);
    return () => {
      document.removeEventListener("mousedown", onDocClick);
      document.removeEventListener("keydown", onKey);
    };
  }, [menuOpen]);

  const runExport = async (format: ExportFormat, scope: "filtered" | "all") => {
    setLoadingFormat(format);
    try {
      await downloadListExport(exportPath, filters, format, scope, filenameBase);
    } catch (err) {
      onError?.(err instanceof Error ? err.message : "خطا در تهیه خروجی");
    } finally {
      setLoadingFormat(null);
      setPendingFormat(null);
    }
  };

  const handleClick = (format: ExportFormat) => {
    setMenuOpen(false);
    if (filtered) {
      setPendingFormat(format);
      return;
    }
    void runExport(format, "filtered");
  };

  const formatLabel = pendingFormat === "pdf" ? "PDF" : "اکسل";

  return (
    <>
      <div ref={rootRef} className="relative">
        <Button
          type="button"
          variant="secondary"
          disabled={disabled || loadingFormat !== null}
          loading={loadingFormat !== null}
          aria-haspopup="menu"
          aria-expanded={menuOpen}
          onClick={() => setMenuOpen((open) => !open)}
          className="gap-2"
        >
          <svg viewBox="0 0 20 20" className="h-4 w-4 shrink-0" fill="currentColor" aria-hidden>
            <path d="M10.75 2.75a.75.75 0 00-1.5 0v8.69L6.72 8.91a.75.75 0 10-1.06 1.06l3.81 3.81a.75.75 0 001.06 0l3.81-3.81a.75.75 0 10-1.06-1.06l-2.53 2.53V2.75z" />
            <path d="M3.5 13.75a.75.75 0 00-1.5 0v1.5A2.75 2.75 0 004.75 18h10.5A2.75 2.75 0 0018 15.25v-1.5a.75.75 0 00-1.5 0v1.5c0 .69-.56 1.25-1.25 1.25H4.75c-.69 0-1.25-.56-1.25-1.25v-1.5z" />
          </svg>
          دریافت خروجی
          <svg viewBox="0 0 20 20" className="h-4 w-4 shrink-0" fill="currentColor" aria-hidden>
            <path
              fillRule="evenodd"
              d="M5.23 7.21a.75.75 0 011.06.02L10 11.17l3.71-3.94a.75.75 0 111.08 1.04l-4.25 4.5a.75.75 0 01-1.08 0l-4.25-4.5a.75.75 0 01.02-1.06z"
              clipRule="evenodd"
            />
          </svg>
        </Button>

        {menuOpen ? (
          <div
            role="menu"
            className="absolute top-full z-30 mt-1 min-w-full overflow-hidden rounded-xl border border-[var(--border)] bg-white py-1 text-sm shadow-lg"
          >
            <button
              type="button"
              role="menuitem"
              className="block w-full px-4 py-2 text-right hover:bg-slate-50"
              onClick={() => handleClick("xlsx")}
            >
              فایل اکسل (Excel)
            </button>
            <button
              type="button"
              role="menuitem"
              className="block w-full px-4 py-2 text-right hover:bg-slate-50"
              onClick={() => handleClick("pdf")}
            >
              فایل پی دی اف (PDF)
            </button>
          </div>
        ) : null}
      </div>

      <ExportScopeDialog
        open={pendingFormat !== null}
        formatLabel={formatLabel}
        loading={loadingFormat !== null}
        onCancel={() => setPendingFormat(null)}
        onChoose={(scope) => {
          if (pendingFormat) void runExport(pendingFormat, scope);
        }}
      />
    </>
  );
}
