"use client";
import { useState } from "react";
import { Download } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
} from "@/components/ui/dialog";
import { exportRecords, type ExportFormat } from "@/lib/export";
type RecordOption = {
  id: string;
  label: string;
  data: Record<string, unknown>;
};
export function TableExport({
  title,
  filename,
  records,
  pageIds,
}: {
  title: string;
  filename?: string;
  records: RecordOption[];
  pageIds: string[];
}) {
  const [open, setOpen] = useState(false),
    [format, setFormat] = useState<ExportFormat>("csv"),
    [scope, setScope] = useState<"page" | "all" | "selected">("page"),
    [selected, setSelected] = useState<string[]>([]),
    [error, setError] = useState(""),
    [busy, setBusy] = useState(false),
    [notice, setNotice] = useState("");
  const result = records.filter(
    (row) =>
      scope === "all" ||
      (scope === "page" ? pageIds : selected).includes(row.id),
  );
  return (
    <>
      <Button
        variant="outline"
        size="icon"
        aria-label={`Export ${title}`}
        onClick={() => {
          setError("");
          setOpen(true);
        }}
      >
        <Download className="size-4" />
      </Button>
      {notice && (
        <span role="status" className="sr-only">
          {notice}
        </span>
      )}
      <Dialog
        open={open}
        onOpenChange={(next) => {
          if (!busy) setOpen(next);
        }}
      >
        <DialogContent className="max-h-[90dvh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>Download {title}</DialogTitle>
            <DialogDescription>
              Export fixture records only. No external service is contacted.
            </DialogDescription>
          </DialogHeader>
          <fieldset>
            <legend className="field-label">File Type</legend>
            <div className="flex flex-wrap gap-2">
              {(
                [
                  { value: "csv", label: "CSV" },
                  { value: "xlsx", label: "Excel" },
                  { value: "pdf", label: "PDF" },
                ] as const
              ).map((option) => (
                <Button
                  key={option.value}
                  variant={format === option.value ? "default" : "outline"}
                  aria-pressed={format === option.value}
                  onClick={() => setFormat(option.value)}
                >
                  {option.label}
                </Button>
              ))}
            </div>
          </fieldset>
          <fieldset>
            <legend className="field-label">Select Data</legend>
            <div className="flex flex-wrap gap-2">
              {(
                [
                  { value: "page", label: "Current Page" },
                  { value: "all", label: "All Filtered Records" },
                  { value: "selected", label: "Select Records" },
                ] as const
              ).map((option) => (
                <Button
                  key={option.value}
                  variant={scope === option.value ? "default" : "outline"}
                  aria-pressed={scope === option.value}
                  onClick={() => setScope(option.value)}
                >
                  {option.label}
                </Button>
              ))}
            </div>
          </fieldset>
          {scope === "selected" && (
            <div className="max-h-52 divide-y overflow-y-auto rounded-lg border">
              {records.map((row) => (
                <label
                  key={row.id}
                  className="flex items-center gap-3 p-3 text-sm"
                >
                  <input
                    type="checkbox"
                    checked={selected.includes(row.id)}
                    onChange={(e) =>
                      setSelected((all) =>
                        e.target.checked
                          ? [...all, row.id]
                          : all.filter((id) => id !== row.id),
                      )
                    }
                  />
                  {row.label}
                </label>
              ))}
            </div>
          )}
          <p className="text-sm text-muted-foreground">
            {result.length} records will be exported.
          </p>
          {error && (
            <p role="alert" className="text-destructive">
              {error}
            </p>
          )}
          <DialogFooter>
            <Button
              disabled={busy}
              variant="outline"
              onClick={() => setOpen(false)}
            >
              Cancel
            </Button>
            <Button
              disabled={busy || !result.length}
              onClick={async () => {
                setBusy(true);
                setError("");
                try {
                  await exportRecords(
                    filename ?? title,
                    result.map((row) => row.data),
                    format,
                  );
                  setNotice(
                    `${result.length} fixture records exported as ${format.toUpperCase()}.`,
                  );
                  setOpen(false);
                } catch (cause) {
                  setError(
                    cause instanceof Error
                      ? cause.message
                      : "Unable to generate the export. Try again.",
                  );
                } finally {
                  setBusy(false);
                }
              }}
            >
              {busy ? "Preparing…" : "Download"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </>
  );
}
