import { useMemo, useState } from "react";
import {
    ComposedChart, Area, Line, XAxis, YAxis, CartesianGrid,
    Tooltip, ResponsiveContainer,
} from "recharts";
import { fmtDateShort } from "@/Components/Dashboard/MetaAdsDrilldown/helpers";

/**
 * Gráfico de evolução temporal com filtro/toggle de métricas, no mesmo padrão
 * dos gráficos de drill-down (MetaAdsDrilldown/DailyChart). Reutilizável: cada
 * métrica é configurada via prop `metrics` ({ key, label, color, fmt, yId }).
 *
 * - daily: array de pontos diários (precisa conter `date` + as keys das métricas)
 * - metrics: catálogo de métricas selecionáveis
 * - defaultVisible: keys ligadas inicialmente
 * - logScale: eixos Y logarítmicos + linhas (em vez de área). Útil quando as
 *   métricas têm magnitudes muito diferentes (ex.: cliques vs CTR/posição), que
 *   numa escala linear ficariam coladas na base. Em log, valores <= 0 viram null
 *   (log não admite zero) e a linha apenas pula o ponto.
 */
function TimelineTooltip({ active, payload, label, metrics }) {
    if (!active || !payload?.length) return null;
    return (
        <div className="rounded-lg border bg-popover px-3 py-2 text-sm shadow-md">
            <p className="font-medium mb-1">{fmtDateShort(label)}</p>
            {payload.map((p) => {
                const m = metrics.find((m) => m.key === p.dataKey);
                return (
                    <div key={p.dataKey} className="flex items-center gap-2">
                        <span className="h-2 w-2 rounded-full shrink-0" style={{ background: p.color }} />
                        <span className="text-muted-foreground">{m?.label ?? p.dataKey}:</span>
                        <span className="font-medium">{m ? m.fmt(p.value) : p.value}</span>
                    </div>
                );
            })}
        </div>
    );
}

export default function IntegrationTimelineChart({ daily, metrics, defaultVisible, logScale = false }) {
    const [visible, setVisible] = useState(() => new Set(defaultVisible));

    const data = useMemo(() => {
        const rows = daily?.length ? daily : [];
        if (!logScale) return rows;
        // Log não admite 0/negativo: zera-os para null (a linha pula o ponto).
        return rows.map((row) => {
            const next = { ...row };
            for (const m of metrics) {
                if (next[m.key] != null && Number(next[m.key]) <= 0) next[m.key] = null;
            }
            return next;
        });
    }, [daily, logScale, metrics]);

    if (!data.length) {
        return (
            <p className="text-sm text-muted-foreground py-6 text-center">
                Sem dados diários para o período.
            </p>
        );
    }

    const toggleMetric = (key) => {
        setVisible((prev) => {
            const next = new Set(prev);
            if (next.has(key)) {
                if (next.size > 1) next.delete(key); // mantém ao menos 1 linha
            } else {
                next.add(key);
            }
            return next;
        });
    };

    const activeMetrics = metrics.filter((m) => visible.has(m.key));
    const hasLeftAxis = activeMetrics.some((m) => m.yId === "left");
    const hasRightAxis = activeMetrics.some((m) => m.yId === "right");

    return (
        <div className="space-y-3">
            {/* Toggles de métricas (filtro de linhas) */}
            <div className="flex flex-wrap gap-1.5">
                {metrics.map((m) => (
                    <button
                        key={m.key}
                        onClick={() => toggleMetric(m.key)}
                        className={`inline-flex items-center gap-1.5 rounded-full px-2.5 py-1 text-xs font-medium transition-colors border ${
                            visible.has(m.key)
                                ? "border-transparent text-white"
                                : "border-border text-muted-foreground bg-transparent hover:bg-muted"
                        }`}
                        style={visible.has(m.key) ? { backgroundColor: m.color } : undefined}
                    >
                        {m.label}
                    </button>
                ))}
            </div>

            <div className="h-[280px] w-full">
                <ResponsiveContainer width="100%" height="100%">
                    <ComposedChart data={data} margin={{ top: 5, right: 10, left: 0, bottom: 5 }}>
                        <defs>
                            {activeMetrics.map((m) => (
                                <linearGradient key={m.key} id={`tl-grad-${m.key}`} x1="0" y1="0" x2="0" y2="1">
                                    <stop offset="5%" stopColor={m.color} stopOpacity={0.3} />
                                    <stop offset="95%" stopColor={m.color} stopOpacity={0.05} />
                                </linearGradient>
                            ))}
                        </defs>
                        <CartesianGrid strokeDasharray="3 3" stroke="hsl(var(--border))" />
                        <XAxis
                            dataKey="date"
                            tickFormatter={fmtDateShort}
                            tick={{ fontSize: 11, fill: "hsl(var(--muted-foreground))" }}
                        />
                        {hasLeftAxis && (
                            <YAxis
                                yAxisId="left"
                                scale={logScale ? "log" : "auto"}
                                domain={logScale ? [0.1, "auto"] : undefined}
                                allowDataOverflow={logScale}
                                tick={{ fontSize: 11, fill: "hsl(var(--muted-foreground))" }}
                                tickFormatter={(v) => v >= 1000 ? `${(v / 1000).toFixed(0)}k` : v}
                                width={50}
                            />
                        )}
                        {hasRightAxis && (
                            <YAxis
                                yAxisId="right"
                                orientation="right"
                                scale={logScale ? "log" : "auto"}
                                domain={logScale ? [0.1, "auto"] : undefined}
                                allowDataOverflow={logScale}
                                tick={{ fontSize: 11, fill: "hsl(var(--muted-foreground))" }}
                                tickFormatter={(v) => v >= 1000 ? `${(v / 1000).toFixed(0)}k` : v}
                                width={50}
                            />
                        )}
                        <Tooltip content={<TimelineTooltip metrics={metrics} />} />
                        {activeMetrics.map((m) => {
                            const yAxisId = m.yId === "left" && hasLeftAxis ? "left" : hasRightAxis ? "right" : "left";
                            return logScale ? (
                                <Line
                                    key={m.key}
                                    yAxisId={yAxisId}
                                    type="monotone"
                                    dataKey={m.key}
                                    name={m.label}
                                    stroke={m.color}
                                    strokeWidth={2}
                                    dot={false}
                                    activeDot={{ r: 4 }}
                                    connectNulls
                                />
                            ) : (
                                <Area
                                    key={m.key}
                                    yAxisId={yAxisId}
                                    type="monotone"
                                    dataKey={m.key}
                                    name={m.label}
                                    stroke={m.color}
                                    fill={`url(#tl-grad-${m.key})`}
                                    strokeWidth={2}
                                    dot={false}
                                    activeDot={{ r: 4 }}
                                    connectNulls
                                />
                            );
                        })}
                    </ComposedChart>
                </ResponsiveContainer>
            </div>
        </div>
    );
}
