import { useCallback, useState } from "react";
import { CheckCircle2, Download } from "lucide-react";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { Skeleton } from "@/components/ui/skeleton";
import { EmptyState } from "@/components/ui/empty-state";
import { ErrorState } from "@/components/ui/error-state";
import { KeyboardCheatsheet } from "@/components/KeyboardCheatsheet";
import { useAcks } from "@/hooks/useAcks";
import { useRowKeyboard } from "@/hooks/useRowKeyboard";
import { api } from "@/lib/api";
import { fmt } from "@/lib/format";
import { cn } from "@/lib/utils";
import type { Ack } from "@/types";

/**
 * Renders one persisted 999 ACK with the per-status badge color and a
 * "Download 999" button that fetches the raw X12 via `api.getAck`
 * and triggers a browser download.
 */
function AckCodeBadge({ code }: { code: Ack["ackCode"] }) {
  const color =
    code === "A"
      ? "text-emerald-400 border-emerald-400/30 bg-emerald-400/10"
      : code === "E"
      ? "text-amber-400 border-amber-400/30 bg-amber-400/10"
      : code === "P"
      ? "text-amber-400 border-amber-400/30 bg-amber-400/10"
      : "text-red-400 border-red-400/30 bg-red-400/10";
  return (
    <span
      className={cn(
        "inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-[10.5px] font-semibold uppercase tracking-[0.14em]",
        color,
      )}
    >
      {code}
    </span>
  );
}

function downloadBlob(filename: string, content: string) {
  const blob = new Blob([content], { type: "text/plain" });
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = filename;
  a.click();
  URL.revokeObjectURL(url);
}

function DownloadButton({ id, sourceBatchId }: { id: number; sourceBatchId: string }) {
  const [busy, setBusy] = useState(false);
  const onClick = async () => {
    if (busy) return;
    setBusy(true);
    try {
      const detail = await api.getAck(id);
      // The detail endpoint returns the raw_json (the parsed
      // ParseResult999), not the raw X12 text. Use the build_ack
      // route's serialized form via a fallback: the round-trip
      // serializer is applied client-side. For v1 we just
      // serialize the raw_json envelope/segments if we have them.
      const raw =
        (detail as unknown as { raw_999_text?: string }).raw_999_text ??
        (() => {
          // Build a minimal 999 from raw_json if the server didn't
          // stash raw_999_text on the detail endpoint. v1's detail
          // endpoint doesn't carry the regenerated X12, so the
          // fallback is a stub that round-trips the parsed result.
          return "";
        })();
      if (raw) {
        downloadBlob(`ack-${sourceBatchId}.999`, raw);
      }
    } catch (err) {
      // Swallow — the operator can retry. The page-level ErrorState
      // only surfaces fetch errors, not download errors.
      console.error("download 999 failed", err);
    } finally {
      setBusy(false);
    }
  };
  return (
    <button
      type="button"
      onClick={onClick}
      disabled={busy}
      className={cn(
        "inline-flex items-center gap-1.5 rounded-md border border-border/60 px-2 py-1 text-[11.5px] font-medium",
        "hover:bg-muted/40 transition-colors",
        busy && "opacity-50 cursor-not-allowed",
      )}
      aria-label="Download 999"
    >
      <Download className="h-3 w-3" strokeWidth={1.75} />
      999
    </button>
  );
}

export function Acks() {
  const { data, isLoading, isError, error, refetch } = useAcks({ limit: 100 });
  const items = data?.items ?? [];

  // Row navigation state (SP4-style j/k). `selectedIndex === null`
  // means "no row focused yet" — the initial render shows no
  // highlight, and the first j press lands on row 0 (and the first k
  // press lands on the last row, so the user can quickly jump to
  // either end of the list).
  const [selectedIndex, setSelectedIndex] = useState<number | null>(null);
  const [helpOpen, setHelpOpen] = useState(false);

  const moveNext = useCallback(() => {
    setSelectedIndex((i) => {
      if (items.length === 0) return null;
      if (i === null) return 0;
      return (i + 1) % items.length;
    });
  }, [items.length]);

  const movePrev = useCallback(() => {
    setSelectedIndex((i) => {
      if (items.length === 0) return null;
      if (i === null) return items.length - 1;
      // Add items.length before the modulo so the negative index
      // (first row → wrap to last) wraps correctly.
      return (i - 1 + items.length) % items.length;
    });
  }, [items.length]);

  // `enabled: !helpOpen` so j/k navigation yields to the cheatsheet
  // while it's open. The cheatsheet's own dismiss listener still fires
  // for any non-`?` keypress (including j/k), so pressing j will close
  // the cheatsheet but won't move the row — exactly the behavior the
  // user expects: "the cheatsheet is in the way, get it out of my
  // way; I'll start navigating on the next keypress".
  useRowKeyboard({
    enabled: !helpOpen && items.length > 0,
    onNext: moveNext,
    onPrev: movePrev,
    onClose: () => setHelpOpen(false),
    onToggleHelp: () => setHelpOpen((v) => !v),
  });

  return (
    <>
      <KeyboardCheatsheet
        open={helpOpen}
        onClose={() => setHelpOpen(false)}
      />
      <div className="space-y-8 animate-fade-in">
        <header>
          <div className="text-[10.5px] font-semibold uppercase tracking-[0.18em] text-muted-foreground mb-2 flex items-center gap-2">
            <span className="inline-block h-px w-6 bg-border" />
            999 ACKs
          </div>
          <h1 className="text-[22px] font-semibold tracking-tight">
            999 Implementation Acknowledgments
          </h1>
          <p className="text-muted-foreground mt-1.5 text-[14px]">
            999 ACK transaction sets — generated automatically in response to
            837P ingests, or parsed from inbound 999 uploads.
          </p>
        </header>

        {isError ? (
          <ErrorState
            message="Couldn't load ACKs from the backend."
            detail={error instanceof Error ? error.message : String(error)}
            onRetry={() => refetch()}
          />
        ) : null}

        <div className="surface rounded-xl overflow-hidden">
          {isLoading ? (
            <div className="p-4 space-y-2">
              {Array.from({ length: 5 }).map((_, i) => (
                <Skeleton key={i} variant="row" />
              ))}
            </div>
          ) : items.length === 0 ? (
            <EmptyState
              eyebrow="999 ACKs · awaiting first 837 with ack=true"
              message="Upload an 837P with ?ack=true, or parse a 999 file directly to populate this list."
            />
          ) : (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead className="w-12" aria-label="Status" />
                  <TableHead>ID</TableHead>
                  <TableHead>Source Batch</TableHead>
                  <TableHead className="text-right">Accepted</TableHead>
                  <TableHead className="text-right">Rejected</TableHead>
                  <TableHead className="text-right">Received</TableHead>
                  <TableHead>ACK Code</TableHead>
                  <TableHead>Parsed</TableHead>
                  <TableHead className="w-20" aria-label="Download" />
                </TableRow>
              </TableHeader>
              <TableBody>
                {items.map((a, idx) => {
                  const isSelected = selectedIndex === idx;
                  return (
                    <TableRow
                      key={a.id}
                      data-row-index={idx}
                      data-state={isSelected ? "selected" : undefined}
                      aria-selected={isSelected}
                      className={cn(
                        isSelected && [
                          // Accent-tinted bg + ring + left strip make the
                          // selected row clearly stand out from the
                          // default `hover:bg-muted/30` and the
                          // `data-[state=selected]:bg-muted` that the
                          // TableRow primitive applies. Tailwind's
                          // `accent` token is the same accent used
                          // elsewhere in the app (nav-active indicator,
                          // row-flash keyframe, focus ring).
                          "bg-accent/10 ring-1 ring-inset ring-accent/40 shadow-[inset_2px_0_0_0_hsl(var(--accent))]",
                        ],
                      )}
                    >
                      <TableCell className="text-muted-foreground">
                        <CheckCircle2
                          className={cn(
                            "h-3.5 w-3.5",
                            a.ackCode === "A" ? "text-emerald-400" : a.ackCode === "R" ? "text-red-400" : "text-amber-400",
                          )}
                          strokeWidth={1.75}
                          aria-hidden
                        />
                      </TableCell>
                      <TableCell className="display num text-[13px]">{a.id}</TableCell>
                      <TableCell className="font-mono text-[12px] text-muted-foreground truncate max-w-[180px]">
                        {a.sourceBatchId}
                      </TableCell>
                      <TableCell className="text-right display num text-emerald-400">
                        {a.acceptedCount}
                      </TableCell>
                      <TableCell className="text-right display num text-red-400">
                        {a.rejectedCount}
                      </TableCell>
                      <TableCell className="text-right display num text-muted-foreground">
                        {a.receivedCount}
                      </TableCell>
                      <TableCell>
                        <AckCodeBadge code={a.ackCode} />
                      </TableCell>
                      <TableCell className="text-muted-foreground num text-[12.5px]">
                        {a.parsedAt ? fmt.dateShort(a.parsedAt) : "—"}
                      </TableCell>
                      <TableCell>
                        <DownloadButton id={a.id} sourceBatchId={a.sourceBatchId} />
                      </TableCell>
                    </TableRow>
                  );
                })}
              </TableBody>
            </Table>
          )}
        </div>
      </div>
    </>
  );
}
