"use client";

import { useRef, useState } from "react";
import { Check, LoaderCircle, ShieldCheck } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { cn } from "@/lib/utils";
import type { Chargepoint } from "../types";
import { sendChargepointCommand } from "./client-api";
import type { CommandResult as Result } from "./contract.ts";
import { CommandResult } from "./command-result";
import { readSecurityProfile, securityWorkflowSteps, type SecurityWorkflow } from "./security-workflow.ts";

export function SecurityWorkflowDialog({ workflow, chargepoint, source, onClose }: { workflow: SecurityWorkflow; chargepoint: Chargepoint; source: "api" | "preview"; onClose: () => void }) {
  const steps = securityWorkflowSteps(workflow);
  const [index, setIndex] = useState(0);
  const [submitting, setSubmitting] = useState(false);
  const [confirmed, setConfirmed] = useState(false);
  const [error, setError] = useState("");
  const [response, setResponse] = useState<Result>();
  const [blocked, setBlocked] = useState(false);
  const [profile, setProfile] = useState<number>();
  const pending = useRef(false);
  const complete = index >= steps.length;
  const step = steps[index];
  const preview = source === "preview";

  async function sendStep() {
    if (!step || pending.current || blocked || (step.confirm && !confirmed)) return;
    pending.current = true;
    setSubmitting(true);
    setError("");
    setResponse(undefined);
    try {
      const result: Result = preview ? { accepted: null, data: { preview: true, message: "No command was sent to the device." }, ...(index === 0 ? { configuration: [{ key: "SecurityProfile", value: workflow === "certificate-signed" ? "3" : "1", readonly: false }] } : {}) } : await sendChargepointCommand(chargepoint.id, step.command, step.payload);
      setResponse(result);
      if (index === 0) {
        const current = readSecurityProfile(result);
        const valid = workflow === "certificate-signed" ? current === 3 : current === 1 || current === 2;
        if (!valid) {
          setBlocked(true);
          setError(current === null ? "The charger did not report a supported SecurityProfile value. Verify it in Get Configuration before starting this workflow again." : `The charger reports Security Profile ${current}. ${workflow === "certificate-signed" ? "Certificate renewal requires Profile 3." : "This upgrade requires Profile 1 or 2."}`);
          return;
        }
        setProfile(current ?? undefined);
      } else if (!preview && result.accepted !== true) {
        setError("This step was not accepted. Review the response and charger Logs before retrying. Later steps have not been sent.");
        return;
      }
      setConfirmed(false);
      setIndex(current => current + 1);
    } catch (cause) {
      setError(cause instanceof Error ? cause.message : "This step could not be confirmed. Check Logs before retrying.");
    } finally {
      pending.current = false;
      setSubmitting(false);
    }
  }

  return <Dialog open onOpenChange={open => { if (!open && !pending.current) onClose(); }}>
    <DialogContent className="max-h-[calc(100dvh-2rem)] overflow-y-auto sm:max-w-2xl" showCloseButton={!submitting} onEscapeKeyDown={event => { if (pending.current) event.preventDefault(); }} onInteractOutside={event => { if (pending.current) event.preventDefault(); }}>
      <DialogHeader><DialogTitle>{workflow === "certificate-signed" ? "Update CP Certificate" : "Upgrade Security Profile"}</DialogTitle><DialogDescription>Complete each step in order and review the response before continuing.</DialogDescription></DialogHeader>
      <div className="flex items-center gap-3 rounded-lg border bg-muted/30 p-3"><ShieldCheck aria-hidden="true" className="size-5 shrink-0 text-primary" /><div className="min-w-0"><p className="truncate font-medium">{chargepoint.name}</p><p className="text-xs text-muted-foreground">{chargepoint.ocppIdentity ?? chargepoint.endpoint}{profile !== undefined ? ` · Starting profile ${profile}` : ""}{preview ? " · Local preview" : ""}</p></div></div>
      <ol aria-label="Security workflow progress" className="space-y-2">{steps.map((item, position) => <li key={item.command} aria-current={!complete && index === position ? "step" : undefined} className={cn("flex items-center gap-3 rounded-lg px-3 py-2 text-sm", position === index ? "bg-primary/10" : "text-muted-foreground")}><span className={cn("flex size-6 shrink-0 items-center justify-center rounded-full border text-xs", position < index ? "border-success/30 bg-success/10 text-success" : "border-border")}>{position < index ? <Check aria-hidden="true" className="size-3.5" /> : position + 1}</span><span className="flex-1">{item.title}</span>{position < index && <span className="text-xs">{preview ? "Validated" : "Accepted"}</span>}</li>)}</ol>
      {response && <CommandResult result={response} preview={preview} />}
      {error && <p role="alert" className="rounded-lg bg-destructive/10 p-3 text-sm text-destructive">{error}</p>}
      {complete ? <p role="status" className="rounded-lg border border-success/25 bg-success/5 p-3 text-sm">{preview ? "Preview complete. No device commands were sent." : workflow === "upgrade-security-profile" ? "All steps were accepted. Check charger connectivity and Logs to confirm it reconnects using Security Profile 3." : "The charger accepted the certificate request. Check Logs for subsequent certificate and connection events."}</p> : <section className="space-y-3 rounded-xl border p-4" aria-busy={submitting}>
        <h3 className="font-semibold">{step.title}</h3><p className="text-sm leading-relaxed text-muted-foreground">{step.description}</p>
        {step.confirm && <label className="flex items-start gap-3 rounded-lg border border-warning/25 bg-warning/5 p-3 text-sm"><input type="checkbox" checked={confirmed} disabled={submitting || blocked} onChange={event => setConfirmed(event.target.checked)} className="mt-0.5 size-4 shrink-0 accent-primary" /><span>{step.command === "reset" ? "I am ready to interrupt charging and hard reset this chargepoint." : "I have reviewed this chargepoint and am ready to send this security change."}</span></label>}
        {submitting && <p role="status" className="text-sm text-muted-foreground">Waiting for this step’s response…</p>}
      </section>}
      <p className="text-xs text-muted-foreground">Closing this flow preserves changes already sent to the charger. Requests are never retried automatically.</p>
      <DialogFooter><Button type="button" variant="outline" disabled={submitting} onClick={onClose}>{complete || blocked ? "Close" : "Cancel"}</Button>{!complete && !blocked && <Button type="button" variant={step.command === "reset" ? "destructive" : "default"} disabled={submitting || (step.confirm && !confirmed)} onClick={sendStep}>{submitting && <LoaderCircle aria-hidden="true" className="size-4 animate-spin motion-reduce:animate-none" />}{submitting ? "Sending…" : preview ? `Validate: ${step.action}` : step.action}</Button>}</DialogFooter>
    </DialogContent>
  </Dialog>;
}
