import { useMemo } from "react";
import { format } from "date-fns";
import { ptBR } from "date-fns/locale";
import {
    AreaChart, Area,
    BarChart, Bar, Cell,
    PieChart, Pie,
    XAxis, YAxis, CartesianGrid, Tooltip,
    ResponsiveContainer, Legend,
} from "recharts";

import { useDashboardFilters } from "@/context/DashboardFiltersContext";
import { providerColor } from "@/Components/Dashboard/chartColors";
import KpiCard from "@/Components/Dashboard/KpiCard";
import ChartCard from "@/Components/Dashboard/ChartCard";
import DashboardSkeleton from "@/Components/Dashboard/DashboardSkeleton";
import TemplateRenderer from "@/Components/Dashboard/TemplateRenderer";
import { IconGoogleAds, IconMetaAds } from "@/Components/Dashboard/integrationIcons";
import { fmtCurrency, fmtDateShort } from "@/Components/Dashboard/MetaAdsDrilldown/helpers";
import {
    getSourceKeys,
    buildSpendByIntegrationDaily,
    getSpendChannels,
    buildSpendTotals,
    buildCampaignGanttData,
    buildObjectiveDistribution,
} from "./resumoDataHelpers";

/* ── Shared chart styling ─────────────────────────────────── */

const tooltipStyle = {
    backgroundColor: "hsl(var(--card))",
    borderColor: "hsl(var(--border))",
    borderRadius: "6px",
    fontSize: 12,
};
const axisStyle = { fontSize: 11, fill: "hsl(var(--muted-foreground))" };
const tickDate = (v) => format(new Date(v + "T12:00:00"), "dd/MM", { locale: ptBR });

function smartCurrencyTick(v) {
    if (v >= 1000) return `R$${(v / 1000).toFixed(0)}k`;
    return `R$${v}`;
}

/* ── Custom Tooltips ──────────────────────────────────────── */

function LeadsTooltip({ active, payload, label }) {
    if (!active || !payload?.length) return null;
    const total = payload.reduce((s, p) => s + (p.value ?? 0), 0);
    return (
        <div className="rounded-md border bg-card px-3 py-2 text-xs shadow-md">
            <p className="font-medium mb-1">{format(new Date(label + "T12:00:00"), "dd/MM/yyyy", { locale: ptBR })}</p>
            {payload.map((p) => (
                <p key={p.dataKey} style={{ color: p.color }}>
                    {p.name}: <span className="font-semibold">{p.value?.toLocaleString("pt-BR")}</span>
                </p>
            ))}
            <p className="mt-1 border-t pt-1 font-medium">
                Total: {total.toLocaleString("pt-BR")}
            </p>
        </div>
    );
}

function SpendStackTooltip({ active, payload, label }) {
    if (!active || !payload?.length) return null;
    const total = payload.reduce((s, p) => s + (p.value ?? 0), 0);
    return (
        <div className="rounded-md border bg-card px-3 py-2 text-xs shadow-md">
            <p className="font-medium mb-1">{format(new Date(label + "T12:00:00"), "dd/MM/yyyy", { locale: ptBR })}</p>
            {payload.map((p) => (
                <p key={p.dataKey} style={{ color: p.color }}>
                    {p.name}: <span className="font-semibold">{fmtCurrency(p.value)}</span>
                </p>
            ))}
            <p className="mt-1 border-t pt-1 font-medium">Total: {fmtCurrency(total)}</p>
        </div>
    );
}

function SpendPieTooltip({ active, payload }) {
    if (!active || !payload?.length) return null;
    const d = payload[0];
    return (
        <div className="rounded-md border bg-card px-3 py-2 text-xs shadow-md">
            <p style={{ color: d.payload.fill }}>{d.name}</p>
            <p className="font-semibold">{fmtCurrency(d.value)} ({d.payload.pct}%)</p>
        </div>
    );
}

function GanttTooltip({ active, payload }) {
    if (!active || !payload?.length) return null;
    const row = payload[0]?.payload;
    if (!row) return null;
    return (
        <div className="rounded-md border bg-card px-3 py-2 text-xs shadow-md max-w-xs">
            <p className="font-medium mb-1 truncate">{row.name}</p>
            <p className="text-muted-foreground">{row.providerLabel}</p>
            <p>Ativo de {fmtDateShort(row.firstDate)} a {fmtDateShort(row.lastDate)}</p>
            <p>Investimento: <span className="font-semibold">{fmtCurrency(row.totalSpend)}</span></p>
        </div>
    );
}

function renderPieLabel({ cx, cy, midAngle, innerRadius, outerRadius, pct }) {
    if (pct < 5) return null;
    const RADIAN = Math.PI / 180;
    const radius = innerRadius + (outerRadius - innerRadius) * 0.5;
    const x = cx + radius * Math.cos(-midAngle * RADIAN);
    const y = cy + radius * Math.sin(-midAngle * RADIAN);
    return (
        <text x={x} y={y} fill="#fff" textAnchor="middle" dominantBaseline="central" fontSize={12} fontWeight={600}>
            {pct}%
        </text>
    );
}

function DonutWithCenter({ children, total }) {
    return (
        <div className="relative w-full h-full">
            {children}
            <div className="absolute inset-0 flex items-center justify-center pointer-events-none" style={{ paddingBottom: 30 }}>
                <div className="text-center">
                    <p className="text-sm font-bold">{fmtCurrency(total)}</p>
                    <p className="text-[10px] text-muted-foreground">Total</p>
                </div>
            </div>
        </div>
    );
}

/* ── Bloco: resumo_kpis_conversoes ────────────────────────── */

function BlockKpisConversoes({ trendMode, hasAds, hasGoogleAds, hasMetaAds, resumoKpis, trends }) {
    if (!hasAds) return null;
    const totalProviders = [hasGoogleAds && "google_ads", hasMetaAds && "meta_ads"].filter(Boolean);
    return (
        <div className="grid grid-cols-2 gap-3 lg:grid-cols-3">
            <KpiCard
                label="Conversões Total"
                value={resumoKpis.conversoes ?? 0}
                format="number"
                trend={trends.conversoes}
                className="bg-muted/40 border-2"
                trendMode={trendMode}
                providers={totalProviders}
            />
            {hasGoogleAds && (
                <KpiCard label="Conversões" value={resumoKpis.conversoes_google_ads ?? 0} format="number" trend={trends.conversoes_google_ads} providers={["google_ads"]} trendMode={trendMode} />
            )}
            {hasMetaAds && (
                <KpiCard label="Conversões" value={resumoKpis.conversoes_meta_ads ?? 0} format="number" trend={trends.conversoes_meta_ads} providers={["meta_ads"]} trendMode={trendMode} />
            )}
        </div>
    );
}

/* ── Bloco: resumo_kpis_investimento ──────────────────────── */

function BlockKpisInvestimento({ trendMode, hasAds, hasGoogleAds, hasMetaAds, resumoKpis, trends }) {
    const custoCards = [hasAds, hasGoogleAds, hasMetaAds].filter(Boolean).length;
    if (custoCards === 0) return null;
    const totalProviders = [hasGoogleAds && "google_ads", hasMetaAds && "meta_ads"].filter(Boolean);
    return (
        <div className="grid grid-cols-2 gap-3 lg:grid-cols-3">
            {hasAds && (
                <KpiCard
                    label="Investimento Total"
                    value={resumoKpis.investimento ?? 0}
                    format="currency"
                    trend={trends.investimento}
                    className="bg-muted/40 border-2"
                    trendMode={trendMode}
                    providers={totalProviders}
                />
            )}
            {hasGoogleAds && (
                <KpiCard label="Investimento" value={resumoKpis.custo_google_ads ?? 0} format="currency" trend={trends.custo_google_ads} providers={["google_ads"]} trendMode={trendMode} />
            )}
            {hasMetaAds && (
                <KpiCard label="Investimento" value={resumoKpis.custo_meta_ads ?? 0} format="currency" trend={trends.custo_meta_ads} providers={["meta_ads"]} trendMode={trendMode} />
            )}
        </div>
    );
}

/* ── Bloco: resumo_leads_por_dia ──────────────────────────── */

function BlockLeadsPorDia({ readiness, leadsBySource, sourceKeys }) {
    if (!readiness.hasLeadTimelineBySource || sourceKeys.length === 0 || leadsBySource.length === 0) return null;
    return (
        <ChartCard
            title="Leads por dia"
            description="Quantidade diária de leads por origem configurada"
            providers={["exent_hub"]}
        >
            <ResponsiveContainer width="100%" height="100%">
                <AreaChart data={leadsBySource} margin={{ top: 5, right: 10, left: 0, bottom: 5 }}>
                    <defs>
                        {sourceKeys.map((src, i) => (
                            <linearGradient key={src.key} id={`leadsFill-${i}`} x1="0" y1="0" x2="0" y2="1">
                                <stop offset="0%" stopColor={src.color} stopOpacity={0.35} />
                                <stop offset="95%" stopColor={src.color} stopOpacity={0.03} />
                            </linearGradient>
                        ))}
                    </defs>
                    <CartesianGrid strokeDasharray="3 3" stroke="hsl(var(--border))" />
                    <XAxis dataKey="date" tick={axisStyle} tickFormatter={tickDate} />
                    <YAxis tick={axisStyle} allowDecimals={false} />
                    <Tooltip content={<LeadsTooltip />} />
                    <Legend wrapperStyle={{ fontSize: 12 }} />
                    {sourceKeys.map((src, i) => (
                        <Area
                            key={src.key}
                            type="monotone"
                            dataKey={src.key}
                            name={src.label}
                            stroke={src.color}
                            strokeWidth={2}
                            fill={`url(#leadsFill-${i})`}
                            stackId="leads"
                            dot={false}
                        />
                    ))}
                </AreaChart>
            </ResponsiveContainer>
        </ChartCard>
    );
}

/* ── Bloco: resumo_investimento_diario ────────────────────── */

function BlockInvestimentoDiario({ readiness, spendDaily, spendChannels, hasGoogleAds, hasMetaAds }) {
    if (!readiness.hasSpendDailyByIntegration || spendDaily.length === 0) return null;
    const providers = [hasGoogleAds && "google_ads", hasMetaAds && "meta_ads"].filter(Boolean);
    return (
        <ChartCard title="Investimento diário por integração" providers={providers}>
            <ResponsiveContainer width="100%" height="100%">
                <BarChart data={spendDaily} margin={{ top: 5, right: 10, left: 0, bottom: 5 }}>
                    <CartesianGrid strokeDasharray="3 3" stroke="hsl(var(--border))" />
                    <XAxis dataKey="date" tick={axisStyle} tickFormatter={tickDate} />
                    <YAxis tick={axisStyle} tickFormatter={smartCurrencyTick} />
                    <Tooltip content={<SpendStackTooltip />} />
                    <Legend wrapperStyle={{ fontSize: 12 }} />
                    {spendChannels.map((ch, idx) => (
                        <Bar
                            key={ch.key}
                            dataKey={ch.key}
                            name={ch.label}
                            stackId="spend"
                            fill={ch.color}
                            radius={idx === spendChannels.length - 1 ? [3, 3, 0, 0] : [0, 0, 0, 0]}
                        />
                    ))}
                </BarChart>
            </ResponsiveContainer>
        </ChartCard>
    );
}

/* ── Bloco: resumo_investimento_acumulado ─────────────────── */

function BlockInvestimentoAcumulado({ readiness, spendPieData, spendTotal, hasGoogleAds, hasMetaAds }) {
    if (!readiness.hasSpendDailyByIntegration || spendPieData.length === 0) return null;
    const providers = [hasGoogleAds && "google_ads", hasMetaAds && "meta_ads"].filter(Boolean);
    return (
        <ChartCard title="Investimento acumulado por integração" providers={providers}>
            <DonutWithCenter total={spendTotal}>
                <ResponsiveContainer width="100%" height="100%">
                    <PieChart>
                        <Pie
                            data={spendPieData}
                            dataKey="value"
                            cx="50%"
                            cy="50%"
                            innerRadius={55}
                            outerRadius={90}
                            strokeWidth={2}
                            stroke="hsl(var(--card))"
                            label={renderPieLabel}
                            labelLine={false}
                        >
                            {spendPieData.map((entry) => (
                                <Cell key={entry.name} fill={entry.fill} />
                            ))}
                        </Pie>
                        <Tooltip content={<SpendPieTooltip />} />
                        <Legend
                            wrapperStyle={{ fontSize: 12 }}
                            formatter={(value, entry) => (
                                <span style={{ color: entry.color }}>{value}</span>
                            )}
                        />
                    </PieChart>
                </ResponsiveContainer>
            </DonutWithCenter>
        </ChartCard>
    );
}

/* ── Bloco: resumo_campanhas_timeline ─────────────────────── */

function BlockCampanhasTimeline({ readiness, gantt, startDate, hasGoogleAds, hasMetaAds }) {
    if (!readiness.hasCampaignActivityTimeline || gantt.data.length === 0) return null;
    const ganttInnerH = Math.max(gantt.data.length * 32 + 40, 200);
    const providers = [hasGoogleAds && "google_ads", hasMetaAds && "meta_ads"].filter(Boolean);
    return (
        <ChartCard title="Campanhas ativas no período" height="h-auto" providers={providers}>
            <div className="overflow-y-auto overflow-x-hidden" style={{ maxHeight: 440 }}>
                <ResponsiveContainer width="100%" height={ganttInnerH}>
                    <BarChart
                        data={gantt.data}
                        layout="vertical"
                        margin={{ top: 5, right: 20, left: 0, bottom: 5 }}
                        barSize={14}
                    >
                        <XAxis
                            type="number"
                            domain={[0, gantt.totalDays]}
                            tick={axisStyle}
                            tickFormatter={(day) => {
                                if (!startDate) return day;
                                const d = new Date(startDate + "T00:00:00");
                                d.setDate(d.getDate() + day);
                                return format(d, "dd/MM", { locale: ptBR });
                            }}
                        />
                        <YAxis
                            type="category"
                            dataKey="name"
                            tick={axisStyle}
                            width={160}
                            tickFormatter={(v) => (v.length > 22 ? v.slice(0, 22) + "..." : v)}
                        />
                        <Tooltip content={<GanttTooltip />} />
                        <Bar dataKey="startOffset" stackId="gantt" fill="transparent" isAnimationActive={false} />
                        <Bar dataKey="duration" stackId="gantt" isAnimationActive={false}>
                            {gantt.data.map((entry, i) => (
                                <Cell key={i} fill={providerColor(entry.provider)} />
                            ))}
                        </Bar>
                    </BarChart>
                </ResponsiveContainer>
            </div>
        </ChartCard>
    );
}

/* ── Bloco: resumo_campanhas_objetivos ────────────────────── */

function BlockCampanhasObjetivos({ readiness, objectives, hasGoogleAds, hasMetaAds }) {
    if (!readiness.hasCampaignObjectiveDistribution || objectives.data.length === 0) return null;
    const providers = [hasGoogleAds && "google_ads", hasMetaAds && "meta_ads"].filter(Boolean);
    return (
        <ChartCard title="Distribuição de objetivos de campanha" providers={providers}>
            <ResponsiveContainer width="100%" height="100%">
                <BarChart
                    data={objectives.data}
                    layout="vertical"
                    margin={{ top: 5, right: 20, left: 0, bottom: 5 }}
                >
                    <XAxis type="number" domain={[0, 100]} tick={axisStyle} tickFormatter={(v) => `${v}%`} />
                    <YAxis type="category" dataKey="providerLabel" tick={axisStyle} width={90} />
                    <Tooltip
                        contentStyle={tooltipStyle}
                        formatter={(v, name) => [`${v}%`, name]}
                    />
                    <Legend wrapperStyle={{ fontSize: 12 }} />
                    {objectives.objectives.map((obj) => (
                        <Bar
                            key={obj.key}
                            dataKey={obj.key}
                            name={obj.label}
                            stackId="objectives"
                            fill={obj.color}
                        />
                    ))}
                </BarChart>
            </ResponsiveContainer>
        </ChartCard>
    );
}

/* ── Bloco: resumo_saldos (placeholder gated) ─────────────── */

function BlockSaldos({ readiness }) {
    if (!readiness.hasBalances) return null;
    return null; // sem dados reais hoje
}

/* ── Dispatch map ─────────────────────────────────────────── */

const RESUMO_DISPATCH = {
    resumo_kpis_conversoes:        BlockKpisConversoes,
    resumo_kpis_investimento:      BlockKpisInvestimento,
    resumo_saldos:                 BlockSaldos,
    resumo_leads_por_dia:          BlockLeadsPorDia,
    resumo_investimento_diario:    BlockInvestimentoDiario,
    resumo_investimento_acumulado: BlockInvestimentoAcumulado,
    resumo_campanhas_timeline:     BlockCampanhasTimeline,
    resumo_campanhas_objetivos:    BlockCampanhasObjetivos,
};

/* ── Main component ───────────────────────────────────────── */

export default function ResumoTab({
    hasAds = true,
    hasGoogleAds = false,
    hasMetaAds = false,
    trendMode = "on",
    layout = null,
}) {
    const { data, loading, startDate, endDate } = useDashboardFilters();

    const readiness          = data?.resumoReadiness ?? {};
    const resumoKpis         = data?.resumoKpis ?? {};
    const trends             = data?.trends?.resumoKpis ?? {};
    const ads                = data?.ads ?? [];
    const leadsBySource      = data?.leadsBySource ?? [];
    const campaignTimeline   = data?.campaignTimeline ?? [];
    const campaignObjectives = data?.campaignObjectives ?? [];

    const sourceKeys    = useMemo(() => getSourceKeys(leadsBySource), [leadsBySource]);
    const spendDaily    = useMemo(() => buildSpendByIntegrationDaily(ads), [ads]);
    const spendChannels = useMemo(() => getSpendChannels(ads), [ads]);
    const spendTotals   = useMemo(() => buildSpendTotals(ads), [ads]);

    const gantt = useMemo(
        () => buildCampaignGanttData(campaignTimeline, startDate, endDate),
        [campaignTimeline, startDate, endDate],
    );
    const objectives = useMemo(
        () => buildObjectiveDistribution(campaignObjectives),
        [campaignObjectives],
    );

    const spendPieData = useMemo(() => spendTotals.map((entry) => ({
        name: entry.label,
        value: entry.spend,
        fill: providerColor(entry.channel),
        pct: entry.pct,
    })), [spendTotals]);

    const spendTotal = useMemo(
        () => spendPieData.reduce((s, d) => s + d.value, 0),
        [spendPieData],
    );

    if (loading) return <DashboardSkeleton />;

    const blockProps = {
        hasAds,
        hasGoogleAds,
        hasMetaAds,
        resumoKpis,
        trends,
        readiness,
        leadsBySource,
        sourceKeys,
        spendDaily,
        spendChannels,
        spendPieData,
        spendTotal,
        gantt,
        objectives,
        startDate,
    };

    return (
        <TemplateRenderer
            rows={layout}
            dispatch={RESUMO_DISPATCH}
            blockProps={blockProps}
            trendMode={trendMode}
        />
    );
}
