"use client";

import { useState, useTransition } from "react";
import { Loader2 } from "lucide-react";
import { Chart } from "@/features/dashboard/chart";
import { Panel, EmptyState } from "@/components/shared/panel";
import { Button } from "@/components/ui/button";
import { useQueryUpdate } from "@/components/shared/query-controls";
import { formatEnergyKwh } from "@/lib/format";
import { overviewPeriods, overviewPeriodRange } from "./overview-contract";
import type { OverviewHistory, OverviewPeriod } from "./overview-contract";

export function OverviewHistoryPanel({ data, today, notice }: { data: OverviewHistory; today: string; notice?: string }) {
  const update = useQueryUpdate();
  const [pending, startTransition] = useTransition();
  const [requestedPeriod, setRequestedPeriod] = useState<OverviewPeriod | null>(null);
  const dateLabel = new Intl.DateTimeFormat("en-GB", { timeZone: "Asia/Jakarta", day: "2-digit", month: "short" });
  const activePeriod = data.period ?? overviewPeriods.find(item => {
    const range = overviewPeriodRange(item.id, today);
    return range.start === data.range.start && range.end === data.range.end;
  })?.id;
  function changePeriod(period: OverviewPeriod) {
    setRequestedPeriod(period);
    startTransition(() => update({ overview_period: period, overview_from: null, overview_to: null, paginate_page: null }));
  }
  const summaries = [
    { title: "Energy Delivered", name: "Energy", unit: "kWh", metric: data.energy, type: "bar" as const },
    { title: "Utilization", name: "Utilization", unit: "%", metric: data.utilization, type: "area" as const },
  ];
  return <Panel title="Location Analytics" description={`${data.range.start} – ${data.range.end} · WIB`}>
    <div className="mb-5 flex flex-wrap items-center gap-3">
      <div role="group" aria-label="Analytics period" aria-busy={pending} className="grid w-full grid-cols-3 gap-1 rounded-xl border bg-muted/30 p-1 sm:flex sm:w-auto sm:flex-wrap">
        {overviewPeriods.map(period => <Button key={period.id} type="button" variant="ghost" disabled={pending} aria-pressed={activePeriod === period.id} onClick={() => changePeriod(period.id)} className="px-2 text-xs text-muted-foreground aria-pressed:border-border aria-pressed:bg-card aria-pressed:text-foreground aria-pressed:shadow-sm sm:px-4 sm:text-sm">
          {period.label}
        </Button>)}
      </div>
      <span role="status" className="flex min-h-5 items-center gap-2 text-xs text-muted-foreground">
        {pending && <><Loader2 aria-hidden="true" className="size-3.5 animate-spin motion-reduce:animate-none" />Updating {overviewPeriods.find(period => period.id === requestedPeriod)?.label.toLowerCase()}…</>}
      </span>
    </div>
    {notice && <p role="alert" className="mb-4 text-sm text-destructive">{notice}</p>}
    <div aria-busy={pending} className="grid min-w-0 gap-5 xl:grid-cols-2">
      {summaries.map(({ title, name, unit, metric, type }) => <section key={title} aria-label={`${title} history`} className="min-w-0 rounded-xl border p-4">
        <div className="mb-4 flex flex-wrap items-start justify-between gap-2"><h3 className="font-semibold">{title}</h3><p className="text-sm font-semibold tabular-nums">{metric.error || !metric.data ? "Unavailable" : `${unit === "kWh" ? formatEnergyKwh(metric.data.total) : metric.data.total.toLocaleString("en-GB", { maximumFractionDigits: 2 })} ${unit}`}</p></div>
        {metric.error ? <p role="alert" className="py-6 text-sm text-destructive">{metric.error}</p> : metric.data?.points.length ? <Chart type={type} series={[{ name, data: metric.data.points.map(point => point.value) }]} categories={metric.data.points.map(point => dateLabel.format(new Date(point.start)))} unit={unit} /> : <EmptyState title="No daily values returned" description="The API returned no daily values for this date range." />}
      </section>)}
    </div>
  </Panel>;
}
