import { useMemo, useState } from "react";
import {
    AreaChart, Area, XAxis, YAxis, CartesianGrid,
    Tooltip, ResponsiveContainer,
} from "recharts";
import { CHART_COLORS } from "@/Components/Dashboard/chartColors";
import { fmtCurrency, fmtNumber, fmtPercent, fmtDateShort } from "./helpers";

const METRICS = [
    { key: "impressions",      label: "Impressoes",   color: CHART_COLORS.orange, fmt: fmtNumber,   yId: "right" },
    { key: "ctr",              label: "CTR",          color: CHART_COLORS.teal,   fmt: fmtPercent,  yId: "right" },
    { key: "clicks",           label: "Cliques",      color: CHART_COLORS.violet, fmt: fmtNumber,   yId: "right" },
    { key: "conversion_rate",  label: "Tx. Conv.",    color: "#a855f7",           fmt: fmtPercent,  yId: "right" },
    { key: "conversions",      label: "Conversoes",   color: CHART_COLORS.green,  fmt: fmtNumber,   yId: "right" },
    { key: "cpl",              label: "CPL",          color: "#f59e0b",           fmt: fmtCurrency, yId: "left" },
    { key: "cost",             label: "Investimento", color: CHART_COLORS.blue,   fmt: fmtCurrency, yId: "left" },
    { key: "cpc",              label: "CPC Medio",    color: CHART_COLORS.red,    fmt: fmtCurrency, yId: "left" },
];

const DEFAULT_VISIBLE = ["cost", "conversions", "cpl"];

function CustomTooltip({ active, payload, label }) {
    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 DailyChart({ daily }) {
    const [visible, setVisible] = useState(new Set(DEFAULT_VISIBLE));

    const data = useMemo(() => {
        if (!daily?.length) return [];
        return daily.map((d) => ({
            ...d,
            _label: fmtDateShort(d.date),
            conversion_rate: d.clicks > 0 ? (d.conversions / d.clicks) * 100 : 0,
        }));
    }, [daily]);

    if (!data.length) {
        return (
            <p className="text-sm text-muted-foreground py-6 text-center">
                Sem dados diarios para o periodo.
            </p>
        );
    }

    const toggleMetric = (key) => {
        setVisible((prev) => {
            const next = new Set(prev);
            if (next.has(key)) {
                if (next.size > 1) next.delete(key);
            } 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">
            {/* Metric toggles */}
            <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%">
                    <AreaChart data={data} margin={{ top: 5, right: 10, left: 0, bottom: 5 }}>
                        <defs>
                            {activeMetrics.map((m) => (
                                <linearGradient key={m.key} id={`gads-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"
                                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"
                                tick={{ fontSize: 11, fill: "hsl(var(--muted-foreground))" }}
                                tickFormatter={(v) => v >= 1000 ? `${(v / 1000).toFixed(0)}k` : v}
                                width={50}
                            />
                        )}
                        <Tooltip content={<CustomTooltip />} />
                        {activeMetrics.map((m) => (
                            <Area
                                key={m.key}
                                yAxisId={m.yId === "left" && hasLeftAxis ? "left" : hasRightAxis ? "right" : "left"}
                                type="monotone"
                                dataKey={m.key}
                                stroke={m.color}
                                fill={`url(#gads-grad-${m.key})`}
                                strokeWidth={2}
                                dot={false}
                                activeDot={{ r: 4 }}
                            />
                        ))}
                    </AreaChart>
                </ResponsiveContainer>
            </div>
        </div>
    );
}
