"use client";

import Link from "next/link";
import { useEffect, useRef, useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { ArrowUpRight, Plus, SlidersHorizontal } from "lucide-react";
import { toast } from "react-hot-toast";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Panel, EmptyState } from "@/components/shared/panel";
import { StatusBadge } from "@/components/shared/status-badge";
import { DlmSiteDialog } from "./site-dialog";
import { DlmRefreshButton } from "./refresh-button";
import type { DlmSiteList } from "./types";
import { paginate, readListQuery, updateQuery } from "@/lib/list-query";
import type { Location } from "@/features/locations/types";

export function DlmSiteListView({ sites, locations, locationsComplete, loadError }: {
  sites: DlmSiteList | null;
  locations: Location[];
  locationsComplete: boolean;
  loadError: string;
}) {
  const router = useRouter();
  const params = useSearchParams();
  const query = params.get("query") ?? "";
  const locationFilter = params.get("location_id") ?? "";
  const page = readListQuery({ paginate_page: params.get("paginate_page") ?? undefined }).page;
  const [creating, setCreating] = useState(false);
  const [searchState, setSearchState] = useState({ source: query, value: query });
  const searchValue = searchState.source === query ? searchState.value : query;
  const searchTimeout = useRef<ReturnType<typeof setTimeout> | null>(null);
  useEffect(() => {
    function restoreSearch() {
      if (searchTimeout.current !== null) clearTimeout(searchTimeout.current);
      searchTimeout.current = null;
      const value = new URLSearchParams(window.location.search).get("query") ?? "";
      setSearchState({ source: value, value });
    }
    window.addEventListener("popstate", restoreSearch);
    return () => {
      window.removeEventListener("popstate", restoreSearch);
      if (searchTimeout.current !== null) clearTimeout(searchTimeout.current);
    };
  }, []);
  function updateFilters(search: string, location: string) {
    if (searchTimeout.current !== null) clearTimeout(searchTimeout.current);
    searchTimeout.current = null;
    const value = search.trim();
    setSearchState({ source: query, value });
    const next = updateQuery(window.location.search, { query: value, location_id: location, paginate_page: null });
    // Next.js syncs native history with useSearchParams without refetching this loaded list.
    window.history.replaceState(null, "", next ? `/chargepoint-dlm?${next}` : "/chargepoint-dlm");
  }
  function changeSearch(value: string) {
    setSearchState({ source: query, value });
    if (searchTimeout.current !== null) clearTimeout(searchTimeout.current);
    searchTimeout.current = setTimeout(() => updateFilters(value, locationFilter), 300);
  }
  const names = new Map(locations.map(location => [location.id, location.name]));
  const normalized = query.trim().toLowerCase();
  const filtered = (sites?.records ?? []).filter(site => (!locationFilter || site.locationId === locationFilter) && (!normalized || `${site.name} ${site.code} ${names.get(site.locationId) ?? site.locationId}`.toLowerCase().includes(normalized)));
  const paged = paginate(filtered, page, 25);
  const pageHref = (number: number) => {
    return `/chargepoint-dlm?${updateQuery(params.toString(), { paginate_page: String(number) })}`;
  };
  const verified = Boolean(sites?.complete);
  const summaries = [
    { label: "DLM sites", value: verified ? String(sites?.records.length) : "—" },
    { label: "Active sites", value: verified ? String(sites?.records.filter(site => site.active).length) : "—" },
    { label: "Locations with DLM", value: verified ? String(new Set(sites?.records.map(site => site.locationId)).size) : "—" },
  ];
  return <div className="space-y-6 [&_.text-muted-foreground]:text-foreground/70 [&_.text-success]:text-foreground">
    <div className="panel flex flex-wrap items-center justify-between gap-4 p-5 md:p-6">
      <div className="flex items-start gap-3"><span className="flex size-11 shrink-0 items-center justify-center rounded-xl bg-primary/10 text-primary"><SlidersHorizontal aria-hidden="true" className="size-5" /></span><div><h2 className="font-semibold">Shared power, managed by site</h2><p className="mt-1 max-w-xl text-sm text-muted-foreground">Set a site power limit, assign connectors, then review and apply their allocation.</p></div></div>
      <div className="flex flex-wrap gap-2"><DlmRefreshButton error={loadError} /><Button disabled={!verified || !locationsComplete || !locations.length} onClick={() => setCreating(true)}><Plus aria-hidden="true" />Create Site</Button></div>
    </div>
    <div className="grid gap-4 sm:grid-cols-3">{summaries.map(summary => <div key={summary.label} className="panel p-5"><p className="text-sm text-muted-foreground">{summary.label}</p><p className="mt-2 text-2xl font-semibold tabular-nums">{summary.value}</p></div>)}</div>
    <Panel title="DLM sites" description="Each site defines a shared charging power budget for a location.">
      {loadError ? <div role="alert" className="rounded-lg border border-destructive/30 bg-destructive/5 p-4 text-sm text-destructive"><p className="font-medium">Unable to load DLM sites</p><p className="mt-1">{loadError}</p></div> : <>
        {!verified && <p role="status" className="mb-4 rounded-lg border bg-muted/40 p-3 text-sm text-muted-foreground">The API site list is incomplete. Search applies to loaded sites; totals and new-site creation are unavailable until the full list is verified.</p>}
        {!locationsComplete && <p role="status" className="mb-4 text-sm text-muted-foreground">Location choices are incomplete or unavailable. Refresh before creating a site.</p>}
        <form role="search" onSubmit={event => { event.preventDefault(); updateFilters(searchValue, locationFilter); }} className="mb-5 flex flex-wrap items-end gap-3">
          <div className="min-w-0 flex-1 sm:min-w-60"><label className="field-label" htmlFor="dlm-search">Search sites</label><Input id="dlm-search" name="query" value={searchValue} onChange={event => changeSearch(event.target.value)} placeholder="Site name, code, or location" /></div>
          <div className="w-full sm:w-64"><label className="field-label" htmlFor="dlm-location">Location</label><select id="dlm-location" name="location_id" value={locationFilter} onChange={event => updateFilters(searchValue, event.target.value)} className="h-11 w-full rounded-lg border border-input bg-card px-3 outline-none focus:border-primary"><option value="">All locations</option>{locations.map(location => <option key={location.id} value={location.id}>{location.name}</option>)}</select></div>
          {(searchValue || locationFilter) && <Button type="button" variant="ghost" onClick={() => updateFilters("", "")}>Clear</Button>}
        </form>
        {!filtered.length ? <EmptyState title={sites?.records.length ? "No matching sites" : "No DLM sites yet"} description={sites?.records.length ? "Try another search or location." : "Create your first site, then assign its charging connectors."} /> : <div className="overflow-x-auto rounded-lg border"><table className="data-table min-w-[760px]"><caption className="sr-only">DLM sites and shared power limits</caption><thead><tr><th scope="col">Site</th><th scope="col">Location</th><th scope="col">Maximum power</th><th scope="col">Algorithm</th><th scope="col">Status</th><th scope="col"><span className="sr-only">Manage</span></th></tr></thead><tbody>{paged.items.map(site => <tr key={site.id}><td><Link href={`/chargepoint-dlm/${site.id}`} className="font-medium hover:underline underline-offset-4">{site.name}</Link><p className="mt-1 text-xs text-muted-foreground">{site.code}</p></td><td>{names.get(site.locationId) ?? site.locationId}</td><td className="whitespace-nowrap font-medium tabular-nums">{site.maxPowerKw} <span className="font-normal text-muted-foreground">kW</span></td><td>{site.algorithm === "equal_share" ? "Equal Share" : "Weighted Priority"}</td><td><StatusBadge tone={site.active ? "success" : "neutral"}>{site.active ? "Active" : "Inactive"}</StatusBadge></td><td><Link href={`/chargepoint-dlm/${site.id}`} className="inline-flex items-center gap-1.5 whitespace-nowrap rounded-lg px-3 py-2 text-sm font-medium text-foreground hover:bg-muted" aria-label={`Manage ${site.name} (${site.code})`}>Manage<ArrowUpRight aria-hidden="true" className="size-4" /></Link></td></tr>)}</tbody></table></div>}
        <div className="mt-4 flex flex-wrap items-center justify-between gap-3"><p role="status" aria-live="polite" className="text-xs text-muted-foreground">Showing {paged.start}–{paged.end} of {filtered.length} matching sites{sites?.complete ? "." : `; ${sites?.totalDocs ?? "unknown"} reported by the API.`}</p>{paged.pages > 1 && <nav aria-label="DLM site pages" className="flex items-center gap-3">{paged.page > 1 ? <Link href={pageHref(paged.page - 1)} className="rounded-lg border px-3 py-2 text-sm hover:bg-muted">Previous</Link> : <span className="px-3 py-2 text-sm text-muted-foreground">Previous</span>}<span className="text-xs text-muted-foreground">Page {paged.page} of {paged.pages}</span>{paged.page < paged.pages ? <Link href={pageHref(paged.page + 1)} className="rounded-lg border px-3 py-2 text-sm hover:bg-muted">Next</Link> : <span className="px-3 py-2 text-sm text-muted-foreground">Next</span>}</nav>}</div>
      </>}
    </Panel>
    {creating && <DlmSiteDialog locations={locations} onOpenChange={setCreating} onCreated={id => { setCreating(false); toast.success("DLM site created. Assign connectors to continue."); router.push(`/chargepoint-dlm/${id}`); router.refresh(); }} />}
  </div>;
}
