"use client";

import { useState } from "react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
} from "@/app/shadcn_components/ui/dialog";
import { Button } from "@/app/shadcn_components/ui/button";
import { Input } from "@/app/shadcn_components/ui/input";
import { CheckCircle2, XCircle } from "lucide-react";

export type PendingDiff = {
  added: string[];
  removed: string[];
};

type Props = {
  open: boolean;
  pendingDiffs: Record<string, PendingDiff>; // dealId -> diff
  dealNames: Record<string, string>; // dealId -> display name
  onConfirm: () => void;
  onCancel: () => void;
  isPending: boolean;
};

const CONFIRM_WORD = "approve";

export function ApprovalConfirmDialog({
  open,
  pendingDiffs,
  dealNames,
  onConfirm,
  onCancel,
  isPending,
}: Props) {
  const [typed, setTyped] = useState("");

  const canConfirm = typed === CONFIRM_WORD && !isPending;

  const totalAdded = Object.values(pendingDiffs).reduce(
    (sum, d) => sum + d.added.length,
    0,
  );
  const totalRemoved = Object.values(pendingDiffs).reduce(
    (sum, d) => sum + d.removed.length,
    0,
  );

  function handleOpenChange(open: boolean) {
    if (!open) {
      setTyped("");
      onCancel();
    }
  }

  return (
    <Dialog open={open} onOpenChange={handleOpenChange}>
      <DialogContent className="sm:max-w-lg">
        <DialogHeader>
          <DialogTitle className="text-brandblue">Confirm approval changes</DialogTitle>
          <DialogDescription>
            Review the changes below. This action will be recorded in the audit
            log and cannot be undone automatically.
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-4 max-h-80 overflow-y-auto py-1 pr-1">
          {Object.entries(pendingDiffs).map(([dealId, diff]) => {
            if (diff.added.length === 0 && diff.removed.length === 0) return null;
            const name = dealNames[dealId] ?? dealId;
            return (
              <div key={dealId} className="space-y-2">
                <p className="text-sm font-semibold text-gray-700">{name}</p>
                <div className="space-y-1 pl-2">
                  {diff.added.map((m) => (
                    <div key={`add-${m}`} className="flex items-center gap-2">
                      <CheckCircle2 className="h-4 w-4 text-emerald-500 shrink-0" />
                      <span className="text-sm text-emerald-700">{m}</span>
                      <span className="text-xs text-gray-400">will be approved</span>
                    </div>
                  ))}
                  {diff.removed.map((m) => (
                    <div key={`rem-${m}`} className="flex items-center gap-2">
                      <XCircle className="h-4 w-4 text-red-400 shrink-0" />
                      <span className="text-sm text-red-600">{m}</span>
                      <span className="text-xs text-gray-400">will be unapproved</span>
                    </div>
                  ))}
                </div>
              </div>
            );
          })}
        </div>

        <div className="space-y-2 pt-2 border-t border-gray-100">
          <p className="text-sm text-gray-600">
            To confirm{" "}
            <span className="font-semibold">
              {totalAdded > 0 && `${totalAdded} approval${totalAdded > 1 ? "s" : ""}`}
              {totalAdded > 0 && totalRemoved > 0 && " and "}
              {totalRemoved > 0 && `${totalRemoved} removal${totalRemoved > 1 ? "s" : ""}`}
            </span>
            , type{" "}
            <code className="px-1 py-0.5 bg-gray-100 rounded text-brandblue font-mono text-xs">
              {CONFIRM_WORD}
            </code>{" "}
            below:
          </p>
          <Input
            value={typed}
            onChange={(e) => setTyped(e.target.value)}
            placeholder={`Type "${CONFIRM_WORD}" to confirm`}
            className="font-mono"
            autoFocus
          />
        </div>

        <DialogFooter>
          <Button variant="secondary" onClick={onCancel} disabled={isPending}>
            Cancel
          </Button>
          <Button
            onClick={() => {
              setTyped("");
              onConfirm();
            }}
            disabled={!canConfirm}
            className="bg-brandblue text-white"
          >
            {isPending ? "Saving…" : "Confirm"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
