"use client";
import { useRef, useState } from "react";
import { ShieldCheck } from "lucide-react";
import { Switch } from "@/components/ui/switch";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { StatusBadge } from "@/components/shared/status-badge";
import { updateChargepoint } from "../edit-client-api";
import type { Chargepoint } from "../types";

export function AuthorizationSettings({ chargepoint, refreshing, userCount, onChanged }: {
  chargepoint: Chargepoint; refreshing: boolean; userCount?: number; onChanged: (message: string) => void;
}) {
  const [pending, setPending] = useState<boolean | null>(null);
  const [saving, setSaving] = useState(false);
  const busy = useRef(false);
  const [error, setError] = useState("");
  const enabled = chargepoint.enableAuthorization;
  async function confirm() {
    if (pending === null || busy.current) return;
    busy.current = true;
    setSaving(true);
    setError("");
    try {
      await updateChargepoint(chargepoint.id, { enable_authorization: pending });
      setPending(null);
      onChanged(`Authorization feature ${pending ? "enabled" : "disabled"}.`);
    } catch (error) {
      setError(error instanceof Error ? error.message : "Unable to update authorization. Try again.");
    } finally { busy.current = false; setSaving(false); }
  }
  return (
    <section className="panel flex flex-wrap items-center justify-between gap-5 p-5 md:p-6" aria-label="Authorization settings">
      <div className="flex items-start gap-3">
        <span className="rounded-xl bg-primary/10 p-2.5 text-primary"><ShieldCheck aria-hidden="true" className="size-5" /></span>
        <div>
          <div className="flex flex-wrap items-center gap-3">
            <h2 className="text-lg font-semibold">Authorization Settings</h2>
            <StatusBadge tone={enabled === true ? "success" : "neutral"}>{enabled === undefined ? "Unavailable" : enabled ? "Enabled" : "Disabled"}</StatusBadge>
          </div>
          <p className="mt-1 text-sm text-muted-foreground">Control user authorization for this chargepoint.</p>
          {enabled === undefined && <p className="mt-2 text-sm text-muted-foreground">The authorization setting is unavailable. You can still manage the user list.</p>}
        </div>
      </div>
      {enabled !== undefined && <label className="flex items-center gap-3 text-sm font-medium">
        Authorization Feature
        <Switch checked={enabled === true} disabled={enabled === undefined || saving || refreshing} aria-label="Authorization feature" onCheckedChange={next => { setError(""); setPending(next); }} />
      </label>}
      <Dialog open={pending !== null} onOpenChange={open => { if (!open && !busy.current) setPending(null); }}>
        <DialogContent showCloseButton={!saving} className="sm:max-w-lg" aria-busy={saving}>
          <DialogHeader>
            <DialogTitle>{pending ? "Enable" : "Disable"} Authorization Feature?</DialogTitle>
            <DialogDescription>Change the authorization setting for <span className="font-medium text-foreground">{chargepoint.name}</span>. Users already in the list will be retained.</DialogDescription>
          </DialogHeader>
          <p className="rounded-lg border bg-muted/40 p-3 text-sm">{pending && userCount === 0 ? "The authorization list is empty. You can add users before enabling this feature." : "You can continue managing authorized users while this feature is disabled."}</p>
          {error && <p role="alert" className="text-sm text-destructive">{error}</p>}
          <DialogFooter>
            <Button variant="outline" disabled={saving} onClick={() => setPending(null)}>Cancel</Button>
            <Button disabled={saving} onClick={confirm}>{saving ? "Saving…" : pending ? "Enable" : "Disable"}</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </section>
  );
}
