"use client";

import { useState } from "react";
import { FileDown, Loader2 } from "lucide-react";
import { useExport } from "@/hooks/useExport";
import { Toast } from "@/components/Toast";

export function ExportPanel() {
  const { exportSnapshot, exportAuditTrail, isLoading, error } = useExport();
  const [successMessage, setSuccessMessage] = useState<string | null>(null);

  const handleExportSnapshot = async (format: "csv" | "xlsx") => {
    try {
      setSuccessMessage(null);
      await exportSnapshot(format);
      const formatName = format === "csv" ? "CSV" : "Excel";
      setSuccessMessage(`Inventory snapshot exported as ${formatName}`);
      setTimeout(() => setSuccessMessage(null), 4000);
    } catch (err) {
      // Error handled by useExport hook
    }
  };

  const handleExportAuditTrail = async (format: "csv" | "xlsx") => {
    try {
      setSuccessMessage(null);
      await exportAuditTrail(format);
      const formatName = format === "csv" ? "CSV" : "Excel";
      setSuccessMessage(`Audit trail exported as ${formatName}`);
      setTimeout(() => setSuccessMessage(null), 4000);
    } catch (err) {
      // Error handled by useExport hook
    }
  };

  return (
    <div className="space-y-6">
      <div className="rounded-lg border border-slate-200 bg-white p-6">
        <div className="mb-6 flex items-center gap-3">
          <div className="rounded-lg bg-primary/10 p-4 border border-primary/20">
            <FileDown className="text-primary" size={24} />
          </div>
          <div>
            <h2 className="text-2xl font-normal">Export & Reports</h2>
            <p className="text-xs text-slate-500">
              Download inventory snapshots and audit trails in CSV or Excel formats
            </p>
          </div>
        </div>

        {/* Inventory Snapshot Section */}
        <div className="mb-8 space-y-3">
          <h3 className="font-normal text-slate-700">Inventory Snapshot</h3>
          <p className="text-sm text-slate-500">
            Export current inventory state with all item details
          </p>
          <div className="flex flex-col gap-2 sm:flex-row">
            <button
              onClick={() => handleExportSnapshot("csv")}
              disabled={isLoading}
              className="flex items-center justify-center gap-2 rounded-md bg-blue-500 px-4 py-2 text-sm font-normal text-white hover:bg-blue-600 disabled:bg-slate-400 disabled:cursor-not-allowed transition-colors"
              aria-label="Export inventory snapshot as CSV"
            >
              {isLoading ? (
                <Loader2 size={16} className="animate-spin" />
              ) : (
                <FileDown size={16} />
              )}
              {isLoading ? "Exporting..." : "Export as CSV"}
            </button>
            <button
              onClick={() => handleExportSnapshot("xlsx")}
              disabled={isLoading}
              className="flex items-center justify-center gap-2 rounded-md bg-green-500 px-4 py-2 text-sm font-normal text-white hover:bg-green-600 disabled:bg-slate-400 disabled:cursor-not-allowed transition-colors"
              aria-label="Export inventory snapshot as Excel"
            >
              {isLoading ? (
                <Loader2 size={16} className="animate-spin" />
              ) : (
                <FileDown size={16} />
              )}
              {isLoading ? "Exporting..." : "Export as Excel"}
            </button>
          </div>
        </div>

        {/* Audit Trail Section */}
        <div className="space-y-3">
          <h3 className="font-normal text-slate-700">Audit Trail</h3>
          <p className="text-sm text-slate-500">
            Export complete audit log of all system actions and changes
          </p>
          <div className="flex flex-col gap-2 sm:flex-row">
            <button
              onClick={() => handleExportAuditTrail("csv")}
              disabled={isLoading}
              className="flex items-center justify-center gap-2 rounded-md bg-blue-500 px-4 py-2 text-sm font-normal text-white hover:bg-blue-600 disabled:bg-slate-400 disabled:cursor-not-allowed transition-colors"
              aria-label="Export audit trail as CSV"
            >
              {isLoading ? (
                <Loader2 size={16} className="animate-spin" />
              ) : (
                <FileDown size={16} />
              )}
              {isLoading ? "Exporting..." : "Export as CSV"}
            </button>
            <button
              onClick={() => handleExportAuditTrail("xlsx")}
              disabled={isLoading}
              className="flex items-center justify-center gap-2 rounded-md bg-green-500 px-4 py-2 text-sm font-normal text-white hover:bg-green-600 disabled:bg-slate-400 disabled:cursor-not-allowed transition-colors"
              aria-label="Export audit trail as Excel"
            >
              {isLoading ? (
                <Loader2 size={16} className="animate-spin" />
              ) : (
                <FileDown size={16} />
              )}
              {isLoading ? "Exporting..." : "Export as Excel"}
            </button>
          </div>
        </div>
      </div>

      {/* Status Messages */}
      {error && (
        <Toast
          type="error"
          message={`Export failed: ${error}`}
          onClose={() => {}}
        />
      )}
      {successMessage && (
        <Toast type="success" message={successMessage} onClose={() => {}} />
      )}
    </div>
  );
}
