import { useMemo } from "react";
import {
    AreaChart, Area,
    BarChart, Bar, Cell,
    PieChart, Pie,
    XAxis, YAxis, CartesianGrid, Tooltip,
    ResponsiveContainer, Legend,
} from "recharts";

import { useDashboardFilters } from "@/context/DashboardFiltersContext";
import { CHART_COLORS } from "@/Components/Dashboard/chartColors";
import { PROVIDER_ICON, INTEGRATION_LABELS } from "@/Components/Dashboard/integrationIcons";
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 { layoutHasForeignData } from "@/lib/blockGrid";
import { Card, CardContent } from "@/Components/ui/card";
import {
    axisStyle, tickDate, tooltipDate,
    fmtNumber,
    sourceColor,
    buildSourceDailySeries,
    buildApprovalSeries,
} from "./leadsFunilDataHelpers";

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

function DateTooltip({ active, payload, label }) {
    if (!active || !payload?.length) return null;
    return (
        <div className="rounded-md border bg-card px-3 py-2 text-xs shadow-md">
            <p className="font-medium mb-1">{tooltipDate(label)}</p>
            {payload.map((p) => (
                <p key={p.dataKey} style={{ color: p.color }}>
                    {p.name}: <span className="font-semibold">{fmtNumber(p.value)}</span>
                </p>
            ))}
        </div>
    );
}

function StackedTooltip({ 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">{tooltipDate(label)}</p>
            {payload.map((p) => (
                <p key={p.dataKey} style={{ color: p.color }}>
                    {p.name}: <span className="font-semibold">{fmtNumber(p.value)}</span>
                </p>
            ))}
            <p className="mt-1 border-t pt-1 font-medium">Total: {fmtNumber(total)}</p>
        </div>
    );
}

function PieTooltip({ 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">{fmtNumber(d.value)} leads ({d.payload.pct}%)</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>
    );
}

const PROVIDER_COLORS = {
    google_ads: { bg: "rgba(249, 171, 0, 0.12)", text: "#B8860B" },
    meta_ads:   { bg: "rgba(24, 119, 242, 0.12)", text: "#1877F2" },
};

function ProviderBadge({ provider }) {
    if (!provider) return <span className="text-muted-foreground">-</span>;
    const Icon = PROVIDER_ICON[provider];
    const label = INTEGRATION_LABELS[provider] ?? provider;
    const colors = PROVIDER_COLORS[provider] ?? { bg: "rgba(100,116,139,0.12)", text: "#64748b" };
    return (
        <span className="inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[10px] font-medium" style={{ backgroundColor: colors.bg, color: colors.text }}>
            {Icon && <Icon size={12} />}
            {label}
        </span>
    );
}

const MAX_TABLE_ROWS = 15;

function CampaignTable({ data }) {
    if (!data?.length) return null;
    const total = data.reduce((s, r) => s + r.leads, 0);
    const visible = data.slice(0, MAX_TABLE_ROWS);
    return (
        <div>
            <p className="text-xs font-semibold text-muted-foreground mb-2">Leads por Campanha</p>
            <div className="rounded-md border overflow-auto max-h-[440px]">
                <table className="w-full text-xs">
                    <thead className="sticky top-0 z-10">
                        <tr className="border-b bg-muted/50">
                            <th className="px-2 py-1.5 text-left font-medium">Campanha</th>
                            <th className="px-2 py-1.5 text-left font-medium hidden sm:table-cell">Plataforma</th>
                            <th className="px-2 py-1.5 text-right font-medium">Leads</th>
                            <th className="px-2 py-1.5 text-right font-medium">%</th>
                        </tr>
                    </thead>
                    <tbody>
                        {visible.map((row, i) => {
                            const pct = total > 0 ? ((row.leads / total) * 100).toFixed(1) : "0";
                            return (
                                <tr key={row.key} className="border-b last:border-0">
                                    <td className="px-2 py-1.5 max-w-[220px] truncate">
                                        <span className="text-muted-foreground mr-1.5">{i + 1}</span>
                                        {row.label}
                                    </td>
                                    <td className="px-2 py-1.5 hidden sm:table-cell">
                                        <ProviderBadge provider={row.provider} />
                                    </td>
                                    <td className="px-2 py-1.5 text-right tabular-nums">{fmtNumber(row.leads)}</td>
                                    <td className="px-2 py-1.5 text-right tabular-nums text-muted-foreground">{pct}%</td>
                                </tr>
                            );
                        })}
                    </tbody>
                    <tfoot className="sticky bottom-0 z-10">
                        <tr className="bg-muted/50 font-medium">
                            <td className="px-2 py-1.5">Total ({data.length})</td>
                            <td className="px-2 py-1.5 hidden sm:table-cell" />
                            <td className="px-2 py-1.5 text-right tabular-nums">{fmtNumber(total)}</td>
                            <td className="px-2 py-1.5 text-right tabular-nums text-muted-foreground">100%</td>
                        </tr>
                    </tfoot>
                </table>
            </div>
        </div>
    );
}

function KeywordTable({ data }) {
    if (!data?.length) return null;
    const filtered = data.filter((r) => r.key !== "unidentified");
    if (!filtered.length) return null;
    const total = filtered.reduce((s, r) => s + r.leads, 0);
    const visible = filtered.slice(0, MAX_TABLE_ROWS);
    const Icon = PROVIDER_ICON.google_ads;
    return (
        <div>
            <div className="flex items-center gap-2 mb-2">
                {Icon && <Icon size={16} />}
                <p className="text-xs font-semibold text-muted-foreground">Palavras-chave (Google Ads)</p>
            </div>
            <div className="rounded-md border overflow-auto max-h-[440px]">
                <table className="w-full text-xs">
                    <thead className="sticky top-0 z-10">
                        <tr className="border-b bg-muted/50">
                            <th className="px-2 py-1.5 text-left font-medium">Palavra-chave</th>
                            <th className="px-2 py-1.5 text-right font-medium">Leads</th>
                            <th className="px-2 py-1.5 text-right font-medium">%</th>
                        </tr>
                    </thead>
                    <tbody>
                        {visible.map((row, i) => {
                            const pct = total > 0 ? ((row.leads / total) * 100).toFixed(1) : "0";
                            return (
                                <tr key={row.key} className="border-b last:border-0">
                                    <td className="px-2 py-1.5 max-w-[200px] truncate">
                                        <span className="text-muted-foreground mr-1.5">{i + 1}</span>
                                        {row.label}
                                    </td>
                                    <td className="px-2 py-1.5 text-right tabular-nums">{fmtNumber(row.leads)}</td>
                                    <td className="px-2 py-1.5 text-right tabular-nums text-muted-foreground">{pct}%</td>
                                </tr>
                            );
                        })}
                    </tbody>
                    <tfoot className="sticky bottom-0 z-10">
                        <tr className="bg-muted/50 font-medium">
                            <td className="px-2 py-1.5">Total ({filtered.length})</td>
                            <td className="px-2 py-1.5 text-right tabular-nums">{fmtNumber(total)}</td>
                            <td className="px-2 py-1.5 text-right tabular-nums text-muted-foreground">100%</td>
                        </tr>
                    </tfoot>
                </table>
            </div>
        </div>
    );
}

/* ── Blocos ───────────────────────────────────────────────── */

function BlockKpis({ leadsKpis, trends, readiness, trendMode }) {
    return (
        <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-4">
            <KpiCard label="Leads Captados"     value={leadsKpis.leads_captados ?? 0}     format="number"  trend={trends.leads_captados} trendMode={trendMode} providers={["exent_hub"]} />
            <KpiCard label="Leads Válidos"      value={leadsKpis.leads_validos ?? 0}      format="number"  trend={trends.leads_validos} trendMode={trendMode} providers={["exent_hub"]} />
            <KpiCard label="Spam"               value={leadsKpis.spam ?? 0}               format="number"  trend={trends.spam} invertTrend trendMode={trendMode} providers={["exent_hub"]} />
            {readiness.hasQualified && (
                <KpiCard label="Qualificados"   value={leadsKpis.leads_qualificados ?? 0} format="number"  trend={trends.leads_qualificados} trendMode={trendMode} providers={["exent_hub"]} />
            )}
            {readiness.hasOpportunities && (
                <KpiCard label="Oportunidades"  value={leadsKpis.oportunidades ?? 0}      format="number"  trend={trends.oportunidades} trendMode={trendMode} providers={["exent_hub"]} />
            )}
        </div>
    );
}

function BlockTimeline({ readiness, approvalSeries }) {
    if (!readiness.hasTimeSeries || approvalSeries.length === 0) return null;
    return (
        <ChartCard title="Leads ao longo do tempo" description="Válidos e Spam empilhados por dia" providers={["exent_hub"]}>
            <ResponsiveContainer width="100%" height="100%">
                <BarChart data={approvalSeries} 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} allowDecimals={false} />
                    <Tooltip content={<DateTooltip />} />
                    <Legend wrapperStyle={{ fontSize: 12 }} />
                    <Bar dataKey="validos" name="Válidos" stackId="leads" fill={CHART_COLORS.blue} radius={[0, 0, 0, 0]} />
                    <Bar dataKey="spam" name="Spam" stackId="leads" fill={CHART_COLORS.red} radius={[3, 3, 0, 0]} />
                </BarChart>
            </ResponsiveContainer>
        </ChartCard>
    );
}

function BlockOrigemTimeline({ readiness, sourceDailyTs }) {
    if (!readiness.hasTimeSeries || !readiness.hasSourceSummary || sourceDailyTs.series.length < 2) return null;
    return (
        <ChartCard title="Leads por Origem ao longo do tempo" description="Distribuição diária de leads por canal de aquisição" providers={["exent_hub"]}>
            <ResponsiveContainer width="100%" height="100%">
                <AreaChart data={sourceDailyTs.series} 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} allowDecimals={false} />
                    <Tooltip content={<StackedTooltip />} />
                    <Legend wrapperStyle={{ fontSize: 12 }} />
                    {sourceDailyTs.channels.map((ch) => (
                        <Area key={ch.key} type="monotone" dataKey={ch.key} name={ch.label} stroke={ch.color} fill={ch.color} fillOpacity={0.15} strokeWidth={2} stackId="src" dot={false} />
                    ))}
                </AreaChart>
            </ResponsiveContainer>
        </ChartCard>
    );
}

function BlockOrigemRanking({ readiness, sourceRanking }) {
    if (!readiness.hasSourceSummary || sourceRanking.length === 0) return null;
    const data = sourceRanking.filter((s) => s.key !== "spam_discarded");
    return (
        <ChartCard title="Leads por Origem" providers={["exent_hub"]}>
            <ResponsiveContainer width="100%" height="100%">
                <BarChart data={data} layout="vertical" margin={{ top: 5, right: 20, left: 0, bottom: 5 }}>
                    <CartesianGrid strokeDasharray="3 3" stroke="hsl(var(--border))" horizontal={false} />
                    <XAxis type="number" tick={axisStyle} />
                    <YAxis type="category" dataKey="label" tick={axisStyle} width={100} />
                    <Tooltip content={({ active, payload }) => {
                        if (!active || !payload?.length) return null;
                        const d = payload[0]?.payload;
                        return (
                            <div className="rounded-md border bg-card px-3 py-2 text-xs shadow-md">
                                <p className="font-medium">{d.label}</p>
                                <p className="font-semibold">{fmtNumber(d.leads)} leads</p>
                            </div>
                        );
                    }} />
                    <Bar dataKey="leads" name="Leads" radius={[0, 4, 4, 0]}>
                        {data.map((s, i) => (<Cell key={s.key} fill={sourceColor(s.key, i)} />))}
                    </Bar>
                </BarChart>
            </ResponsiveContainer>
        </ChartCard>
    );
}

function BlockOrigemDonut({ readiness, sourcePieData }) {
    if (!readiness.hasSourceSummary || sourcePieData.length === 0) return null;
    return (
        <ChartCard title="Distribuição por Origem" description="Proporção de leads por canal (excl. spam)" providers={["exent_hub"]}>
            <ResponsiveContainer width="100%" height="100%">
                <PieChart>
                    <Pie data={sourcePieData} dataKey="value" cx="50%" cy="50%" innerRadius={50} outerRadius={85} strokeWidth={2} stroke="hsl(var(--card))" label={renderPieLabel} labelLine={false}>
                        {sourcePieData.map((entry) => (<Cell key={entry.name} fill={entry.fill} />))}
                    </Pie>
                    <Tooltip content={<PieTooltip />} />
                    <Legend wrapperStyle={{ fontSize: 12 }} formatter={(value, entry) => (<span style={{ color: entry.color }}>{value}</span>)} />
                </PieChart>
            </ResponsiveContainer>
        </ChartCard>
    );
}

function BlockCampanhas({ readiness, campaignRanking }) {
    if (!readiness.hasCampaignSummary || campaignRanking.length === 0) return null;
    return <CampaignTable data={campaignRanking} />;
}

function BlockPalavrasChave({ readiness, keywordRanking, hasUsableKeywords }) {
    if (!readiness.hasKeywordSummary || !hasUsableKeywords) return null;
    return <KeywordTable data={keywordRanking} />;
}

export const LEADS_DISPATCH = {
    leads_kpis:             BlockKpis,
    leads_timeline:         BlockTimeline,
    leads_origem_timeline:  BlockOrigemTimeline,
    leads_origem_ranking:   BlockOrigemRanking,
    leads_origem_donut:     BlockOrigemDonut,
    leads_campanhas:        BlockCampanhas,
    leads_palavras_chave:   BlockPalavrasChave,
};

/**
 * Hook compartilhado para montar os blockProps consumidos pelos componentes
 * de LEADS_DISPATCH. Usado tanto por LeadsFunilTab quanto por IntegrationTab
 * (aba Exent Hub) para evitar duplicacao.
 */
export function useLeadsBlockProps() {
    const { data } = useDashboardFilters();

    const crm             = data?.crm ?? [];
    const leadsKpis       = data?.leadsKpis ?? {};
    const trends          = data?.trends?.leadsKpis ?? {};
    const readiness       = data?.leadsReadiness ?? {};
    const sourceRanking   = data?.leadsSourceRanking ?? [];
    const campaignRanking = data?.leadsCampaignRanking ?? [];
    const keywordRanking  = data?.leadsKeywordRanking ?? [];

    const approvalSeries = useMemo(() => buildApprovalSeries(crm), [crm]);

    const sourceDailyTs = useMemo(
        () => buildSourceDailySeries(crm, sourceRanking),
        [crm, sourceRanking],
    );

    const sourcePieData = useMemo(() => {
        const filtered = sourceRanking.filter((s) => s.key !== "spam_discarded");
        const total = filtered.reduce((s, r) => s + r.leads, 0);
        return filtered.map((s, i) => ({
            name: s.label,
            value: s.leads,
            fill: sourceColor(s.key, i),
            pct: total > 0 ? Math.round((s.leads / total) * 1000) / 10 : 0,
        }));
    }, [sourceRanking]);

    const hasUsableKeywords = useMemo(
        () => keywordRanking.some((r) => r.key !== "unidentified"),
        [keywordRanking],
    );

    return {
        leadsKpis, trends, readiness,
        sourceRanking, campaignRanking, keywordRanking,
        approvalSeries, sourceDailyTs, sourcePieData,
        hasUsableKeywords,
    };
}

/* ── Main Component ──────────────────────────────────────── */

export default function LeadsFunilTab({ trendMode = "on", layout = null } = {}) {
    const { data, loading } = useDashboardFilters();
    const blockProps = useLeadsBlockProps();

    if (loading) return <DashboardSkeleton />;

    // Não bloqueia a aba quando o template tem um bloco de outro provider com dado (ex.: cvcrm).
    if (!blockProps.readiness.hasData && !layoutHasForeignData(layout, data)) {
        return (
            <Card>
                <CardContent className="py-12 text-center">
                    <p className="text-muted-foreground">Nenhum dado de leads (Exent Hub) no período selecionado.</p>
                </CardContent>
            </Card>
        );
    }

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