"use client";
import { useSearchParams } from "next/navigation";
import {
  PageHeader,
  Panel,
  DetailList,
  Metric,
  StatusBadge,
} from "@/components/shared/page";
import { Tabs } from "@/components/shared/tabs";
import { DataTable } from "@/components/shared/data-table";
import {
  usePreviewRole,
  PreviewLink,
} from "@/components/layout/preview-context";
import { isManager } from "@/lib/preview";
import { currency } from "@/lib/format";
import { financials, locationSessions } from "./fixtures";
import { useLocations } from "./store";
import { scopedLocations } from "./model";
import { FinancialReport } from "./financial-report";
export function LocationDetail({ id }: { id: string }) {
  const { locations } = useLocations();
  const role = usePreviewRole(),
    params = useSearchParams(),
    manager = isManager(role),
    investor = role === "investor";
  const location = scopedLocations(locations, role).find(
    (row) => row.id === id,
  );
  if (!location)
    return (
      <>
        <PageHeader title="Location unavailable" />
        <Panel title="Location unavailable">
          <p className="p-5 text-muted-foreground">
            This location does not exist or is outside your assigned preview
            scope.
          </p>
          <div className="px-5 pb-5">
            <PreviewLink href="/locations" className="text-primary">
              Back to Locations
            </PreviewLink>
          </div>
        </Panel>
      </>
    );
  const items = manager
    ? [{ value: "sessions", label: "Sessions" }]
    : investor
      ? [
          { value: "financial", label: "Financial Report" },
          { value: "chargepoints", label: "Chargepoints" },
        ]
      : [
          { value: "overview", label: "Overview" },
          { value: "chargepoints", label: "Chargepoints" },
          { value: "sessions", label: "Sessions" },
          { value: "accounts", label: "Accounts" },
        ];
  const requested = params.get("tab"),
    tab = manager
      ? "sessions"
      : (items.find((item) => item.value === requested)?.value ??
        items[0].value);
  return (
    <div className="space-y-5">
      <PageHeader
        title={location.name}
        parent={{
          label: investor ? "Financial Report" : "Locations",
          href: "/locations",
        }}
      />
      <Tabs items={items} value={tab} />
      {tab === "overview" && (
        <>
          <div className="grid gap-4 sm:grid-cols-3">
            <Metric label="Chargepoints" value={location.chargepoints} />
            <Metric
              label="Connector Availability"
              value={`${location.connectors - 1} / ${location.connectors}`}
              note="One connector is currently in use"
            />
            <Metric
              label="Uptime"
              value={`${location.uptime}%`}
              note="Last 30 days"
            />
          </div>
          <div className="grid gap-5 xl:grid-cols-2">
            <Panel title="Site Information">
              <DetailList
                items={{
                  Name: location.name,
                  "Email address": location.email,
                  Phone: location.phone,
                  Organization: location.organization,
                  Status: <StatusBadge>{location.status}</StatusBadge>,
                }}
              />
            </Panel>
            <Panel title="Address">
              <DetailList
                items={{
                  Country: location.country,
                  "City / State": `${location.city} / ${location.state}`,
                  "Postal Code": location.postalCode,
                  "Full Address": location.street,
                  Coordinates: `${location.latitude}, ${location.longitude}`,
                }}
              />
            </Panel>
          </div>
          <Panel title="Faulted Connectors">
            <p className="p-8 text-center text-sm text-muted-foreground">
              No faulted connectors at this location.
            </p>
          </Panel>
        </>
      )}
      {tab === "financial" && <FinancialReport locationId={id} embedded />}
      {tab === "chargepoints" && (
        <DataTable
          title="Chargepoints"
          rows={financials.filter((row) => row.locationId === id)}
          columns={[
            {
              key: "chargepoint",
              label: "Chargepoint",
              render: (row) =>
                investor ? (
                  <PreviewLink
                    className="text-primary"
                    href={`/locations/${id}?tab=financial&chargepoint=${row.chargepoint}`}
                  >
                    {row.chargepoint} · Financial Report
                  </PreviewLink>
                ) : (
                  <PreviewLink
                    className="text-primary"
                    href={`/chargepoints/${row.chargepoint}`}
                  >
                    {row.chargepoint}
                  </PreviewLink>
                ),
            },
            { key: "kwh", label: "Energy (kWh)" },
            { key: "sessions", label: "Sessions" },
            {
              key: "gross",
              label: "Gross Revenue",
              render: (row) => currency(row.gross),
            },
          ]}
        />
      )}{" "}
      {tab === "sessions" && (
        <>
          {manager && <FinancialReport locationId={id} embedded />}
          <DataTable
            title="Sessions"
            description={`Sessions at ${location.name}`}
            rows={locationSessions.filter((row) => row.locationId === id)}
            columns={[
              {
                key: "id",
                label: "Session ID",
                render: (row) => <span>{row.id}</span>,
              },
              { key: "chargepoint", label: "Chargepoint" },
              { key: "started", label: "Started" },
              { key: "energy", label: "Energy (kWh)" },
              {
                key: "amount",
                label: "Amount",
                render: (row) => currency(row.amount),
              },
              {
                key: "status",
                label: "Status",
                render: (row) => <StatusBadge>{row.status}</StatusBadge>,
              },
            ]}
            filters={[
              {
                key: "status",
                label: "Status",
                options: ["Completed", "Charging"],
              },
            ]}
          />
        </>
      )}
      {tab === "accounts" && (
        <Panel title="Site Manager Accounts">
          <DetailList
            items={{
              Name: "Rizky Pratama",
              Email: "rizky@example.test",
              Role: "Site Manager",
              "Assigned Location": location.name,
              Status: <StatusBadge>Active</StatusBadge>,
            }}
          />
        </Panel>
      )}
    </div>
  );
}
