"use client";

import * as React from "react";
import { toast } from "sonner";

import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";

import {
  diffObsStatusSnapshots,
  filterTodaysObservationEvents,
  formatObsStatusFlags,
  localTodayKey,
  snapshotObsStatus,
  writeObsStatusSnapshot,
  type ObsStatusFlip,
  type ObsStatusSnapshotRow,
} from "../../_lib/cashflow-obs-status-dry-run";
import type { CashflowEvent } from "./schema";

type CashflowObsStatusDryRunDialogProps = {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  tenant: string;
  events: CashflowEvent[];
  isLoading: boolean;
  refreshKey: number;
  onRefresh: () => void;
};

export function CashflowObsStatusDryRunDialog({
  open,
  onOpenChange,
  tenant,
  events,
  isLoading,
  refreshKey,
  onRefresh,
}: CashflowObsStatusDryRunDialogProps) {
  const [flips, setFlips] = React.useState<ObsStatusFlip[] | null>(null);
  const [running, setRunning] = React.useState(false);
  const beforeRef = React.useRef<ObsStatusSnapshotRow[] | null>(null);
  const runFromKeyRef = React.useRef<number | null>(null);

  React.useEffect(() => {
    if (!open) return;
    // Reset the previous run each time the dialog opens: the refs are cleared together with the state, and
    // refs cannot be written during render, so this stays an effect.
    // eslint-disable-next-line react-hooks/set-state-in-effect
    setFlips(null);
    setRunning(false);
    beforeRef.current = null;
    runFromKeyRef.current = null;
  }, [open]);

  React.useEffect(() => {
    if (!running || isLoading) return;
    if (runFromKeyRef.current === null || refreshKey === runFromKeyRef.current) return;

    const before = beforeRef.current;
    if (!before) {
      setRunning(false);
      runFromKeyRef.current = null;
      toast.message("Dry-run failed — no before snapshot.");
      return;
    }

    const todayKey = localTodayKey();
    const after = snapshotObsStatus(filterTodaysObservationEvents(events, todayKey));
    const nextFlips = diffObsStatusSnapshots(before, after);
    setFlips(nextFlips);
    setRunning(false);
    beforeRef.current = null;
    runFromKeyRef.current = null;
    toast.message(
      nextFlips.length === 0
        ? "No Early Redm / Delivery flips"
        : `${nextFlips.length} Observation status flip${nextFlips.length === 1 ? "" : "s"}`,
    );
  }, [running, isLoading, refreshKey, events]);

  const todayObsCount = React.useMemo(() => {
    return filterTodaysObservationEvents(events, localTodayKey()).length;
  }, [events]);

  function handleRun() {
    const todayKey = localTodayKey();
    const before = snapshotObsStatus(filterTodaysObservationEvents(events, todayKey));
    if (before.length === 0) {
      setFlips([]);
      toast.message(`No Observation events for ${todayKey}`);
      return;
    }

    // Before = currently loaded calendar (pre-refresh). Pull prices first, then Run.
    writeObsStatusSnapshot(tenant, before);
    beforeRef.current = before;
    runFromKeyRef.current = refreshKey;
    setFlips(null);
    setRunning(true);
    onRefresh();
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-h-[85vh] max-w-2xl overflow-hidden sm:max-w-2xl">
        <DialogHeader>
          <DialogTitle>Observation status dry-run</DialogTitle>
          <DialogDescription>
            Pull market prices first, then Run. Compares the loaded calendar to a fresh refresh and
            lists only Early Redm / Delivery flips. Nothing is saved to the server.
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-3 text-sm">
          <p className="text-muted-foreground">
            Today ({localTodayKey()}): <span className="tabular-nums text-foreground">{todayObsCount}</span>{" "}
            Observation event{todayObsCount === 1 ? "" : "s"} in the loaded calendar.
          </p>

          {flips !== null ? (
            flips.length === 0 ? (
              <p className="rounded-md border border-dashed px-3 py-6 text-center text-muted-foreground">
                No flips after refresh.
              </p>
            ) : (
              <div className="max-h-[40vh] overflow-auto rounded-md border">
                <table className="w-full text-left text-xs">
                  <thead className="sticky top-0 bg-background">
                    <tr className="border-b text-muted-foreground">
                      <th className="px-2 py-1.5 font-medium">Ref</th>
                      <th className="px-2 py-1.5 font-medium">ISIN</th>
                      <th className="px-2 py-1.5 font-medium">Name</th>
                      <th className="px-2 py-1.5 font-medium">Before</th>
                      <th className="px-2 py-1.5 font-medium">After</th>
                    </tr>
                  </thead>
                  <tbody>
                    {flips.map((row) => (
                      <tr key={row.key} className="border-b last:border-0">
                        <td className="px-2 py-1.5 tabular-nums">{row.refId || "—"}</td>
                        <td className="px-2 py-1.5 font-mono text-[11px]">{row.isin || "—"}</td>
                        <td className="max-w-[12rem] truncate px-2 py-1.5" title={row.name}>
                          {row.name || "—"}
                        </td>
                        <td className="px-2 py-1.5 tabular-nums">{formatObsStatusFlags(row.before)}</td>
                        <td className="px-2 py-1.5 tabular-nums">{formatObsStatusFlags(row.after)}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )
          ) : null}
        </div>

        <DialogFooter>
          <Button type="button" size="sm" onClick={handleRun} disabled={isLoading || running}>
            {running || isLoading ? "Running…" : "Run"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
