"use client";

import { TriangleAlert } from "lucide-react";
import * as React from "react";

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

import type { PreviewCounts } from "../_lib/schema";

type Props = {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  underlyingIsin: string;
  ratio: string;
  counts: PreviewCounts;
  selectedCount: number;
  tenantCount: number;
  startDate: string | null;
  isSaving: boolean;
  onApply: (confirmIsin: string) => void;
};

/**
 * The Save confirmation.
 *
 * A split reaches the structure master, the staged feed rows, and live client
 * holdings together — there is no partial option. Applying rewrites settled
 * history, so it is gated behind typing the underlying's identifier, and the
 * dialog states the blast radius in numbers rather than adjectives.
 */
export function ApplyOptionsDialog({
  open,
  onOpenChange,
  underlyingIsin,
  ratio,
  counts,
  selectedCount,
  tenantCount,
  startDate,
  isSaving,
  onApply,
}: Props) {
  const [confirmIsin, setConfirmIsin] = React.useState("");

  // Reset on close in the handler rather than an effect: the state change is
  // caused by the open/close event, not by synchronising with anything external.
  const handleOpenChange = (next: boolean) => {
    if (!next) {
      setConfirmIsin("");
    }
    onOpenChange(next);
  };

  const confirmMatches =
    confirmIsin.trim().toUpperCase() === underlyingIsin.trim().toUpperCase();

  return (
    <Dialog open={open} onOpenChange={handleOpenChange}>
      <DialogContent className="sm:max-w-xl">
        <DialogHeader>
          <DialogTitle>
            Apply {ratio} to {underlyingIsin}
          </DialogTitle>
          <DialogDescription>
            {selectedCount} of {counts.total} row(s) selected.
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-4">
          <div className="flex gap-3 rounded-lg border border-amber-500/50 bg-amber-500/5 p-4">
            <TriangleAlert className="mt-0.5 size-5 shrink-0 text-amber-600 dark:text-amber-500" />
            <div className="space-y-2 text-sm">
              <p>
                This rewrites <strong>{counts.master}</strong> structure master
                level(s), <strong>{counts.temp}</strong> staged temp row(s) and{" "}
                <strong>{counts.trx}</strong> live transaction(s)
                {tenantCount > 0
                  ? ` across ${tenantCount} client portfolio${tenantCount === 1 ? "" : "s"}`
                  : ""}
                {startDate ? `, back to ${startDate}` : ""}.
              </p>
              <p className="text-muted-foreground text-xs">
                Closed structures and Interest / Dividend entries are never touched.
                Rows already carrying a corporate action stamp are skipped, so a feed
                that arrived split-adjusted is not adjusted twice. This can be
                reverted from the corporate actions history.
              </p>
            </div>
          </div>

          <div className="space-y-2">
            <Label htmlFor="confirm-isin" className="text-sm">
              Type <span className="font-mono font-semibold">{underlyingIsin}</span> to
              confirm
            </Label>
            <Input
              id="confirm-isin"
              value={confirmIsin}
              onChange={(event) => setConfirmIsin(event.target.value)}
              autoComplete="off"
              placeholder={underlyingIsin}
            />
          </div>
        </div>

        <DialogFooter className="gap-2 sm:justify-between">
          <Button
            type="button"
            variant="outline"
            onClick={() => handleOpenChange(false)}
            disabled={isSaving}
          >
            Cancel
          </Button>
          <Button
            type="button"
            onClick={() => onApply(confirmIsin)}
            disabled={isSaving || !confirmMatches}
          >
            {isSaving ? "Applying…" : "Apply split"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
