"use client";

import { useEffect, useRef, useState } from "react";
import { Loader2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { FormField, SelectField } from "@/components/shared/form-field";
import { SearchableFilterField } from "@/components/shared/searchable-filter-field";
import { validateDlmSite, capacityFields } from "./contract";
import { createDlmSiteRequest } from "./client-api";
import { formNumber, PowerFields, DlmStatusField } from "./form-fields";
import type { Location } from "@/features/locations/types";

const capacityLabels = { installed_site_capacity_kw: "Installed site capacity (kW)", hotel_reserved_kw: "Hotel reserved power (kW)", cafe_reserved_kw: "Cafe reserved power (kW)", ev_pool_kw: "EV pool capacity (kW)" };
export function DlmSiteDialog({ locations, onOpenChange, onCreated }: {
  locations: Pick<Location, "id" | "name" | "address">[];
  onOpenChange: (open: boolean) => void;
  onCreated: (id: string) => void;
}) {
  const [locationId, setLocationId] = useState("");
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState("");
  const pending = useRef(false), errorRef = useRef<HTMLParagraphElement>(null);
  useEffect(() => { if (error) errorRef.current?.focus(); }, [error]);
  function changeOpen(open: boolean) { if (!pending.current) onOpenChange(open); }
  async function submit(event: React.FormEvent<HTMLFormElement>) {
    event.preventDefault();
    if (pending.current) return;
    const form = new FormData(event.currentTarget);
    const metadata = Object.fromEntries(capacityFields.filter(field => String(form.get(field) ?? "").trim() !== "").map(field => [field, formNumber(form, field)]));
    const valid = validateDlmSite({ location_id: form.get("location_id"), code: form.get("code"), name: form.get("name"), max_power_kw: formNumber(form, "max_power_kw"), reserve_percent: formNumber(form, "reserve_percent"), algorithm: form.get("algorithm"), active: form.get("active") === "true", ...(Object.keys(metadata).length ? { metadata } : {}) });
    if ("error" in valid) { setError(valid.error); return; }
    pending.current = true; setSaving(true); setError("");
    try { const site = await createDlmSiteRequest(valid.payload); onCreated(site.id); }
    catch (cause) { setError(cause instanceof Error ? cause.message : "Unable to create the DLM site."); }
    finally { pending.current = false; setSaving(false); }
  }
  return <Dialog open onOpenChange={changeOpen}>
    <DialogContent className="flex max-h-[calc(100dvh-2rem)] flex-col overflow-hidden p-0 [&_.text-muted-foreground]:text-foreground/70 sm:max-w-xl" showCloseButton={!saving}>
      <DialogHeader className="shrink-0 border-b px-6 py-5"><DialogTitle>Create DLM site</DialogTitle><DialogDescription>Define a shared power limit, then assign the charging connectors.</DialogDescription></DialogHeader>
      <form onSubmit={submit} className="flex min-h-0 flex-1 flex-col">
        <div className="min-h-0 flex-1 space-y-5 overflow-y-auto px-6 py-5">
          {error && <p ref={errorRef} tabIndex={-1} role="alert" className="rounded-lg border border-destructive/30 bg-destructive/5 p-3 text-sm text-destructive">{error}</p>}
          <fieldset disabled={saving} className="space-y-5 disabled:opacity-70">
            <SearchableFilterField name="location_id" label="Location" value={locationId} onValueChange={setLocationId} required allowCustomValue={false} placeholder="Choose a location" options={locations.map(location => ({ value: location.id, label: location.name, description: location.address }))} helperText="Choose the location whose connectors will share this power limit." />
            <div className="grid gap-4 sm:grid-cols-2">
              <FormField name="name" label="Site name" placeholder="e.g. Main parking chargers" maxLength={200} required />
              <div><FormField name="code" label="Site code" placeholder="e.g. PARKING-DLM-01" maxLength={100} required /><p className="mt-1.5 text-xs text-muted-foreground">Use a unique code to identify this power group.</p></div>
              <PowerFields />
              <SelectField name="algorithm" label="Allocation algorithm" defaultValue="equal_share" options={[{ value: "equal_share", label: "Equal Share" }, { value: "weighted_priority", label: "Weighted Priority" }]} required />
              <DlmStatusField />
            </div>
            <p className="rounded-lg bg-muted/50 p-3 text-xs leading-relaxed text-muted-foreground">Equal Share distributes available power evenly. Weighted Priority uses the connector priorities and weights configured after creation.</p>
            <details className="rounded-lg border p-4"><summary className="cursor-pointer text-sm font-medium">Additional settings <span className="ml-1 text-xs font-normal text-muted-foreground">Optional</span></summary>
              <div className="mt-4 grid gap-4 sm:grid-cols-2">
                <FormField name="reserve_percent" label="Power reserve (%)" type="number" min="0" max="100" step="any" defaultValue={0} required />
                <p className="self-center text-xs leading-relaxed text-muted-foreground">The backend uses this reserve when evaluating the available site power.</p>
                {capacityFields.map(field => <FormField key={field} name={field} label={capacityLabels[field]} type="number" min="0" step="any" placeholder="Not set" />)}
              </div>
            </details>
          </fieldset>
        </div>
        <DialogFooter className="mx-0 mb-0 shrink-0 px-6 py-4"><Button type="button" variant="outline" disabled={saving} onClick={() => changeOpen(false)}>Cancel</Button><Button type="submit" disabled={saving} aria-busy={saving}>{saving && <Loader2 aria-hidden="true" className="animate-spin motion-reduce:animate-none" />}{saving ? "Creating…" : "Create Site"}</Button></DialogFooter>
      </form>
    </DialogContent>
  </Dialog>;
}
