/**
 * Right-side chart column used on data pages.
 * Shows the user's configured charts + an "Add chart" button.
 * When `tab` is provided, uses the per-ledger chart arrays instead of the
 * shared dashboard charts.
 */

import { useAppStore } from '@/store/appStore';
import { ChartPanel } from './ChartPanel';

type PageTab = 'work' | 'payments' | 'expenses' | 'tax';

export function ChartSidebar({ tab, defaultRangeStart, defaultRangeEnd }: {
  tab?: PageTab;
  defaultRangeStart?: string;
  defaultRangeEnd?: string;
}) {
  const dashCharts = useAppStore((s) => s.data.dashboard.charts);
  const workCharts = useAppStore((s) => s.data.dashboard.workCharts);
  const paymentsCharts = useAppStore((s) => s.data.dashboard.paymentsCharts);
  const expensesCharts = useAppStore((s) => s.data.dashboard.expensesCharts);
  const taxCharts = useAppStore((s) => s.data.dashboard.taxCharts);
  const addChart = useAppStore((s) => s.addChart);
  const updateChart = useAppStore((s) => s.updateChart);
  const removeChart = useAppStore((s) => s.removeChart);
  const addLedgerChart = useAppStore((s) => s.addLedgerChart);
  const updateLedgerChart = useAppStore((s) => s.updateLedgerChart);
  const removeLedgerChart = useAppStore((s) => s.removeLedgerChart);

  if (tab) {
    const charts = tab === 'work' ? workCharts : tab === 'payments' ? paymentsCharts : tab === 'expenses' ? expensesCharts : taxCharts;
    return (
      <>
        {(charts ?? []).map((c) => (
          <ChartPanel
            key={c.id}
            config={c}
            onChange={(patch) => updateLedgerChart(tab, c.id, patch)}
            onRemove={() => removeLedgerChart(tab, c.id)}
            defaultRangeStart={defaultRangeStart}
            defaultRangeEnd={defaultRangeEnd}
          />
        ))}
        <button className="btn" onClick={() => addLedgerChart(tab)}>
          + Add chart
        </button>
      </>
    );
  }

  return (
    <>
      {dashCharts.map((c) => (
        <ChartPanel
          key={c.id}
          config={c}
          onChange={(patch) => updateChart(c.id, patch)}
          onRemove={() => removeChart(c.id)}
        />
      ))}
      <button className="btn" onClick={() => addChart()}>
        + Add chart
      </button>
    </>
  );
}
