"use client";
import dynamic from "next/dynamic";
import { useTheme } from "next-themes";
import { useState } from "react";
import type { ReactNode } from "react";
import type { ApexTooltipCustomOpts } from "apexcharts";
import { Button } from "@/components/ui/button";
import {
  CalendarDays,
  ChevronDown,
  ChevronLeft,
  ChevronRight,
} from "lucide-react";
import { Panel } from "./page";
export const DashboardChart = dynamic(() => import("react-apexcharts"), {
  ssr: false,
  loading: () => (
    <div className="flex h-64 items-center justify-center text-muted-foreground">
      Loading chart…
    </div>
  ),
});
export type ChartSeries = { name: string; data: number[] }[];
const DATE_CATEGORY_PAGE_SIZE = 7;
const regularAxisNumber = new Intl.NumberFormat("en-US", {
  maximumFractionDigits: 2,
});
const compactAxisNumber = new Intl.NumberFormat("en-US", {
  notation: "compact",
  compactDisplay: "short",
  maximumFractionDigits: 1,
});

function formatDateCategory(value: string) {
  const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value);
  if (!match) return value;

  const [, year, month, day] = match;
  const monthLabel = new Intl.DateTimeFormat("en-US", {
    month: "short",
    timeZone: "UTC",
  }).format(new Date(Date.UTC(Number(year), Number(month) - 1, Number(day))));

  return `${monthLabel} ${Number(day)}`;
}

function formatPeriodRange(startDate: string, endDate: string) {
  const start = new Date(`${startDate}T00:00:00.000Z`);
  const end = new Date(`${endDate}T00:00:00.000Z`);
  const format = (date: Date) =>
    new Intl.DateTimeFormat("en-US", {
      month: "short",
      day: "numeric",
      timeZone: "UTC",
    }).format(date);
  return `${format(start)} – ${format(end)}`;
}

function formatAxisValue(value: number) {
  return Math.abs(value) < 10_000
    ? regularAxisNumber.format(value)
    : compactAxisNumber.format(value);
}

export function ChartPanel({
  title,
  type = "bar",
  series,
  categories = [],
  height = 300,
  colors,
  tooltipCustom,
  toolbar,
  paginateDates = true,
  horizontal = false,
  stacked = false,
  bare = false,
  barDataLabelFormatter,
  categoryLabelFormatter,
  loading = false,
  error = null,
}: {
  title: string;
  type?: "area" | "bar" | "donut" | "line";
  series: ChartSeries;
  categories?: string[];
  height?: number;
  colors?: string[];
  tooltipCustom?: (options: ApexTooltipCustomOpts) => string;
  toolbar?: ReactNode;
  paginateDates?: boolean;
  horizontal?: boolean;
  stacked?: boolean;
  bare?: boolean;
  barDataLabelFormatter?: (value: number) => string;
  categoryLabelFormatter?: (value: string) => string | string[];
  loading?: boolean;
  error?: string | null;
}) {
  const { resolvedTheme } = useTheme();
  const categoryKey = JSON.stringify(categories);
  const [pagination, setPagination] = useState({ categoryKey: "", page: 0 });
  const datePage = pagination.categoryKey === categoryKey ? pagination.page : 0;
  const hasDateCategories = categories.every((category) =>
    /^\d{4}-\d{2}-\d{2}$/.test(category),
  );
  const canPaginate =
    paginateDates &&
    type !== "donut" &&
    hasDateCategories &&
    categories.length > DATE_CATEGORY_PAGE_SIZE;
  const pageCount = Math.ceil(categories.length / DATE_CATEGORY_PAGE_SIZE);
  const currentPage = Math.min(datePage, Math.max(pageCount - 1, 0));
  const visibleStart = canPaginate
    ? Math.max(
        0,
        categories.length - (currentPage + 1) * DATE_CATEGORY_PAGE_SIZE,
      )
    : 0;
  const visibleEnd = canPaginate
    ? categories.length - currentPage * DATE_CATEGORY_PAGE_SIZE
    : categories.length;
  const visibleCategories = categories.slice(visibleStart, visibleEnd);
  const visibleSeries = canPaginate
    ? series.map((item) => ({
        ...item,
        data: item.data.slice(visibleStart, visibleEnd),
      }))
    : series;
  const periods = canPaginate
    ? Array.from({ length: pageCount }, (_, index) => {
        const page = pageCount - index - 1;
        const end = categories.length - page * DATE_CATEGORY_PAGE_SIZE;
        const start = Math.max(0, end - DATE_CATEGORY_PAGE_SIZE);
        return {
          page,
          label: formatPeriodRange(categories[start]!, categories[end - 1]!),
        };
      })
    : [];

  return (
    <Panel
      title={bare ? undefined : title}
      className={bare ? "border-0 bg-transparent" : ""}
    >
      {toolbar && (
        <div className="relative z-20 border-b px-5 py-3">{toolbar}</div>
      )}
      {canPaginate && (
        <div className="flex justify-end border-b px-5 py-3">
          <div className="flex w-full max-w-[280px] flex-col items-end gap-1.5">
            <span className="text-xs font-medium text-muted-foreground">
              Period
            </span>
            <div className="flex w-full items-center">
              <Button
                type="button"
                variant="outline"
                size="icon"
                className="h-9 w-9 shrink-0 rounded-l-xl rounded-r-none"
                disabled={currentPage >= pageCount - 1}
                aria-label="Previous period"
                onClick={() =>
                  setPagination({
                    categoryKey,
                    page: Math.min(pageCount - 1, currentPage + 1),
                  })
                }
              >
                <ChevronLeft className="size-4" aria-hidden="true" />
              </Button>
              <div className="relative -ml-px min-w-0 flex-1">
                <CalendarDays
                  className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground"
                  aria-hidden="true"
                />
                <select
                  aria-label="Select date period"
                  className="h-9 w-full appearance-none rounded-none border border-border bg-background pl-9 pr-8 text-xs font-semibold text-foreground outline-none focus-visible:ring-2 focus-visible:ring-ring"
                  value={currentPage}
                  onChange={(event) =>
                    setPagination({
                      categoryKey,
                      page: Number(event.target.value),
                    })
                  }
                >
                  {periods.map((period) => (
                    <option key={period.page} value={period.page}>
                      {period.label}
                    </option>
                  ))}
                </select>
                <ChevronDown
                  className="pointer-events-none absolute right-2.5 top-1/2 size-3 -translate-y-1/2 text-muted-foreground"
                  aria-hidden="true"
                />
              </div>
              <Button
                type="button"
                variant="outline"
                size="icon"
                className="-ml-px h-9 w-9 shrink-0 rounded-l-none rounded-r-xl"
                disabled={currentPage === 0}
                aria-label="Next period"
                onClick={() =>
                  setPagination({
                    categoryKey,
                    page: Math.max(0, currentPage - 1),
                  })
                }
              >
                <ChevronRight className="size-4" aria-hidden="true" />
              </Button>
            </div>
          </div>
        </div>
      )}
      {error ? (
        <p role="alert" className="p-8 text-center text-sm text-destructive">
          {error}
        </p>
      ) : loading ? (
        <div className="flex h-64 items-center justify-center text-muted-foreground">
          Loading chart…
        </div>
      ) : (
        <div
          className="chart-container overflow-hidden p-4"
          role="img"
          aria-label={`${title}: ${visibleSeries.map((s) => `${s.name}: ${s.data.join(", ")}`).join("; ")}`}
        >
          <DashboardChart
            type={type}
            height={height}
            series={type === "donut" ? (visibleSeries[0]?.data ?? []) : visibleSeries}
            options={{
            chart: {
              toolbar: { show: false },
              stacked,
              fontFamily: "inherit",
              background: "transparent",
              foreColor: "var(--muted-foreground)",
            },
            theme: { mode: resolvedTheme === "dark" ? "dark" : "light" },
            colors: colors ?? [
              "var(--chart-1)",
              "var(--chart-2)",
              "var(--chart-3)",
              "var(--chart-4)",
            ],
            labels: visibleCategories,
            xaxis: {
              categories: visibleCategories,
              labels: {
                formatter: (value: string | number) =>
                  horizontal
                    ? formatAxisValue(Number(value))
                    : categoryLabelFormatter
                      ? categoryLabelFormatter(String(value))
                      : formatDateCategory(String(value)),
                rotate: categoryLabelFormatter ? 0 : undefined,
              },
            },
            yaxis: horizontal
              ? {
                  labels: {
                    maxWidth: 180,
                    formatter: (value: number) => {
                      const label = String(value);
                      return label.length > 22
                        ? label.slice(0, 21) + "…"
                        : label;
                    },
                  },
                }
              : {
                  labels: {
                    formatter: (value: number) => formatAxisValue(value),
                  },
                },
            dataLabels: barDataLabelFormatter
              ? {
                  enabled: true,
                  formatter: (value: number) => barDataLabelFormatter(value),
                  style: {
                    colors: ["#ffffff"],
                    fontSize: "11px",
                    fontWeight: 700,
                  },
                }
              : { enabled: false },
            stroke: {
              curve: "smooth",
              width: type === "line" || type === "area" ? 2 : 0,
            },
            legend: { position: "bottom" },
            grid: { borderColor: "var(--border)" },
            plotOptions: {
              bar: {
                horizontal,
                borderRadius: horizontal ? 10 : 4,
                borderRadiusApplication: "end",
                columnWidth: "45%",
                barHeight: horizontal ? "62%" : undefined,
                dataLabels: horizontal ? { position: "center" } : undefined,
              },
            },
            tooltip: {
              theme: resolvedTheme === "dark" ? "dark" : "light",
              custom: tooltipCustom,
            },
            }}
          />
        </div>
      )}
    </Panel>
  );
}
