import { QueryTabs } from "@/components/shared/query-controls";
import { Panel, EmptyState } from "@/components/shared/panel";
import { MetricCard } from "@/features/dashboard/metric-card";
import { Chart, ChartPanel } from "@/features/dashboard/chart";
import { ChargepointTable } from "@/features/chargepoints/chargepoint-table";
import { SessionTable } from "@/features/sessions/session-table";
import { OverviewTodayCards } from "@/features/sessions/overview-today-cards";
import { OverviewHistoryPanel } from "@/features/sessions/overview-history";
import type { OverviewToday, OverviewHistory } from "@/features/sessions/overview-contract";
import type { Location, LocationAnalytics } from "./types";
import type { Chargepoint } from "@/features/chargepoints/types";
import type { Session } from "@/features/sessions/types";
import type { Pagination } from "@/lib/list-query";
import type { LocationSiteManagerAccount } from "./related-api-contract";
import { LocationAccounts } from "./location-accounts";
export function LocationDetail({
  location,
  analytics,
  tab,
  chargepoints,
  sessions,
  locations,
  cpPagination,
  sessionPagination,
  relatedDataErrors = [],
  chargepointDataComplete = true,
  sessionDataComplete = true,
  readOnlyRelatedData = false,
  sessionNotice,
  siteManagers,
  siteManagerError,
  canManageSiteManagers = true,
  overview,
  overviewHistory,
  overviewRangeNotice,
}: {
  location: Location;
  analytics: LocationAnalytics | null;
  tab: string;
  chargepoints: Chargepoint[];
  sessions: Session[];
  locations: Location[];
  cpPagination: Pagination;
  sessionPagination: Pagination;
  relatedDataErrors?: string[];
  chargepointDataComplete?: boolean;
  sessionDataComplete?: boolean;
  readOnlyRelatedData?: boolean;
  sessionNotice?: string;
  siteManagers?: LocationSiteManagerAccount[];
  siteManagerError?: string;
  canManageSiteManagers?: boolean;
  overview?: OverviewToday;
  overviewHistory?: OverviewHistory;
  overviewRangeNotice?: string;
}) {
  const todayFormatter = new Intl.DateTimeFormat("en-CA", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    timeZone: "Asia/Jakarta",
  });
  const today = todayFormatter.format(new Date());
  const todaysSessions = sessions.filter((session) => {
    const timestamp = Date.parse(session.start);
    return (
      Number.isFinite(timestamp) &&
      todayFormatter.format(new Date(timestamp)) === today
    );
  });
  const todaysEnergy = todaysSessions.reduce(
    (total, session) => total + session.energy,
    0,
  );
  return (
    <div className="space-y-6">
      {relatedDataErrors.length > 0 && (
        <div
          role="alert"
          className="rounded-xl border border-destructive/30 bg-destructive/5 p-4 text-sm"
        >
          Some related location data could not be loaded. {relatedDataErrors.join(" ")}
        </div>
      )}
      {relatedDataErrors.length === 0 &&
        (!chargepointDataComplete || !sessionDataComplete) && (
          <div
            role="status"
            className="rounded-xl border border-input bg-muted/40 p-4 text-sm text-muted-foreground"
          >
            The API returned a partial related-data list. Counts and tables may be incomplete.
          </div>
        )}
      <QueryTabs
        clearListFilters
        items={[
          { id: "overview", label: "Overview" },
          { id: "chargepoints", label: "Chargepoints" },
          { id: "sessions", label: "Sessions" },
          { id: "accounts", label: "Accounts" },
        ]}
        active={tab}
      />
      {tab === "overview" ? (
        <>
          <div className="grid gap-6 xl:grid-cols-2">
            <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
              <MetricCard
                detail
                label="Online Chargepoints"
                value={
                  chargepointDataComplete
                    ? String(
                        chargepoints.filter((cp) => cp.online === "Online")
                          .length,
                      )
                    : "—"
                }
                description="Currently connected chargepoints"
                icon="power"
              />
              <MetricCard
                detail
                label="Faulted Connectors"
                value={
                  chargepointDataComplete
                    ? String(
                        chargepoints
                          .flatMap((cp) => cp.connectors)
                          .filter((connector) => connector.status === "Faulted")
                          .length,
                      )
                    : "—"
                }
                description="Connectors requiring attention"
                icon="energy"
              />
              {readOnlyRelatedData ? <OverviewTodayCards data={overview} /> : <><MetricCard
                detail
                label="Sessions Today"
                value={sessionDataComplete ? String(todaysSessions.length) : "—"}
                description="Total sessions since 00:00"
                icon="sessions"
              />
              <MetricCard
                detail
                label="Energy Delivered"
                value={sessionDataComplete ? `${todaysEnergy.toFixed(2)} kWh` : "—"}
                description="Total energy since 00:00"
                icon="energy"
              />
              </>}
            </div>
            <Panel title="Connector Status">
              {chargepointDataComplete ? (
                <Chart
                  type="donut"
                  series={[
                    chargepoints
                      .flatMap((cp) => cp.connectors)
                      .filter((connector) => connector.status === "Available")
                      .length,
                    chargepoints
                      .flatMap((cp) => cp.connectors)
                      .filter((connector) => connector.status === "Charging")
                      .length,
                    chargepoints
                      .flatMap((cp) => cp.connectors)
                      .filter((connector) => connector.status === "Faulted")
                      .length,
                  ]}
                  labels={["Available", "Charging", "Faulted"]}
                  height={290}
                />
              ) : (
                <EmptyState
                  title="Connector status unavailable"
                  description="The connector list is incomplete."
                />
              )}
            </Panel>
          </div>
          {analytics ? (
            <>
              <ChartPanel
                title="Energy Delivered"
                series={[{ name: "Energy", data: Array(12).fill(0) }]}
                categories={analytics.months}
                unit="kWh"
              />
              <ChartPanel
                title="Cost Breakdown"
                series={analytics.costSeries}
                categories={analytics.months}
              />
              <div className="grid gap-6 xl:grid-cols-2">
                <ChartPanel
                  title="Utilization"
                  series={analytics.utilizationSeries}
                  categories={["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]}
                  type="area"
                  unit="%"
                />
                <ChartPanel
                  title="Uptime"
                  series={[
                    { name: "Uptime", data: [100, 100, 100, 100, 100, 100, 100] },
                  ]}
                  categories={["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]}
                  type="area"
                  unit="%"
                />
              </div>
            </>
          ) : overviewHistory ? (
            <OverviewHistoryPanel data={overviewHistory} today={overview?.date ?? today} notice={overviewRangeNotice} />
          ) : (
            <Panel title="Location Analytics">
              <EmptyState
                title="Location analytics unavailable"
                description="Location history could not be loaded. Refresh and try again."
              />
            </Panel>
          )}
          <Panel title="Faulted Connectors">
            <table className="data-table">
              <thead>
                <tr>
                  <th>Chargepoint</th>
                  <th>Connector</th>
                  <th>Status</th>
                </tr>
              </thead>
              <tbody>
                {chargepoints.flatMap((cp) =>
                  cp.connectors
                    .filter((c) => c.status === "Faulted")
                    .map((c) => (
                      <tr key={c.id}>
                        <td>{cp.name}</td>
                        <td>{c.number}</td>
                        <td>{c.status}</td>
                      </tr>
                    )),
                )}
              </tbody>
            </table>
            {chargepointDataComplete &&
              !chargepoints.some((cp) =>
                cp.connectors.some((connector) => connector.status === "Faulted"),
              ) && (
              <EmptyState
                title="No faulted connectors"
                description="All connectors are operating normally."
              />
            )}
          </Panel>
        </>
      ) : tab === "chargepoints" ? (
        <ChargepointTable
          data={chargepoints}
          pagination={cpPagination}
          locations={locations}
          scopeLocation={location}
          readOnly={readOnlyRelatedData}
          detailLinksEnabled
          paginationEnabled={chargepointDataComplete}
        />
      ) : tab === "sessions" ? (
        <SessionTable
          data={sessions}
          pagination={sessionPagination}
          source={readOnlyRelatedData ? "api" : "preview"}
          paginationEnabled={!readOnlyRelatedData}
          loadNotice={sessionNotice}
          scopeLocationId={location.id}
          chargepointOptions={chargepoints.map(cp => ({ value: cp.id, label: cp.name }))}
        />
      ) : (
        <LocationAccounts
          location={location}
          accounts={siteManagers}
          error={siteManagerError}
          source={readOnlyRelatedData ? "api" : "preview"}
          canManageSiteManagers={canManageSiteManagers}
        />
      )}
    </div>
  );
}
