"use client";
import { useState, Fragment } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { MoreHorizontal, Plus, Minus, Pencil, Eye } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { TableToolbar } from "@/components/shared/table-toolbar";
import {
  PaginationControls,
  SortHeading,
} from "@/components/shared/query-controls";
import { EmptyState } from "@/components/shared/panel";
import { StatusBadge } from "@/components/shared/status-badge";
import type { SearchableFilterOption } from "@/components/shared/searchable-filter-field";
import type { Pagination } from "@/lib/list-query";
import type { Location } from "@/features/locations/types";
import { ChargepointEditor } from "./chargepoint-editor";
import type { Chargepoint } from "./types";
import { CreateChargepointDialog } from "./create-chargepoint-dialog";
import type { GoogleMapConfig } from "@/components/shared/google-map";
export function ChargepointTable({
  data,
  pagination,
  locations,
  scopeLocation,
  readOnly = false,
  paginationEnabled = true,
  source = "preview",
  searchEnabled = true,
  detailLinksEnabled = !readOnly,
  loadError,
  loadNotice,
  createEnabled = false,
  mapsConfig = { apiKey: "", mapId: "" },
}: {
  data: Chargepoint[];
  pagination: Pagination;
  locations: Location[];
  scopeLocation?: Location;
  readOnly?: boolean;
  paginationEnabled?: boolean;
  source?: "api" | "preview";
  searchEnabled?: boolean;
  detailLinksEnabled?: boolean;
  loadError?: string;
  loadNotice?: string;
  createEnabled?: boolean;
  mapsConfig?: GoogleMapConfig;
}) {
  const router = useRouter();
  const [rowState, setRowState] = useState(() => ({ source: data, rows: data }));
  const rows = rowState.source === data ? rowState.rows : data;
  function setRows(update: Chargepoint[] | ((current: Chargepoint[]) => Chargepoint[])) {
    setRowState((current) => {
      const currentRows = current.source === data ? current.rows : data;
      return {
        source: data,
        rows: typeof update === "function" ? update(currentRows) : update,
      };
    });
  }
  const [expanded, setExpanded] = useState<string[]>([]);
  const [editor, setEditor] = useState(false);
  const [editing, setEditing] = useState<Chargepoint>();
  const [notice, setNotice] = useState("");
  const [createdId, setCreatedId] = useState("");
  return (
    <section className="panel overflow-hidden">
      <TableToolbar
        title="Chargestations"
        description={
          source === "api"
            ? "Chargepoints connected to the CSMS API"
            : "Manage and monitor charging stations"
        }
        searchKey={source === "api" ? "search" : "query"}
        fields={source === "api" ? [
          {
            name: "location_id",
            label: "Location",
            section: "Charging assets",
            searchable: true,
            placeholder: "Search location by name or ID...",
            helperText: "Type to narrow locations, choose a match, or paste its ID.",
            options: locations.map((location): SearchableFilterOption => ({
              label: location.name,
              value: location.id,
              description: location.id,
            })),
          },
          {
            name: "active_only",
            label: "Active status",
            section: "Station details",
            options: [
              { value: "true", label: "Active" },
              { value: "false", label: "Inactive" },
            ],
          },
          { name: "name", label: "Name", section: "Station details", placeholder: "Search by station name" },
          { name: "max_power", label: "Maximum power", section: "Power & connector", type: "number", placeholder: "kW" },
          { name: "power", label: "Power", section: "Power & connector", type: "number", placeholder: "kW" },
          { name: "connector_type", label: "Connector type", section: "Power & connector", placeholder: "Enter connector type" },
          { name: "type", label: "Type", section: "Power & connector", placeholder: "Enter station type" },
        ] : [
            { name: "status", label: "Status", options: ["Active", "Inactive"] },
            { name: "online", label: "Online", options: ["Online", "Offline"] },
            {
              name: "visibility",
              label: "Public",
              options: ["Public", "Private"],
            },
            {
              name: "protocol",
              label: "Protocol",
              options: ["OCPP1.6", "OCPP2.0.1"],
            },
            {
              name: "locationId",
              label: "Location",
              options: locations.map((location) => ({
                label: location.name,
                value: location.id,
              })),
            },
          ]}
        exportIds={rows.map((row) => row.id)}
        exportRows={rows.map((row) => ({
          Name: row.name,
          Location: row.locationName,
          Status: row.status,
          Online: row.online,
          Public: row.visibility,
          Protocol: row.protocol,
          Endpoint: row.endpoint,
        }))}
        showFilters={source === "api" || !readOnly}
        showSearch={source !== "api" || searchEnabled}
        searchDebounceMs={source === "api" && searchEnabled ? 300 : undefined}
        refreshNotice={source === "api" ? "Chargepoint data refreshed" : undefined}
        onCreate={readOnly && !createEnabled ? undefined : () => {
          setEditing(undefined);
          setEditor(true);
        }}
      />
      {loadError && (
        <p role="alert" className="px-5 pb-3 text-destructive">
          {loadError}
        </p>
      )}
      {loadNotice && (
        <p role="status" className="px-5 pb-3 text-sm text-muted-foreground">
          {loadNotice}
        </p>
      )}
      {notice && (
        <p role="status" className="px-5 pb-3 text-muted-foreground">
          {notice}
          {createdId && <Link href={`/chargepoints/${createdId}`} className="ml-2 font-medium text-primary underline">View details</Link>}
        </p>
      )}
      <div className="overflow-x-auto">
        <table className="data-table min-w-[1350px]">
          <caption className="sr-only">Charging stations</caption>
          <thead>
            <tr>
              <th className="w-[72px] max-w-[72px] whitespace-nowrap px-2">
                Expand
              </th>
              {[
                ["Name", "name"],
                ["Location", "locationName"],
                ["Status", "status"],
                ["Online", "online"],
                ["Public", "visibility"],
                ["Protocol", "protocol"],
                ["Static Endpoint", "endpoint"],
              ].map(([label, key]) => (
                source === "preview" ? (
                  <SortHeading key={key} label={label} value={key} />
                ) : (
                  <th key={key}>{label}</th>
                )
              ))}
              <th>Connectors</th>
              {!readOnly && <th>Actions</th>}
            </tr>
          </thead>
          <tbody>
            {rows.map((row) => (
              <Fragment key={row.id}>
                <tr>
                  <td className="w-[72px] max-w-[72px] px-2 text-center">
                    <Button
                      variant="ghost"
                      size="icon-sm"
                      aria-label={`Expand ${row.name}`}
                      aria-expanded={expanded.includes(row.id)}
                      onClick={() =>
                        setExpanded((current) =>
                          current.includes(row.id)
                            ? current.filter((id) => id !== row.id)
                            : [...current, row.id],
                        )
                      }
                    >
                      {expanded.includes(row.id) ? <Minus /> : <Plus />}
                    </Button>
                  </td>
                  <td className="w-[220px] max-w-[220px] font-medium">
                    {detailLinksEnabled ? (
                      <Link
                        href={`/chargepoints/${row.id}`}
                        title={row.name}
                        className="block max-w-[188px] truncate"
                      >
                        {row.name}
                      </Link>
                    ) : (
                      <span
                        title={row.name}
                        className="block max-w-[188px] truncate"
                      >
                        {row.name}
                      </span>
                    )}
                  </td>
                  <td className="w-36">
                    <Link href={`/locations/${row.locationId}`}>
                      {row.locationName}
                    </Link>
                  </td>
                  <td className="w-[104px] max-w-[104px] whitespace-nowrap">
                    <StatusBadge>{row.status}</StatusBadge>
                  </td>
                  <td className="w-[104px] max-w-[104px] whitespace-nowrap">
                    <StatusBadge>{row.online}</StatusBadge>
                  </td>
                  <td className="w-[104px] max-w-[104px] whitespace-nowrap">
                    <StatusBadge>{row.visibility}</StatusBadge>
                  </td>
                  <td className="w-[120px] max-w-[120px] whitespace-nowrap">
                    {row.protocol}
                  </td>
                  <td className="w-[152px] max-w-[152px]">
                    <span
                      className="block max-w-[120px] truncate"
                      title={row.endpoint}
                    >
                      {row.endpoint}
                    </span>
                  </td>
                  <td className="w-[128px] max-w-[128px] space-y-2">
                    {row.connectors.map((connector) => (
                      <div
                        key={connector.id}
                        className="flex items-center gap-1 whitespace-nowrap"
                        title={`Connector ${connector.number}: ${connector.status}`}
                      >
                        <span
                          aria-label={`Connector ${connector.number}`}
                          className="text-xs font-medium text-muted-foreground"
                        >
                          #{connector.number}
                        </span>
                        <StatusBadge>{connector.status}</StatusBadge>
                      </div>
                    ))}
                  </td>
                  {!readOnly && (
                    <td>
                      <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                          <Button
                            variant="ghost"
                            size="icon-sm"
                            aria-label={`Actions for ${row.name}`}
                          >
                            <MoreHorizontal />
                          </Button>
                        </DropdownMenuTrigger>
                        <DropdownMenuContent>
                          <DropdownMenuItem asChild>
                            <Link href={`/chargepoints/${row.id}`}>
                              <Eye />
                              Details
                            </Link>
                          </DropdownMenuItem>
                          <DropdownMenuItem
                            onSelect={() => {
                              setEditing(row);
                              setEditor(true);
                            }}
                          >
                            <Pencil />
                            Edit
                          </DropdownMenuItem>
                        </DropdownMenuContent>
                      </DropdownMenu>
                    </td>
                  )}
                </tr>
                {expanded.includes(row.id) && (
                  <tr>
                    <td colSpan={readOnly ? 9 : 10} className="bg-muted/40">
                      <div
                        className={
                          readOnly
                            ? "grid gap-4 md:grid-cols-2"
                            : "grid gap-4 md:grid-cols-3"
                        }
                      >
                        <div>
                          <span className="metric-label">
                            Device Information
                          </span>
                          <p className="mt-2">
                            Model: {row.model} · Vendor: {row.vendor}
                          </p>
                        </div>
                        <div>
                          <span className="metric-label">Coordinates</span>
                          <p className="mt-2">
                            {row.latitude.toFixed(6)},{" "}
                            {row.longitude.toFixed(6)}
                          </p>
                        </div>
                        {!readOnly && (
                          <div>
                            <span className="metric-label">Connection URL</span>
                            <p className="mt-2">ws://demo.local/{row.endpoint}</p>
                          </div>
                        )}
                      </div>
                    </td>
                  </tr>
                )}
              </Fragment>
            ))}
          </tbody>
        </table>
        {!rows.length && <EmptyState title="No chargepoints found" />}
      </div>
      {(paginationEnabled || source === "api") && (
        <PaginationControls
          navigationEnabled={paginationEnabled}
          pageSizeEnabled={paginationEnabled}
          pagination={{
            ...pagination,
            total: pagination.total + rows.length - data.length,
            end: pagination.end + rows.length - data.length,
          }}
        />
      )}
      {!readOnly && (
        <ChargepointEditor
          open={editor}
          onOpenChange={setEditor}
          chargepoint={editing}
          defaultLocationId={scopeLocation?.id}
          locations={locations}
          onSave={(row) => {
            setRows((current) => {
              const updated = editing
                ? current.map((item) => (item.id === row.id ? row : item))
                : [row, ...current];
              return scopeLocation
                ? updated.filter((item) => item.locationId === scopeLocation.id)
                : updated;
            });
            setNotice("Chargestation saved in this preview.");
          }}
        />
      )}
      {source === "api" && editor && createEnabled && (
        <CreateChargepointDialog
          open={editor}
          onOpenChange={setEditor}
          locations={locations}
          mapsConfig={mapsConfig}
          onCreated={(id) => {
            setCreatedId(id);
            setNotice("Chargepoint created successfully.");
            router.refresh();
          }}
        />
      )}
    </section>
  );
}
