'use client';

import React from 'react';
import ClientOnlyRecharts from '@/components/charts/ClientOnlyRecharts';

interface BarChartProps {
    data: Record<string, unknown>[];
    dataKey: string;
    bars: Array<{
        key: string;
        name: string;
        color?: string;
        stackId?: string;
    }>;
    height?: number;
    showGrid?: boolean;
    showLegend?: boolean;
    showTooltip?: boolean;
    /** Direção das barras: `horizontal` = crescem para a direita; `vertical` = crescem para cima. */
    layout?: 'horizontal' | 'vertical';
    tooltipFormatter?: (
        value: number | string,
        name: string | number,
        item?: { payload?: Record<string, unknown> }
    ) => [React.ReactNode, React.ReactNode];
    /** Uma série: usa o campo `fill` de cada linha em `data`. */
    useDataFillPerCell?: boolean;
    tooltipLabelKey?: string;
    horizontalChart?: {
        categoryAxisWidth?: number;
        tickFontSize?: number;
        barSize?: number;
        xDomain?: [number, number];
    };
    verticalChart?: {
        yDomain?: [number, number];
        barSize?: number;
        tickFontSize?: number;
    };
    onBarClick?: (payload: Record<string, unknown>, barKey: string) => void;
}

export default function BarChart({
    data,
    dataKey,
    bars,
    height = 300,
    showGrid = true,
    showLegend = true,
    showTooltip = true,
    layout = 'vertical',
    tooltipFormatter,
    useDataFillPerCell = false,
    tooltipLabelKey,
    horizontalChart,
    verticalChart,
    onBarClick,
}: BarChartProps) {
    /** Recharts inverte o nome: layout `vertical` = barras horizontais. */
    const isHorizontalBars = layout === 'horizontal';
    const rechartsLayout = isHorizontalBars ? 'vertical' : 'horizontal';

    const hOpts = horizontalChart ?? {};
    const vOpts = verticalChart ?? {};
    const tickFontSize =
        hOpts.tickFontSize ?? vOpts.tickFontSize ?? (isHorizontalBars ? 11 : 12);
    const categoryWidth = hOpts.categoryAxisWidth ?? 140;
    const barSize = hOpts.barSize ?? (isHorizontalBars ? 18 : undefined);
    const chartMargin = isHorizontalBars
        ? { top: 12, right: 20, bottom: 12, left: 8 }
        : { top: 8, right: 12, bottom: 8, left: 4 };

    return (
        <ClientOnlyRecharts minHeight={height}>
            {({
                ResponsiveContainer,
                BarChart: RechartsBarChart,
                Bar,
                XAxis,
                YAxis,
                CartesianGrid,
                Tooltip,
                Legend,
            }) => (
                <ResponsiveContainer width="100%" height={height}>
                    <RechartsBarChart data={data} layout={rechartsLayout} margin={chartMargin}>
                        {showGrid && <CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0" />}
                        {isHorizontalBars ? (
                            <>
                                <XAxis
                                    type="number"
                                    domain={hOpts.xDomain ?? [0, 'auto']}
                                    tick={{ fontSize: tickFontSize, fill: '#64748b' }}
                                    tickLine={false}
                                    axisLine={{ stroke: '#e2e8f0' }}
                                />
                                <YAxis
                                    dataKey={dataKey}
                                    type="category"
                                    width={categoryWidth}
                                    tick={{ fontSize: tickFontSize, fill: '#475569' }}
                                    interval={0}
                                    tickLine={false}
                                    axisLine={false}
                                />
                            </>
                        ) : (
                            <>
                                <XAxis
                                    dataKey={dataKey}
                                    tick={{ fontSize: tickFontSize, fill: '#475569' }}
                                    tickLine={false}
                                    axisLine={{ stroke: '#e2e8f0' }}
                                    interval={0}
                                />
                                <YAxis
                                    domain={vOpts.yDomain ?? [0, 'auto']}
                                    tick={{ fontSize: tickFontSize, fill: '#64748b' }}
                                    tickLine={false}
                                    axisLine={{ stroke: '#e2e8f0' }}
                                />
                            </>
                        )}
                        {showTooltip && (
                            <Tooltip
                                formatter={(value: unknown, name: unknown, item: unknown) =>
                                    tooltipFormatter
                                        ? tooltipFormatter(
                                              value as number | string,
                                              name as string | number,
                                              item as { payload?: Record<string, unknown> }
                                          )
                                        : [value as React.ReactNode, name as React.ReactNode]
                                }
                                labelFormatter={(label: unknown, payload: unknown) => {
                                    const rows = payload as
                                        | Array<{ payload?: Record<string, unknown> }>
                                        | undefined;
                                    if (tooltipLabelKey && rows?.[0]?.payload) {
                                        const full = rows[0].payload[tooltipLabelKey];
                                        if (full != null && String(full).trim() !== '') {
                                            return String(full);
                                        }
                                    }
                                    return String(label ?? '');
                                }}
                            />
                        )}
                        {showLegend && <Legend wrapperStyle={{ fontSize: tickFontSize }} />}
                        {bars.map((bar) => (
                            <Bar
                                key={bar.key}
                                dataKey={bar.key}
                                name={bar.name}
                                fill={
                                    useDataFillPerCell && bars.length === 1
                                        ? undefined
                                        : bar.color || '#27132e'
                                }
                                stackId={bar.stackId}
                                radius={isHorizontalBars ? [0, 4, 4, 0] : [4, 4, 0, 0]}
                                barSize={isHorizontalBars ? barSize : vOpts.barSize ?? barSize ?? 48}
                                minPointSize={2}
                                isAnimationActive={false}
                                cursor={onBarClick ? 'pointer' : undefined}
                                onClick={
                                    onBarClick
                                        ? (barData: unknown) => {
                                              const typed = barData as
                                                  | {
                                                        payload?: Record<string, unknown>;
                                                        dataKey?: string | number;
                                                    }
                                                  | undefined;
                                              const payload = typed?.payload;
                                              const barKey = String(typed?.dataKey ?? '');
                                              if (payload) onBarClick(payload, barKey);
                                          }
                                        : undefined
                                }
                            />
                        ))}
                    </RechartsBarChart>
                </ResponsiveContainer>
            )}
        </ClientOnlyRecharts>
    );
}
