"use client";

import Link from "next/link";
import { useRef, useState } from "react";
import { useRouter } from "next/navigation";
import { ArrowLeft, Plus, Pencil } from "lucide-react";
import { toast } from "react-hot-toast";
import { Button } from "@/components/ui/button";
import { Panel, EmptyState } from "@/components/shared/panel";
import { StatusBadge } from "@/components/shared/status-badge";
import { DlmRefreshButton } from "./refresh-button";
import { DlmConnectorDialog } from "./connector-dialog";
import { DlmSiteActions } from "./site-actions";
import { getDlmConnectorOptionsRequest } from "./client-api";
import type { DlmSite, DlmConnector, DlmConnectorList, DlmConnectorOptions } from "./types";

export function DlmSiteDetailView({ site, locationName, connectors, connectorError }: { site: DlmSite; locationName: string; connectors: DlmConnectorList | null; connectorError: string }) {
  const router = useRouter();
  const [assigning, setAssigning] = useState(false), [editing, setEditing] = useState<DlmConnector>();
  const [options, setOptions] = useState<DlmConnectorOptions | null>(null), [loading, setLoading] = useState(false), [lookupError, setLookupError] = useState("");
  const lookupPending = useRef(false);
  async function loadOptions() {
    if (lookupPending.current) return;
    lookupPending.current = true; setLoading(true); setLookupError(""); setOptions(null);
    try { setOptions(await getDlmConnectorOptionsRequest(site.id)); }
    catch (cause) { setLookupError(cause instanceof Error ? cause.message : "Unable to load connectors."); }
    finally { lookupPending.current = false; setLoading(false); }
  }
  function openAssignment(connector?: DlmConnector) { setEditing(connector); setAssigning(true); void loadOptions(); }
  const rows = connectors?.records ?? [];
  const complete = Boolean(connectors?.complete);
  const activeConnectors = rows.filter(row => row.active).length;
  const settingsVersion = JSON.stringify([site, rows.map(row => [row.connectorId, row.maxPowerKw, row.minPowerKw, row.priority, row.priorityWeight, row.active])]);
  return <div className="space-y-6 [&_.text-muted-foreground]:text-foreground/70 [&_.text-success]:text-foreground">
    <div className="flex flex-wrap items-center justify-between gap-3"><Link href="/chargepoint-dlm" className="inline-flex items-center gap-2 text-sm text-muted-foreground hover:text-foreground"><ArrowLeft aria-hidden="true" className="size-4" />All DLM sites</Link><DlmRefreshButton error={connectorError} /></div>
    <div className="panel p-5 md:p-6"><div className="flex flex-wrap items-start justify-between gap-3"><div><p className="text-xs font-medium tracking-wide text-muted-foreground">{site.code}</p><h2 className="mt-1 text-lg font-semibold">Site settings</h2><Link href={`/locations/${site.locationId}`} className="mt-1 inline-block text-sm text-muted-foreground hover:underline underline-offset-4">{locationName}</Link></div><StatusBadge tone={site.active ? "success" : "neutral"}>{site.active ? "Active" : "Inactive"}</StatusBadge></div><dl className="mt-5 grid gap-4 sm:grid-cols-2 xl:grid-cols-4">{[{ label: "Maximum site power", value: `${site.maxPowerKw} kW` }, { label: "Power reserve", value: `${site.reservePercent}%` }, { label: "Algorithm", value: site.algorithm === "equal_share" ? "Equal Share" : "Weighted Priority" }, { label: "Assigned connectors", value: complete ? String(rows.length) : "—" }].map(item => <div key={item.label} className="rounded-lg border bg-muted/20 p-4"><dt className="text-xs text-muted-foreground">{item.label}</dt><dd className="mt-2 font-semibold tabular-nums">{item.value}</dd></div>)}</dl></div>
    <Panel title="Assigned connectors" description="Manage each connector's power limits and allocation priority." actions={<Button disabled={!complete} onClick={() => openAssignment()}><Plus aria-hidden="true" />Assign Connector</Button>}>
      {connectorError ? <p role="alert" className="rounded-lg border border-destructive/30 bg-destructive/5 p-4 text-sm text-destructive">{connectorError}</p> : <>
        {!complete && <p role="status" className="mb-4 rounded-lg border bg-muted/40 p-3 text-sm text-muted-foreground">Connector data is incomplete. Refresh before changing assignments. Evaluate and Apply remain available using the backend configuration.</p>}
        {!rows.length ? <EmptyState title={complete ? "No connectors assigned" : "Connector data unavailable"} description={complete ? "Assign connectors from this location to start sharing the site power budget." : "Refresh to load the connector list."} /> : <div className="overflow-x-auto rounded-lg border"><table className="data-table min-w-[850px]"><caption className="sr-only">Connectors assigned to {site.name} ({site.code})</caption><thead><tr><th scope="col">Chargepoint / connector</th><th scope="col">Minimum</th><th scope="col">Maximum</th><th scope="col">Priority</th><th scope="col">Weight</th><th scope="col">Status</th><th scope="col"><span className="sr-only">Edit limits</span></th></tr></thead><tbody>{rows.map(row => <tr key={row.connectorId}><td><Link href={`/chargepoints/${row.chargepointId}`} className="font-medium hover:underline underline-offset-4">{row.ocppIdentity}</Link><p className="mt-1 text-xs text-muted-foreground">Connector {row.connectorNumber}</p></td><td className="whitespace-nowrap tabular-nums">{row.minPowerKw} kW</td><td className="whitespace-nowrap font-medium tabular-nums">{row.maxPowerKw} kW</td><td className="tabular-nums">{row.priority}</td><td className="tabular-nums">{row.priorityWeight}</td><td><StatusBadge tone={row.active ? "success" : "neutral"}>{row.active ? "Active" : "Inactive"}</StatusBadge></td><td><Button variant="outline" size="sm" disabled={!complete} aria-label={`Edit limits for ${row.ocppIdentity} connector ${row.connectorNumber}`} onClick={() => openAssignment(row)}><Pencil aria-hidden="true" className="size-3.5" />Edit Limits</Button></td></tr>)}</tbody></table></div>}
      </>}
    </Panel>
    <DlmSiteActions key={settingsVersion} site={site} locationName={locationName} activeConnectors={activeConnectors} connectorsComplete={complete} />
    {assigning && <DlmConnectorDialog key={editing?.connectorId ?? "new"} site={site} locationName={locationName} options={options} loading={loading} error={lookupError} editing={editing} assignedIds={rows.map(row => row.connectorId)} onReload={() => void loadOptions()} onOpenChange={setAssigning} onAssigned={() => { setAssigning(false); toast.success(editing ? "Connector limits saved. Use Apply to send the changes." : "Connector assigned. Use Apply to send the changes."); router.refresh(); }} />}
  </div>;
}
