"use client";

import { isApiSuccess } from "@/lib/api-messages";
import { toast } from "sonner";
import { useRouter } from "next/navigation";
import { useTransition } from "react";
import { Loader2 } from "lucide-react";
import { requestDashboardApi } from "@/lib/dashboard-api-client";
import { DataTableHeaderActions, downloadCsv } from "@/app/dashboard/_components/data-table";
import { Button } from "@/components/ui/button";

import type { UniqueIsinRow } from "./schema";
const ACCUMULATOR_LIVE_HREF = "/dashboard/master-table/unique-isin/accumulator-live";
const STRUCTURE_LIVE_HREF = "/dashboard/master-table/unique-isin/structure-live";




function exportUniqueIsinCsv(rows: UniqueIsinRow[]) {
  downloadCsv({
    filename: "unique-isin",
    headers: ["ISIN"],
    rows,
    toRow: (row) => [row.isin],
  });
}

type UniqueIsinHeaderActionsProps = {
  data: UniqueIsinRow[];
};

export function UniqueIsinHeaderActions({ data }: UniqueIsinHeaderActionsProps) {
  const [isAccumulatorPending, startAccumulatorTransition] = useTransition();
  const [isStructurePending, startStructureTransition] = useTransition();
  const router = useRouter();
  const [isPending, startTransition] = useTransition();

  const handleUpdateAccumulatorLive = () => {
    startTransition(async () => {
      try {
        const result = await requestDashboardApi<{ status?: string; message?: string }>({    
          url: ACCUMULATOR_LIVE_HREF,
            method: "POST",
            fallbackError: "Could not update accumulator live.",
            validate: (payload) => isApiSuccess(payload),
          });
      }
      catch (error) {
        toast.error(
          error instanceof Error ? error.message : "Could not update accumulator live.",
        );
      }
    });
  };

  const handleUpdateStructureLive = () => {
    startStructureTransition(async () => {
      try {
        const result = await requestDashboardApi<{ status?: string; message?: string }>({
          url: STRUCTURE_LIVE_HREF,
          method: "POST",
          fallbackError: "Could not update structure live.",
          validate: (payload) => isApiSuccess(payload),
        });
        toast.success(result.message ?? "Structure live updated.");
        router.refresh();
      } catch (error) {
        toast.error(
          error instanceof Error ? error.message : "Could not update structure live.",
        );
      }
    });
  };

  return (
    <DataTableHeaderActions
      exportLabel="Export CSV"
      onExport={() => exportUniqueIsinCsv(data)}
      prefixActions={
        <>
          <Button
            variant="outline"
            size="sm"
            onClick={handleUpdateAccumulatorLive}
            disabled={isPending}
          >
            {isPending ? <Loader2 className="h-4 w-4 animate-spin" /> : "Update accumulator live"}
          </Button>
          <Button
            variant="outline"
            size="sm"
            className="gap-1.5 border-emerald-600 text-emerald-800 hover:bg-emerald-50"
            onClick={handleUpdateStructureLive}
            disabled={isStructurePending}
          >
            {isStructurePending ? (
              <Loader2 className="h-4 w-4 animate-spin" />
            ) : (
              "Update structure live"
            )}
          </Button>
        </>
      }
    />
  );
}
