'use client';

import { Bar, BarChart, CartesianGrid, ResponsiveContainer, Tooltip, XAxis, YAxis } from 'recharts';

import { CardSkeleton } from '@/components/shared/loading-skeleton';
import { EmptyState } from '@/components/shared/empty-state';
import { ChartCard } from './chart-card';
import { useRevenue } from './use-analytics';
import type { DateRange } from '@/lib/services/analytics.service';

interface Props {
  range: DateRange;
}

const STATUS_LABELS: Record<string, string> = {
  draft: 'Draft',
  sent: 'Sent',
  paid: 'Paid',
  overdue: 'Overdue',
  cancelled: 'Cancelled',
};

export function RevenueBreakdownChart({ range }: Props) {
  const { data, isLoading } = useRevenue(range);
  const bars = data?.bars ?? [];

  function toCsv(): string | null {
    if (!bars.length) return null;
    const header = 'status,currency,amount';
    const rows = bars.map((b) => `${b.status},${b.currency},${b.amount}`);
    return [header, ...rows].join('\n');
  }

  const chartData = bars.map((b) => ({
    label: `${STATUS_LABELS[b.status] ?? b.status} (${b.currency})`,
    amount: b.amount,
    currency: b.currency,
  }));

  return (
    <ChartCard
      title="Revenue Breakdown"
      description="Invoice totals grouped by status and currency"
      exportFilename={`revenue-breakdown-${range}`}
      toCsv={toCsv}
    >
      {isLoading ? (
        <CardSkeleton />
      ) : !bars.length ? (
        <EmptyState title="No invoices in range" description="Invoices appear here once issued." />
      ) : (
        <ResponsiveContainer width="100%" height={260}>
          <BarChart data={chartData} margin={{ top: 4, right: 8, left: -8, bottom: 40 }}>
            <CartesianGrid strokeDasharray="3 3" className="stroke-border" />
            <XAxis
              dataKey="label"
              tick={{ fontSize: 11, fill: 'hsl(var(--muted-foreground))' }}
              angle={-30}
              textAnchor="end"
              interval={0}
            />
            <YAxis tick={{ fontSize: 11, fill: 'hsl(var(--muted-foreground))' }} />
            <Tooltip
              contentStyle={{
                background: 'hsl(var(--popover))',
                border: '1px solid hsl(var(--border))',
                borderRadius: '6px',
                fontSize: 12,
              }}
              formatter={(value, _name, item) => {
                const c = (item?.payload as { currency?: string } | undefined)?.currency ?? '';
                const num = typeof value === 'number' ? value : Number(value);
                return [`${num.toLocaleString()} ${c}`, 'Amount'];
              }}
            />
            <Bar dataKey="amount" fill="hsl(var(--chart-3))" radius={[4, 4, 0, 0]} />
          </BarChart>
        </ResponsiveContainer>
      )}
    </ChartCard>
  );
}
