"use client";

import { useState } from "react";
import { FileDown, FileSpreadsheet, FileText, Loader2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { useToast } from "@/hooks/use-toast";
import { apiErrorMessage } from "@/lib/store/api-call";
import {
  exportUserDetailData,
  type UserDetailExportSection,
  type UserDetailExportUser,
} from "@/lib/user-detail-export";
import type { ExportFormat } from "@/lib/export-workbook";

const FORMATS: { format: ExportFormat; label: string; icon: typeof FileSpreadsheet }[] = [
  { format: "xlsx", label: "Excel (.xlsx)", icon: FileSpreadsheet },
  { format: "csv", label: "CSV (.csv)", icon: FileText },
  { format: "pdf", label: "PDF (.pdf)", icon: FileText },
];

const SECTION_LABEL: Record<UserDetailExportSection, string> = {
  "report-card": "Report Card",
  performance: "Performance",
  "logged-hours": "Work Summary",
  "work-history": "Work History",
  attendance: "Attendance",
  all: "all data",
};

interface UserDetailExportMenuProps {
  user: UserDetailExportUser;
  dateFrom: string;
  dateTo: string;
  section: UserDetailExportSection;
  variant?: "default" | "all";
}

export function UserDetailExportMenu({
  user,
  dateFrom,
  dateTo,
  section,
  variant = "default",
}: UserDetailExportMenuProps) {
  const { toast } = useToast();
  const [exporting, setExporting] = useState<ExportFormat | null>(null);

  const handleExport = async (format: ExportFormat) => {
    if (exporting) return;
    setExporting(format);
    try {
      await exportUserDetailData({ user, dateFrom, dateTo, section, format });
      toast({
        title: "Export ready",
        description: `${SECTION_LABEL[section]} downloaded as ${format.toUpperCase()} for ${dateFrom} to ${dateTo}.`,
      });
    } catch (error) {
      toast({
        title: "Export failed",
        description: apiErrorMessage(error, "Could not export this tab. Try again."),
        variant: "destructive",
      });
    } finally {
      setExporting(null);
    }
  };

  const isAll = variant === "all";

  return (
    <DropdownMenu>
      <DropdownMenuTrigger asChild>
        <Button
          variant={isAll ? "default" : "outline"}
          size="sm"
          className="h-8 shrink-0"
          disabled={!!exporting}
        >
          {exporting ? (
            <Loader2 className="h-3.5 w-3.5 mr-1.5 animate-spin" />
          ) : (
            <FileDown className="h-3.5 w-3.5 mr-1.5" />
          )}
          {exporting ? "Exporting…" : isAll ? "Export all data" : "Export"}
        </Button>
      </DropdownMenuTrigger>
      <DropdownMenuContent align="end" className="w-48">
        <DropdownMenuLabel className="text-xs text-muted-foreground font-normal">
          {isAll ? "All tabs" : SECTION_LABEL[section]} · {dateFrom} to {dateTo}
        </DropdownMenuLabel>
        <DropdownMenuSeparator />
        {FORMATS.map(({ format, label, icon: Icon }) => (
          <DropdownMenuItem
            key={format}
            disabled={!!exporting}
            onSelect={() => {
              void handleExport(format);
            }}
          >
            <Icon className="h-4 w-4 mr-2 text-muted-foreground" />
            {label}
          </DropdownMenuItem>
        ))}
      </DropdownMenuContent>
    </DropdownMenu>
  );
}
