import { ChartConfig, ChartContainer, ChartTooltip, ChartTooltipContent } from '@/components/ui/chart';
import { Bar, BarChart, CartesianGrid, XAxis, YAxis } from 'recharts';
import { formatTnd, type KpiPropertyRow } from './kpi-types';

interface RevenueChartProps {
    rows: KpiPropertyRow[];
    locale: string;
    t: (ns: string, key: string, fallback?: string) => string;
}

/**
 * Horizontal bar chart of the top earning properties — bars are sorted so the
 * "who earns most" answer is the top bar. Property names sit on the Y axis so
 * long names stay readable (vs. a cramped X-axis).
 */
export default function RevenueChart({ rows, locale, t }: RevenueChartProps) {
    const data = [...rows]
        .sort((a, b) => b.revenue - a.revenue)
        .slice(0, 8)
        .map((r) => ({
            name: (r.name ?? '—').length > 22 ? (r.name ?? '—').slice(0, 22) + '…' : (r.name ?? '—'),
            revenue: Math.round(r.revenue),
        }));

    const chartConfig = {
        revenue: {
            label: t('properties.kpi', 'revenue'),
            color: 'var(--chart-1)',
        },
    } satisfies ChartConfig;

    if (data.length === 0) {
        return <div className="text-muted-foreground mt-3 text-sm">{t('properties.kpi', 'no_data_period')}</div>;
    }

    return (
        <ChartContainer config={chartConfig} className="mt-3 aspect-auto h-[320px] w-full">
            <BarChart accessibilityLayer data={data} layout="vertical" margin={{ left: 8, right: 16 }}>
                <CartesianGrid horizontal={false} />
                <XAxis type="number" tickLine={false} axisLine={false} tickFormatter={(v) => formatTnd(Number(v), locale)} />
                <YAxis type="category" dataKey="name" width={140} tickLine={false} axisLine={false} tick={{ fontSize: 12 }} />
                <ChartTooltip cursor={false} content={<ChartTooltipContent formatter={(value) => formatTnd(Number(value), locale)} />} />
                <Bar dataKey="revenue" fill="#31B08F" radius={6} />
            </BarChart>
        </ChartContainer>
    );
}
