'use client';

/**
 * Composers / Writers Dashboard — Income distribution and trends.
 *
 * Displays:
 * - KPI card: total Composers
 * - Horizontal bar chart: top 10 Composers by income
 * - Line chart: Composer count trends over time
 * - Bar chart: Composers by associated Works count
 * - Multi-line chart: income per top 5 Composers over time
 * - DateRangeFilter at the top
 *
 * Requirements: 6.1, 6.2, 6.3, 6.4, 6.5, 6.6, 6.7
 */

import { useComposersData } from '@/lib/api/queries';
import { useTranslation } from '@/lib/hooks/useTranslation';
import { formatNumber } from '@/lib/utils/format';
import { useCurrencyAxisFormatter } from '@/lib/hooks/useCurrencyFormatter';
import { chartColors, chartColorArray } from '@/lib/constants/theme';
import DateRangeFilter from '@/components/dashboard/DateRangeFilter';
import KpiGrid from '@/components/dashboard/KpiGrid';
import KpiCard from '@/components/dashboard/KpiCard';
import ChartGrid from '@/components/dashboard/ChartGrid';
import ChartCard from '@/components/charts/ChartCard';
import LineChartWidget from '@/components/charts/LineChartWidget';
import BarChartWidget from '@/components/charts/BarChartWidget';

/**
 * Transform the incomePerTop5OverTime data from per-composer arrays into a
 * flat array suitable for a multi-line Recharts chart.
 *
 * Input shape:
 *   [{ name: "Composer A", data: [{ month: "2024-01", value: 100 }, ...] }, ...]
 *
 * Output shape:
 *   [{ month: "2024-01", "Composer A": 100, "Composer B": 200, ... }, ...]
 */
function transformMultiLineData(
  series: Array<{ name: string; data: Array<{ month: string; value: number }> }>,
): Array<Record<string, unknown>> {
  const monthMap = new Map<string, Record<string, unknown>>();

  for (const composer of series) {
    for (const point of composer.data) {
      if (!monthMap.has(point.month)) {
        monthMap.set(point.month, { month: point.month });
      }
      const row = monthMap.get(point.month)!;
      row[composer.name] = point.value;
    }
  }

  return Array.from(monthMap.values()).sort((a, b) =>
    (a.month as string).localeCompare(b.month as string),
  );
}

export default function ComposersPage() {
  const { data, isLoading } = useComposersData();
  const t = useTranslation();
  const fmtAxis = useCurrencyAxisFormatter();

  if (isLoading || !data) {
    return (
      <div className="flex items-center justify-center h-64">
        <p className="text-divisi-text-secondary text-sm">{t.dashboard.loading}</p>
      </div>
    );
  }

  const { kpis, topByIncome, countTrends, byWorksCount, incomePerTop5OverTime } = data;

  // Transform multi-line data for the LineChartWidget
  const multiLineData = transformMultiLineData(incomePerTop5OverTime);
  const multiLineConfigs = incomePerTop5OverTime.map((composer, index) => ({
    dataKey: composer.name,
    color: chartColorArray[index % chartColorArray.length],
    name: composer.name,
  }));

  return (
    <div className="space-y-6">
      {/* Date Range Filter */}
      <DateRangeFilter />

      {/* KPI Cards */}
      <KpiGrid>
        <KpiCard title={t.dashboard.totalComposers} value={formatNumber(kpis.totalComposers)} />
      </KpiGrid>

      {/* Charts */}
      <ChartGrid>
        {/* Horizontal bar chart: top 10 Composers by income */}
        <ChartCard title={t.dashboard.top10ComposersByIncome}>
          <BarChartWidget
            data={topByIncome}
            xKey="name"
            bars={[{ dataKey: 'value', color: chartColors.primary, name: t.dashboard.totalIncome }]}
            layout="horizontal"
            yAxisFormatter={fmtAxis}
          />
        </ChartCard>

        {/* Line chart: Composer count trends */}
        <ChartCard title={t.dashboard.composerCountTrends}>
          <LineChartWidget
            data={countTrends}
            xKey="month"
            lines={[{ dataKey: 'value', color: chartColors.primary, name: 'New Composers' }]}
          />
        </ChartCard>

        {/* Bar chart: by associated Works count */}
        <ChartCard title={t.dashboard.composersByWorksCount}>
          <BarChartWidget
            data={byWorksCount}
            xKey="name"
            bars={[{ dataKey: 'value', color: chartColors.primary, name: t.dashboard.totalComposers }]}
          />
        </ChartCard>

        {/* Multi-line chart: income per top 5 Composers over time */}
        <ChartCard title={t.dashboard.incomePerTop5}>
          <LineChartWidget
            data={multiLineData}
            xKey="month"
            lines={multiLineConfigs}
            showLegend
            yAxisFormatter={fmtAxis}
          />
        </ChartCard>
      </ChartGrid>
    </div>
  );
}
