"use client";
import dynamic from "next/dynamic";
import { useState } from "react";
import { SelectField } from "@/components/shared/form-field";
import { Panel } from "@/components/shared/panel";
import { cn } from "@/lib/utils";
import type { ChartSeries, ChartPeriods } from "./types";
const RenderChart = dynamic(() => import("./render-chart"), {
  ssr: false,
  loading: () => (
    <div
      className="h-[315px] animate-pulse rounded-lg bg-muted/40"
      role="status"
      aria-label="Loading chart"
    />
  ),
});
export type ChartProps = {
  type: "bar" | "area" | "donut";
  series: ChartSeries | number[];
  categories?: string[];
  labels?: string[];
  height?: number;
  unit?: string;
  appearance?: "default" | "compact";
  showLegend?: boolean;
  showDonutTotal?: boolean;
};
export function Chart(props: ChartProps) {
  return (
    <div className="chart-container min-w-0">
      <RenderChart {...props} />
      <div className="sr-only">
        <table className="mt-2 w-full">
          <caption className="sr-only">Chart values</caption>
          <tbody>
            {props.series.map((series, index) =>
              typeof series === "number" ? (
                <tr key={index}>
                  <th className="py-1 text-left">
                    {props.labels?.[index] ?? index + 1}
                  </th>
                  <td>{series}</td>
                </tr>
              ) : (
                <tr key={series.name}>
                  <th className="py-1 text-left">{series.name}</th>
                  <td>{series.data.join(", ")}</td>
                </tr>
              ),
            )}
          </tbody>
        </table>
      </div>
    </div>
  );
}
export function ChartPanel({
  title,
  series,
  categories,
  type = "bar",
  unit,
  periodsData,
  locationPeriods,
  locations,
}: {
  title: string;
  series: ChartSeries;
  categories: string[];
  type?: "bar" | "area";
  unit?: string;
  periodsData?: ChartPeriods;
  locationPeriods?: Record<string, ChartPeriods>;
  locations?: { id: string; name: string }[];
}) {
  const [location, setLocation] = useState("");
  const [period, setPeriod] = useState("Daily");
  const periods = ["Daily", "Weekly", "Monthly", "Yearly"];
  const filtered = series.map((s) => ({
    ...s,
    data:
      period === "Daily"
        ? s.data.slice(-7)
        : period === "Weekly"
          ? s.data.slice(-4)
          : period === "Yearly"
            ? [
                s.data.reduce((a, b) => a + b, 0) /
                  (unit === "%" ? Math.max(s.data.length, 1) : 1),
              ]
            : s.data,
  }));
  const labels =
    period === "Daily"
      ? ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
      : period === "Weekly"
        ? ["Week 1", "Week 2", "Week 3", "Week 4"]
        : period === "Yearly"
          ? ["2026"]
          : categories;
  const selectedPeriods = location ? locationPeriods?.[location] : periodsData;
  const plotted = selectedPeriods?.[period] ?? {
    series: filtered,
    categories: labels,
  };
  return (
    <Panel
      className="rounded-2xl"
      title={title}
      description={
        period === "Daily"
          ? "This Week (Mon-Sun)"
          : period === "Weekly"
            ? "This Month"
            : period === "Monthly"
              ? "This Year"
              : "All Years"
      }
    >
      <div className="mb-3 flex flex-wrap items-center justify-between gap-4">
        {locations ? (
          <div className="w-full sm:w-64">
            <SelectField
              label="Filter by location"
              name="chart-location"
              value={location}
              onChange={(e) => setLocation(e.target.value)}
              options={[
                { value: "", label: "All locations" },
                ...locations.map((row) => ({ value: row.id, label: row.name })),
              ]}
            />
          </div>
        ) : (
          <span />
        )}
        <div
          className="flex max-w-full flex-wrap rounded-lg border p-1"
          role="group"
          aria-label={`${title} reporting period`}
        >
          {periods.map((p) => (
            <button
              key={p}
              aria-pressed={p === period}
              className={cn(
                "rounded-md px-3 py-2 text-xs font-medium",
                p === period
                  ? "bg-muted text-foreground"
                  : "text-muted-foreground",
              )}
              onClick={() => setPeriod(p)}
            >
              {p}
            </button>
          ))}
        </div>
      </div>
      <Chart
        type={type}
        series={plotted.series}
        categories={plotted.categories}
        unit={unit}
      />
    </Panel>
  );
}
