import Link from "next/link";
import { Battery } from "lucide-react";
import { QueryTabs } from "@/components/shared/query-controls";
import { Panel } from "@/components/shared/panel";
import { StatusBadge } from "@/components/shared/status-badge";
import { SessionLogsView } from "./session-logs-view";
import type { OcppLog } from "@/features/chargepoints/logs/mock-data";
import { sessionCost, sessionDate, sessionDuration, sessionHasTimingIssue, sessionIsActive, sessionState, sessionStatusLabel, sessionTone } from "./presentation";
import type { Session } from "./types";
import { formatEnergyKwh } from "@/lib/format";
function Timeline({ session }: { session: Session }) {
  return (
    <div className="mt-5 flex flex-col items-center gap-3 rounded-lg border p-4 md:flex-row">
      <span className="whitespace-nowrap text-xs font-medium">
        {sessionDate(session.start)}
      </span>
      <span className="text-xs text-muted-foreground">START</span>
      <span className="size-3 shrink-0 rounded-full bg-success" />
      <div
        className="h-3 w-full rounded-full bg-success"
        role="img"
        aria-label="Charging time"
      />
      <span className="size-3 shrink-0 rounded-full bg-info" />
      <span className="text-xs text-muted-foreground">END</span>
      <span className="whitespace-nowrap text-xs font-medium">
        {sessionIsActive(session) ? "In progress" : sessionDate(session.end)}
      </span>
    </div>
  );
}
export function SessionDetail({
  session,
  tab,
  logs,
  source = "preview",
  logError,
  logNotice,
}: {
  session: Session;
  tab: string;
  logs: OcppLog[];
  source?: "api" | "preview";
  logError?: string;
  logNotice?: string;
}) {
  const battery = session.soc !== null;
  return (
    <div className="space-y-6">
      {sessionHasTimingIssue(session) && <p role="status" className="text-sm text-muted-foreground">This session has inconsistent timestamps; its duration is unavailable.</p>}
      <Panel>
        <div className="flex items-center justify-between gap-4">
          <div>
            <h2 className="text-xl font-semibold">Session Details</h2>
            <p className="mt-2 break-all text-muted-foreground">
              Session ID: {session.id}
            </p>
            <p className="mt-1 text-muted-foreground">
              Transaction ID:{" "}
              <span className="font-medium text-foreground">
                {session.transactionId || "—"}
              </span>
            </p>
            {session.ocppTransactionId && <p className="mt-1 break-all text-muted-foreground">
              OCPP Transaction ID:{" "}
              <span className="font-medium text-foreground">{session.ocppTransactionId}</span>
            </p>}
          </div>
          <StatusBadge tone={sessionTone(session.status)}>{sessionStatusLabel(session.status)}</StatusBadge>
        </div>
        {!battery && <Timeline session={session} />}
      </Panel>
      {battery && (
        <Panel title="Charging Progress">
          <div
            className="mx-auto mt-3 flex h-48 w-24 items-end overflow-hidden rounded-xl border-4 border-input bg-muted"
            role="meter"
            aria-label="State of charge"
            aria-valuemin={0}
            aria-valuemax={100}
            aria-valuenow={session.soc ?? 0}
          >
            <div
              className="relative flex w-full items-center justify-center bg-success/60"
              style={{ height: `${Math.max(20, session.soc ?? 0)}%` }}
            >
              <Battery className="my-4 size-8 text-muted-foreground" />
            </div>
          </div>
          <div className="mx-auto mt-5 grid max-w-lg grid-cols-3 gap-4 text-center">
            <div>
              <p className="text-base font-semibold">
                {sessionState(session.status)}
              </p>
              <p className="mt-1 text-muted-foreground">State</p>
            </div>
            <div>
              <p className="text-2xl font-semibold">{session.soc ?? 0}%</p>
              <p className="mt-1 text-muted-foreground">State of Charge</p>
            </div>
            <div>
              <p className="text-2xl font-semibold">
                {sessionDuration(session)}
              </p>
              <p className="mt-1 text-muted-foreground">Duration</p>
            </div>
          </div>
          <Timeline session={session} />
        </Panel>
      )}
      <QueryTabs
        items={[
          { id: "overview", label: "Overview" },
          { id: "logs", label: "Logs" },
        ]}
        active={tab}
      />
      {tab === "logs" ? (
        <SessionLogsView
          data={logs}
          sessionId={session.id}
          sessionWindow={{ start: session.start, end: session.end }}
          source={source}
          loadError={logError}
          loadNotice={logNotice}
        />
      ) : (
        <>
          <Panel title="Relations">
            <dl className="grid gap-4 md:grid-cols-3">
              <div>
                <dt className="metric-label">Location</dt>
                <dd className="mt-1">
                  {session.locationId ? <Link
                    className="underline hover:text-primary"
                    href={`/locations/${session.locationId}`}
                  >
                    {session.locationName}
                  </Link> : session.locationName}
                </dd>
              </div>
              <div>
                <dt className="metric-label">Chargepoint</dt>
                <dd className="mt-1">
                  {session.chargepointId ? <Link
                    className="underline hover:text-primary"
                    href={`/chargepoints/${session.chargepointId}`}
                  >
                    {session.chargepointName}
                  </Link> : session.chargepointName}
                </dd>
              </div>
              <div>
                <dt className="metric-label">User</dt>
                <dd className="mt-1">{session.userId ? <Link className="underline hover:text-primary" href={`/customers/${encodeURIComponent(session.userId)}`} prefetch={false}>{session.userName === "—" ? "View user" : session.userName}</Link> : session.userName}</dd>
              </div>
            </dl>
          </Panel>
          <Panel>
            <div className="grid gap-4 xl:grid-cols-5">
              <section className="rounded-lg border p-4 xl:col-span-3">
                <h2 className="text-base font-semibold">Cost</h2>
                <p className="metric-label mt-4">Total Cost</p>
                <p className="mt-1 text-2xl font-bold md:text-3xl">
                  {sessionCost(session.cost, session.currency)}
                </p>
                <dl className="mt-4 space-y-2 rounded-lg border p-3">
                  {session.breakdown.map((item, index) => (
                    <div
                      key={`${item.type}:${item.name}:${index}`}
                      className="flex flex-wrap items-center justify-between gap-2"
                    >
                      <dt className="text-muted-foreground">
                        {item.name}
                      </dt>
                      <dd className="whitespace-nowrap">{sessionCost(item.amount, session.currency)}</dd>
                    </div>
                  ))}
                </dl>
              </section>
              <section className="rounded-lg border p-4 xl:col-span-2">
                <h2 className="text-base font-semibold">Energy</h2>
                <dl className="mt-4 grid gap-4 md:grid-cols-2">
                  {[
                    ["Energy Consumed", `${formatEnergyKwh(session.energy)} kWh`],
                    [
                      "Charging Time",
                      sessionDuration(session),
                    ],
                    ["Power", session.power !== null ? `${session.power.toFixed(2)} kW` : "—"],
                    ["Current", session.current !== null ? `${session.current.toFixed(2)} A` : "—"],
                  ].map(([label, value]) => (
                    <div key={label} className="rounded-lg border p-4">
                      <dt className="metric-label">{label}</dt>
                      <dd className="mt-1">{value}</dd>
                    </div>
                  ))}
                </dl>
              </section>
            </div>
          </Panel>
          <Panel title="Technical Details">
            <div className="grid gap-3 md:grid-cols-2">
              <p>
                <span className="font-medium">ID Tag:</span> {session.idTag || "—"}
              </p>
              <p>
                <span className="font-medium">Connector:</span>{" "}
                {session.connector || "—"}
              </p>
              <p>
                <span className="font-medium">Rate:</span> {session.rateName || "—"}
              </p>
              <p>
                <span className="font-medium">SOC:</span> {session.soc ?? "—"}%
              </p>
            </div>
          </Panel>
          <Panel title="Charging Activity">
            {session.stopReason && <div className="mb-3 rounded-lg border bg-muted/40 p-3">
              <p className="metric-label">Stop Reason</p>
              <p className="mt-1 text-sm font-medium">{session.stopReason}</p>
            </div>}
            <div className="flex flex-col justify-between gap-2 rounded-lg border p-3 md:flex-row">
              <StatusBadge tone={sessionTone(session.status)}>
                {session.status === "Started" ? "Charging" : sessionStatusLabel(session.status)}
              </StatusBadge>
              <p>
                {sessionDate(session.start)} - {sessionDate(session.end)}
              </p>
            </div>
          </Panel>
        </>
      )}
    </div>
  );
}
