'use client';

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

type XAxisInterval =
    | number
    | 'preserveStart'
    | 'preserveEnd'
    | 'preserveStartEnd'
    | 'equidistantPreserveStart';

interface LineChartProps {
    data: Record<string, unknown>[];
    dataKey: string;
    lines: Array<{
        key: string;
        name: string;
        color?: string;
        strokeWidth?: number;
    }>;
    height?: number;
    showGrid?: boolean;
    showLegend?: boolean;
    showTooltip?: boolean;
    tooltipFormatter?: (
        value: number | string,
        name: string | number
    ) => [React.ReactNode, React.ReactNode];
    yAxisTickFormatter?: (value: number) => string;
    /** Tamanho dos ticks (eixos). Default: 12. */
    tickFontSize?: number;
    /** Ângulo dos labels do eixo X (ex.: -35 em impressão estreita). */
    xTickAngle?: number;
    /**
     * Intervalo dos ticks do eixo X.
     * Default `preserveStartEnd` — evita sobreposição com séries densas (ex.: 24 horas).
     * Use `0` só quando houver poucos pontos e todos os labels forem necessários.
     */
    xAxisInterval?: XAxisInterval;
    /** Margem interna do gráfico Recharts. */
    chartMargin?: { top?: number; right?: number; bottom?: number; left?: number };
    /** Domínio mínimo do eixo Y (útil quando a série é toda zero / valores baixos). */
    yAxisDomain?: [number | 'auto' | 'dataMin', number | 'auto' | 'dataMax'];
}

export default function LineChart({
    data,
    dataKey,
    lines,
    height = 300,
    showGrid = true,
    showLegend = true,
    showTooltip = true,
    tooltipFormatter,
    yAxisTickFormatter,
    tickFontSize = 12,
    xTickAngle = 0,
    xAxisInterval = 'preserveStartEnd',
    chartMargin,
    yAxisDomain,
}: LineChartProps) {
    const margin = {
        top: chartMargin?.top ?? 12,
        right: chartMargin?.right ?? 16,
        bottom: chartMargin?.bottom ?? (xTickAngle ? 28 : 12),
        left: chartMargin?.left ?? 8,
    };

    return (
        <ClientOnlyRecharts minHeight={height}>
            {({
                ResponsiveContainer,
                LineChart: RechartsLineChart,
                Line,
                XAxis,
                YAxis,
                CartesianGrid,
                Tooltip,
                Legend,
            }) => (
                <ResponsiveContainer width="100%" height={height}>
                    <RechartsLineChart data={data} margin={margin}>
                        {showGrid && <CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0" />}
                        <XAxis
                            dataKey={dataKey}
                            interval={xAxisInterval}
                            minTickGap={28}
                            tick={{ fontSize: tickFontSize, fill: '#475569' }}
                            tickLine={false}
                            axisLine={{ stroke: '#e2e8f0' }}
                            angle={xTickAngle}
                            textAnchor={xTickAngle ? 'end' : 'middle'}
                            height={xTickAngle ? 42 : undefined}
                        />
                        <YAxis
                            domain={yAxisDomain}
                            allowDecimals={false}
                            tickFormatter={yAxisTickFormatter}
                            tick={{ fontSize: tickFontSize, fill: '#64748b' }}
                            tickLine={false}
                            axisLine={{ stroke: '#e2e8f0' }}
                            width={40}
                        />
                        {showTooltip && <Tooltip formatter={tooltipFormatter} />}
                        {showLegend && <Legend wrapperStyle={{ fontSize: tickFontSize }} />}
                        {lines.map((line) => (
                            <Line
                                key={line.key}
                                type="monotone"
                                dataKey={line.key}
                                name={line.name}
                                stroke={line.color || '#27132e'}
                                strokeWidth={line.strokeWidth || 2}
                                isAnimationActive={false}
                                dot={{ r: 3, strokeWidth: 1 }}
                            />
                        ))}
                    </RechartsLineChart>
                </ResponsiveContainer>
            )}
        </ClientOnlyRecharts>
    );
}
