"use client";

import * as React from "react";
import { format, parseISO } from "date-fns";
import {
  CartesianGrid,
  Line,
  LineChart as RechartsLineChart,
  XAxis,
  YAxis,
} from "recharts";

import { Button } from "@/components/ui/button";
import {
  ChartContainer,
  ChartTooltip,
  ChartTooltipContent,
  type ChartConfig,
} from "@/components/ui/chart";
import { cn } from "@/lib/utils";

import { ReportLoadingPanel } from "@/app/customer/[tenant]/reports/_shared/components/report-loading-panel";
import { type PortfolioAnalyticsFilters, isFilterFullySelected } from "./schema";
import { CHART_COLORS, buildChartData, formatCompact } from "./utils";

export type PortfolioAnalyticsChartSeries = { id: string; name: string };

export function PortfolioAnalyticsChartPanel({
  isLoading,
  chartData,
  chartSeriesConfig,
  visibleChartSeries,
  apiSeries,
  filters,
  filterOptionLists,
  focusedSeries,
  onLegendClick,
  onClearFocus,
}: {
  isLoading: boolean;
  chartData: ReturnType<typeof buildChartData>;
  chartSeriesConfig: ChartConfig;
  visibleChartSeries: PortfolioAnalyticsChartSeries[];
  apiSeries: PortfolioAnalyticsChartSeries[];
  filters: PortfolioAnalyticsFilters;
  filterOptionLists: { assetClasses: string[] };
  focusedSeries: string | null;
  onLegendClick: (seriesId: string) => void;
  onClearFocus: () => void;
}) {
  return (
    <section className="overflow-hidden rounded-2xl border border-border/70 bg-card shadow-[0_1px_2px_rgba(0,0,0,0.04)]">
      <div className="flex items-start justify-between gap-3 border-border/60 border-b px-5 py-4">
        <div>
          <h2 className="font-medium text-sm tracking-tight">Asset values over time</h2>
          <p className="mt-0.5 text-muted-foreground text-xs">
            Click a series to isolate it
            {focusedSeries ? " · one series selected" : ""}
          </p>
        </div>
      </div>
      <div className="px-3 pt-4 pb-2 sm:px-5">
        <ReportLoadingPanel
          loading={isLoading}
          label="Loading portfolio analytics…"
          minHeightClassName="min-h-[340px]"
          className={cn(isLoading && "pointer-events-none")}
        >
          {chartData.length === 0 ? (
            !isLoading ? (
              <div className="flex h-[340px] items-center justify-center text-muted-foreground text-sm">
                No chart data for the selected filters
              </div>
            ) : (
              <div className="h-[340px]" aria-hidden />
            )
          ) : (
            <ChartContainer config={chartSeriesConfig} className="aspect-auto h-[340px] w-full">
              <RechartsLineChart data={chartData} margin={{ top: 8, right: 12, left: 4, bottom: 0 }}>
                <CartesianGrid strokeDasharray="3 3" vertical={false} className="stroke-border/50" />
                <XAxis
                  dataKey="date"
                  tickLine={false}
                  axisLine={false}
                  tickMargin={10}
                  tickFormatter={(value) => format(parseISO(String(value)), "d MMM")}
                  className="text-[11px] text-muted-foreground"
                />
                <YAxis
                  tickLine={false}
                  axisLine={false}
                  tickMargin={8}
                  tickFormatter={(value) => formatCompact(Number(value))}
                  className="text-[11px] text-muted-foreground tabular-nums"
                />
                <ChartTooltip
                  content={
                    <ChartTooltipContent
                      labelFormatter={(value) => format(parseISO(String(value)), "EEEE, d MMM yyyy")}
                      formatter={(value, name) => (
                        <span className="font-medium tabular-nums">
                          {chartSeriesConfig[String(name)]?.label ?? name}:{" "}
                          {Number(value).toLocaleString("en-US", { minimumFractionDigits: 2 })}
                        </span>
                      )}
                    />
                  }
                />
                {visibleChartSeries.map((series) => (
                  <Line
                    key={series.id}
                    type="monotone"
                    dataKey={series.id}
                    name={series.id}
                    stroke={`var(--color-${series.id})`}
                    strokeWidth={focusedSeries || series.id === "ALL" ? 2.25 : 1.5}
                    strokeOpacity={focusedSeries && focusedSeries !== series.id ? 0.25 : 1}
                    dot={false}
                    activeDot={{ r: 4, strokeWidth: 0 }}
                    connectNulls
                  />
                ))}
              </RechartsLineChart>
            </ChartContainer>
          )}
        </ReportLoadingPanel>
        <div className="mt-3 mb-4 flex flex-wrap items-center gap-1.5">
          {apiSeries
            .filter((s) => {
              if (!isFilterFullySelected(filters.assetClasses, filterOptionLists.assetClasses)) {
                const allowed = new Set(filters.assetClasses);
                return s.id === "ALL" || allowed.has(s.name);
              }
              return true;
            })
            .map((series) => {
              const color = chartSeriesConfig[series.id]?.color ?? CHART_COLORS[0];
              const isolated = focusedSeries === series.id;
              const dimmed = focusedSeries && !isolated;
              return (
                <button
                  key={series.id}
                  type="button"
                  onClick={() => onLegendClick(series.id)}
                  className={cn(
                    "inline-flex items-center gap-2 rounded-full border border-transparent px-2.5 py-1 text-xs transition-colors",
                    isolated && "border-border bg-muted/60 font-medium text-foreground",
                    !isolated && "text-muted-foreground hover:bg-muted/40 hover:text-foreground",
                    dimmed && "opacity-40",
                  )}
                >
                  <span className="size-1.5 rounded-full" style={{ backgroundColor: color }} />
                  {series.name}
                </button>
              );
            })}
          {focusedSeries ? (
            <Button
              variant="ghost"
              size="sm"
              className="h-7 px-2 text-muted-foreground text-xs"
              onClick={onClearFocus}
            >
              Show all
            </Button>
          ) : null}
        </div>
      </div>
    </section>
  );
}
