"use client";
import { useState } from "react";
import { useSearchParams } from "next/navigation";
import { Pencil, Trash2, MapPin } from "lucide-react";
import { DataTable } from "@/components/shared/data-table";
import {
  PageHeader,
  Panel,
  PreviewNotice,
  StatusBadge,
} from "@/components/shared/page";
import { Tabs } from "@/components/shared/tabs";
import {
  PreviewLink,
  usePreviewRole,
} from "@/components/layout/preview-context";
import { canManage, isManager } from "@/lib/preview";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
} from "@/components/ui/dialog";
import { useChargepoints } from "./provider";
import { ChargepointEditor } from "./editor";
import type { Chargepoint } from "./model";
export function ChargepointList() {
  const { points, setPoints } = useChargepoints(),
    role = usePreviewRole(),
    params = useSearchParams();
  const [editing, setEditing] = useState<Chargepoint | null>(null),
    [deleting, setDeleting] = useState<Chargepoint | null>(null),
    [notice, setNotice] = useState("");
  const rows = points.filter((p) =>
    isManager(role)
      ? p.locationId === "loc-001"
      : role === "investor"
        ? ["loc-001", "loc-002"].includes(p.locationId)
        : true,
  );
  return (
    <>
      <PageHeader title="Chargestations" />
      <div className="space-y-5">
        <PreviewNotice />
        {notice && (
          <p role="status" className="text-success">
            {notice}
          </p>
        )}
        <Tabs
          items={[
            { value: "map", label: "Map" },
            { value: "list", label: "List" },
          ]}
        />
        {params.get("tab") !== "list" && (
          <Panel title="Chargestation Locations">
            <div className="relative min-h-64 overflow-hidden bg-muted/50 p-6">
              <div className="absolute inset-0 opacity-10" aria-hidden="true">
                <svg width="100%" height="100%">
                  <defs>
                    <pattern
                      id="map-grid"
                      width="52"
                      height="42"
                      patternUnits="userSpaceOnUse"
                    >
                      <path
                        d="M0 0H52V42"
                        fill="none"
                        stroke="currentColor"
                        strokeWidth="2"
                      />
                    </pattern>
                  </defs>
                  <rect width="100%" height="100%" fill="url(#map-grid)" />
                </svg>
              </div>
              <div className="relative flex flex-wrap justify-center gap-4 pt-8">
                {rows.slice(0, 4).map((p) => (
                  <PreviewLink
                    key={p.id}
                    href={`/chargepoints/${p.id}`}
                    className="flex items-center gap-2 rounded-lg border bg-card p-4 shadow-sm"
                  >
                    <MapPin className="size-5 text-primary" />
                    <span className="text-sm">
                      {p.name}
                      <span className="block text-xs text-muted-foreground">
                        {p.location}
                      </span>
                    </span>
                  </PreviewLink>
                ))}
              </div>
              <p className="relative mt-8 text-center text-xs text-muted-foreground">
                Offline fixture map · live map tiles are unavailable in this
                phase
              </p>
            </div>
          </Panel>
        )}
        {params.get("tab") === "list" && (
          <DataTable
            title="Chargestations"
            rows={rows}
            columns={[
              {
                key: "name",
                label: "Name",
                render: (r) => (
                  <PreviewLink
                    href={`/chargepoints/${r.id}`}
                    className="text-link"
                  >
                    {r.name}
                  </PreviewLink>
                ),
              },
              {
                key: "location",
                label: "Location",
                render: (r) => (
                  <PreviewLink
                    href={`/locations/${r.locationId}`}
                    className="text-link"
                  >
                    {r.location}
                  </PreviewLink>
                ),
              },
              {
                key: "status",
                label: "Status",
                render: (r) => <StatusBadge>{r.status}</StatusBadge>,
              },
              {
                key: "online",
                label: "Online",
                render: (r) => <StatusBadge>{r.online}</StatusBadge>,
              },
              { key: "visibility", label: "Public" },
              { key: "protocol", label: "Protocol" },
              { key: "endpoint", label: "Static Endpoint" },
              { key: "connectors", label: "Connectors" },
            ]}
            filters={[
              {
                key: "status",
                label: "Status",
                options: ["Active", "Inactive"],
              },
              {
                key: "online",
                label: "Online Status",
                options: ["Online", "Offline"],
              },
              {
                key: "visibility",
                label: "Public Status",
                options: ["Public", "Private"],
              },
            ]}
            onCreate={
              canManage(role)
                ? () =>
                    setEditing({
                      id: "",
                      name: "",
                      description: "",
                      locationId: "loc-001",
                      location: "Sarinah Thamrin",
                      status: "Active",
                      online: "Offline",
                      visibility: "Public",
                      protocol: "OCPP 1.6",
                      endpoint: "",
                      connectors: 2,
                      vendor: "",
                      model: "",
                      serial: "",
                      power: 22,
                      firmware: "—",
                    })
                : undefined
            }
            actions={
              canManage(role)
                ? (r) => (
                    <>
                      <Button
                        variant="ghost"
                        size="icon"
                        aria-label={`Edit ${r.name}`}
                        onClick={() => setEditing({ ...r })}
                      >
                        <Pencil className="size-4" />
                      </Button>
                      <Button
                        variant="ghost"
                        size="icon"
                        aria-label={`Delete ${r.name}`}
                        onClick={() => setDeleting(r)}
                      >
                        <Trash2 className="size-4" />
                      </Button>
                    </>
                  )
                : undefined
            }
          />
        )}
      </div>
      <Dialog
        open={!!editing}
        onOpenChange={(open) => {
          if (!open) setEditing(null);
        }}
      >
        <DialogContent className="max-h-[90dvh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>
              {editing?.id ? "Edit Chargestation" : "Create Chargestation"}
            </DialogTitle>
            <DialogDescription>
              Local configuration preview. No hardware or infrastructure
              changes.
            </DialogDescription>
          </DialogHeader>
          {editing && (
            <ChargepointEditor
              point={editing}
              points={points}
              onCancel={() => setEditing(null)}
              onSave={(p) => {
                const next = {
                  ...p,
                  id: p.id || `TIAR-PREVIEW-${crypto.randomUUID()}`,
                };
                setPoints((all) =>
                  p.id
                    ? all.map((x) => (x.id === p.id ? next : x))
                    : [next, ...all],
                );
                setEditing(null);
                setNotice("Chargestation saved locally.");
              }}
            />
          )}
        </DialogContent>
      </Dialog>
      <Dialog
        open={!!deleting}
        onOpenChange={(open) => {
          if (!open) setDeleting(null);
        }}
      >
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Delete {deleting?.name}?</DialogTitle>
            <DialogDescription>
              Only the local preview record is removed.
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button variant="outline" onClick={() => setDeleting(null)}>
              Cancel
            </Button>
            <Button
              variant="destructive"
              onClick={() => {
                setPoints((all) => all.filter((p) => p.id !== deleting?.id));
                setDeleting(null);
                setNotice("Chargestation removed locally.");
              }}
            >
              Delete Preview
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </>
  );
}
