"use client";

import { useEffect, useRef, useState } from "react";
import { CheckCircle2, Copy, ShieldCheck } from "lucide-react";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from "@/components/ui/dialog";
import { FormField } from "@/components/shared/form-field";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import type { CreatedChargepoint } from "./create-result";

export function ChargepointCreatedDialog({ result, name, identity, onContinue }: {
  result: CreatedChargepoint;
  name: string;
  identity: string;
  onContinue: () => void;
}) {
  const [saved, setSaved] = useState(false);
  const [copying, setCopying] = useState(false);
  const [copied, setCopied] = useState(false);
  const [copyError, setCopyError] = useState("");
  const completed = useRef(false);
  const key = result.authorizationKey;
  useEffect(() => {
    if (!key || saved) return;
    function warnBeforeLeaving(event: BeforeUnloadEvent) { event.preventDefault(); event.returnValue = ""; }
    window.addEventListener("beforeunload", warnBeforeLeaving);
    return () => window.removeEventListener("beforeunload", warnBeforeLeaving);
  }, [key, saved]);

  function finish() {
    if ((key && !saved) || completed.current) return;
    completed.current = true;
    onContinue();
  }
  return <Dialog open onOpenChange={() => {}}>
    <DialogContent className="max-h-[calc(100dvh-2rem)] overflow-y-auto sm:max-w-[560px]" showCloseButton={false}>
      <DialogHeader>
        <span className="flex size-11 items-center justify-center rounded-xl bg-success/10 text-success"><CheckCircle2 aria-hidden="true" className="size-6" /></span>
        <DialogTitle>Chargepoint created</DialogTitle>
        <DialogDescription>{name} is ready. {key ? "Save its authorization key before leaving this screen." : "Review the charger authentication details before continuing."}</DialogDescription>
      </DialogHeader>
      <dl className="grid gap-3 rounded-lg border bg-muted/40 p-4 sm:grid-cols-2">
        <div><dt className="text-xs text-muted-foreground">OCPP identity</dt><dd className="mt-1 break-all font-medium">{identity}</dd></div>
        <div><dt className="text-xs text-muted-foreground">Chargepoint ID</dt><dd className="mt-1 break-all font-mono text-xs">{result.id}</dd></div>
      </dl>
      {key ? <>
        <div className="rounded-lg border border-warning/30 bg-warning/5 p-4"><p className="flex items-center gap-2 font-medium"><ShieldCheck aria-hidden="true" className="size-4" />Shown only once</p><p className="mt-1 text-sm text-muted-foreground">Keep this key in a secure password manager. It cannot be viewed here again after closing or refreshing this page.</p></div>
        <div className="space-y-2">
          <FormField label="Authorization key" id="created-authorization-key" value={key} readOnly autoComplete="off" spellCheck={false} className="[&_input]:px-3 [&_input]:font-mono [&_input]:text-sm" onFocus={event => event.currentTarget.select()} />
          <Button type="button" variant="outline" disabled={copying} onClick={async () => {
            if (copying) return;
            setCopying(true); setCopyError("");
            try { await navigator.clipboard.writeText(key); setCopied(true); }
            catch { setCopyError("Copy is unavailable. Select the key above and copy it manually."); }
            finally { setCopying(false); }
          }}><Copy aria-hidden="true" />{copying ? "Copying…" : copied ? "Copied" : "Copy authorization key"}</Button>
          {copied && <p role="status" className="text-sm text-muted-foreground">Key copied. Save it securely before continuing.</p>}
          {copyError && <p role="alert" className="text-sm text-destructive">{copyError}</p>}
        </div>
        <label className="flex cursor-pointer items-start gap-3 rounded-lg border p-4 text-sm" htmlFor="authorization-key-saved"><Checkbox id="authorization-key-saved" checked={saved} onCheckedChange={value => setSaved(value === true)} className="mt-0.5" /><span>I have saved this authorization key securely.</span></label>
      </> : <p role="alert" className="rounded-lg border border-warning/30 bg-warning/5 p-4 text-sm">The chargepoint was created, but the backend did not return a valid authorization key. Do not create it again. Open the created chargepoint and update its authorization key before configuring the charger.</p>}
      <DialogFooter><Button type="button" disabled={Boolean(key) && !saved} onClick={finish}>{key ? "Done" : "Continue"}</Button></DialogFooter>
    </DialogContent>
  </Dialog>;
}
