"use client";

import {
  TrendingUp, BarChart3, Phone, Mail, FileText,
  ArrowUpRight, ArrowDownRight, Minus, Info, DollarSign, Percent,
} from "lucide-react";
import { EmbeddedConversionsSummaryCard } from "./embedded-conversions-summary-card";
import {
  ResponsiveContainer, AreaChart, Area, XAxis, YAxis, CartesianGrid,
  Tooltip as RTooltip,
} from "recharts";

// ─── Types ──────────────────────────────────────────────────────────────────

interface GA4Data {
  dataOrigin: "conversion_event" | "metric_snapshot" | "none";
  totals: { conversions: number; revenue: number; avgValue: number; sessions: number; conversionRate: number };
  changes: {
    conversions: { pct: number; direction: string };
    revenue: { pct: number; direction: string };
    conversionRate: { pct: number; direction: string };
    sessions: { pct: number; direction: string };
  };
  byType: Array<{ type: string; count: number; revenue: number; change: { pct: number; direction: string } }>;
  byChannel: Array<{ channel: string; count: number; revenue: number; change: { pct: number; direction: string } }>;
  topPages: Array<{ name: string; count: number; revenue: number }>;
  dailyTrend: Array<{ date: string; count: number | null; revenue: number; siteTagCount?: number }>;
}

interface TagConversions {
  totalConversions: number;
  byType: Record<string, number>;
  conversionRate: number;
  topConvertingPages: Array<{ url: string; conversions: number }>;
  byUtmSource: Array<{ source: string; conversions: number }>;
}

export interface ConversionsTabProps {
  ga4: GA4Data | null;
  tagConversions: TagConversions | null;
  hasGa4: boolean;
  hasTag: boolean;
  brandId?: string;
  onNavigateToEmbedded?: () => void;
}

// ─── Icon for conversion type ───────────────────────────────────────────────

const typeIcons: Record<string, typeof Phone> = {
  click_to_call: Phone,
  form_submit: FileText,
  sms_submit: Mail,
};

// ─── Conversions Tab ────────────────────────────────────────────────────────

export function ConversionsTab({ ga4, tagConversions, hasGa4, hasTag, brandId, onNavigateToEmbedded }: ConversionsTabProps) {
  const tagTotal = tagConversions?.totalConversions ?? 0;
  const tagRate = tagConversions?.conversionRate ?? 0;
  const tagByType = tagConversions?.byType ?? {};

  const ga4Total = ga4?.totals.conversions ?? 0;
  const ga4Revenue = ga4?.totals.revenue ?? 0;
  const ga4Rate = ga4?.totals.conversionRate ?? 0;

  return (
    <div className="space-y-6">

      {/* Embedded conversions gateway — only shown when tag is installed */}
      {hasTag && brandId && (
        <EmbeddedConversionsSummaryCard
          brandId={brandId}
          onNavigate={onNavigateToEmbedded}
        />
      )}

      {/* Priority messaging */}
      {hasTag && tagTotal === 0 && hasGa4 && ga4Total > 0 && (
        <div className="flex items-start gap-2 rounded-xl border border-blue-200 bg-blue-50 px-4 py-3">
          <Info className="w-4 h-4 text-blue-600 mt-0.5 shrink-0" />
          <div className="text-xs text-blue-900 leading-relaxed">
            Site Tag data is collecting. GA4 data shown as supplement. Once the Site Tag records conversions they will appear above.
          </div>
        </div>
      )}

      {/* Site Tag Conversions — always first when tag installed */}
      {hasTag && (
        <>
          <SectionHeading title="Site Tag Conversions" subtitle="Machine Enhancing tracked events from the meSEO tag" />

          {tagTotal > 0 ? (
            <>
              {/* Per-type breakdown */}
              {Object.keys(tagByType).length > 0 && (
                <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
                  {Object.entries(tagByType).map(([type, count]) => {
                    const Icon = typeIcons[type] ?? TrendingUp;
                    return <SummaryCard key={type} label={formatType(type)} value={String(count)} icon={Icon} />;
                  })}
                </div>
              )}

              {/* Top Converting Pages (tag) */}
              {tagConversions && tagConversions.topConvertingPages.length > 0 && (
                <TableCard title="Top Converting Pages" icon={TrendingUp}>
                  <table className="w-full text-sm">
                    <thead>
                      <tr className="text-left text-[11px] font-semibold uppercase tracking-wider text-slate-400">
                        <th className="px-5 py-2">Page</th>
                        <th className="px-5 py-2 text-right">Conversions</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-slate-100">
                      {tagConversions.topConvertingPages.map((p) => (
                        <tr key={p.url}>
                          <td className="px-5 py-3 font-mono text-brand-600 truncate max-w-xs">{p.url}</td>
                          <td className="px-5 py-3 text-right font-bold text-slate-900 tabular-nums">{p.conversions}</td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </TableCard>
              )}

              {/* By UTM Source */}
              {tagConversions && tagConversions.byUtmSource.length > 0 && (
                <TableCard title="Conversions by UTM Source" icon={BarChart3}>
                  <table className="w-full text-sm">
                    <thead>
                      <tr className="text-left text-[11px] font-semibold uppercase tracking-wider text-slate-400">
                        <th className="px-5 py-2">Source</th>
                        <th className="px-5 py-2 text-right">Conversions</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-slate-100">
                      {tagConversions.byUtmSource.map((s) => (
                        <tr key={s.source}>
                          <td className="px-5 py-3 font-medium text-slate-800">{s.source}</td>
                          <td className="px-5 py-3 text-right font-bold text-slate-900 tabular-nums">{s.conversions}</td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </TableCard>
              )}
            </>
          ) : (
            <div className="bg-white rounded-xl border border-slate-100 px-5 py-4 text-xs text-slate-400">
              No Site Tag conversions recorded yet. Form submissions, phone clicks, and SMS events will appear here.
            </div>
          )}
        </>
      )}

      {/* Site Tag + no GA4 — gentle upsell hint. Surfaces only when
          Site Tag conversions exist so brands that are actively
          collecting see the "connect GA4 for cross-source comparisons"
          path without the empty-state noise. */}
      {hasTag && tagTotal > 0 && !hasGa4 && (
        <div className="flex items-start gap-2 rounded-xl border border-slate-200 bg-slate-50 px-4 py-3">
          <Info className="w-4 h-4 text-slate-500 mt-0.5 shrink-0" />
          <div className="text-xs text-slate-700 leading-relaxed">
            <span className="font-semibold">GA4 is not connected</span> for this brand. Connect it in Settings → Integrations to compare Site Tag conversions against Google's ground-truth conversion counts and quantify the ad-blocker / consent-rejection delta.
          </div>
        </div>
      )}

      {/* GA4 Conversions */}
      {hasGa4 && ga4 && (
        <>
          <SectionHeading
            title="GA4 Conversions"
            subtitle={hasTag ? "Supplementary data from Google Analytics" : (ga4.dataOrigin === "metric_snapshot" ? "Aggregate totals from GA4 daily snapshots" : "Per-event data from GA4")}
          />

          {ga4.dataOrigin === "metric_snapshot" && (
            <div className="flex items-start gap-2 rounded-xl border border-blue-200 bg-blue-50 px-4 py-3">
              <Info className="w-4 h-4 text-blue-600 mt-0.5 shrink-0" />
              <div className="text-xs text-blue-900 leading-relaxed">
                Showing aggregate GA4 conversion totals from daily snapshots.
                Connect GA4 conversion events for per-event breakdown by type and channel.
              </div>
            </div>
          )}

          {/* GA4 KPI cards */}
          <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
            <SummaryCard label="GA4 Conversions" value={ga4Total.toLocaleString()} icon={TrendingUp}
              change={ga4.changes.conversions} />
            <SummaryCard label="GA4 Conv. Rate" value={`${ga4Rate.toFixed(2)}%`} icon={Percent}
              change={ga4.changes.conversionRate} />
            <SummaryCard label="Revenue" value={`$${ga4Revenue.toLocaleString()}`} icon={DollarSign}
              change={ga4.changes.revenue} />
            <SummaryCard label="Sessions" value={(ga4.totals.sessions ?? 0).toLocaleString()} icon={BarChart3}
              change={ga4.changes.sessions} />
          </div>

          {/* Daily Conversion Trend */}
          {ga4.dailyTrend && ga4.dailyTrend.length > 0 && (
            <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
              <div className="px-5 py-3.5 border-b border-slate-100 flex items-center gap-2">
                <TrendingUp className="w-4 h-4 text-brand-600" />
                <h3 className="font-bold text-slate-800 text-sm">Daily Conversion Trend</h3>
              </div>
              <div className="px-2 pt-3 pb-2 h-64">
                <ResponsiveContainer width="100%" height="100%" minWidth={0} minHeight={120}>
                  <AreaChart data={ga4.dailyTrend}>
                    <defs>
                      <linearGradient id="convGradientTab" x1="0" y1="0" x2="0" y2="1">
                        <stop offset="0%" stopColor="#4f46e5" stopOpacity={0.35} />
                        <stop offset="100%" stopColor="#4f46e5" stopOpacity={0.02} />
                      </linearGradient>
                    </defs>
                    <CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0" vertical={false} />
                    <XAxis dataKey="date" tick={{ fontSize: 10 }} stroke="#94a3b8"
                      tickFormatter={(v) => new Date(v).toLocaleDateString(undefined, { month: "short", day: "numeric" })} />
                    <YAxis tick={{ fontSize: 10 }} stroke="#94a3b8" allowDecimals={false} />
                    <RTooltip
                      contentStyle={{ fontSize: "11px", borderRadius: "8px", border: "1px solid #e2e8f0" }}
                      labelFormatter={(v) => new Date(String(v)).toLocaleDateString(undefined, { month: "short", day: "numeric", year: "numeric" })}
                      formatter={(v: unknown) => [typeof v === "number" ? v.toLocaleString() : String(v), "Conversions"]} />
                    {ga4.dailyTrend.some((d: { siteTagCount?: number }) => (d.siteTagCount ?? 0) > 0) && (
                      <Area type="monotone" dataKey="siteTagCount" name="Site Tag" stroke="#10b981" strokeWidth={2} fill="url(#convGradientTab)" />
                    )}
                    {ga4.dailyTrend.some((d: { count: number | null }) => (d.count ?? 0) > 0) && (
                      <Area type="monotone" dataKey="count" name="GA4 Key Events" stroke="#4f46e5" strokeWidth={1.5} strokeDasharray="4 3" fill="none" connectNulls={false} />
                    )}
                  </AreaChart>
                </ResponsiveContainer>
              </div>
              <div className="px-5 pb-3 flex items-center gap-3 text-[10px]">
                <span className="flex items-center gap-1"><span className="w-3 h-0.5 bg-emerald-500 rounded" /> Site Tag</span>
                {ga4.dailyTrend.some((d: { count: number | null }) => (d.count ?? 0) > 0)
                  ? <span className="flex items-center gap-1"><span className="w-3 h-0.5 bg-indigo-500 rounded" style={{ borderTop: "1.5px dashed #4f46e5", height: 0 }} /> GA4</span>
                  : <span className="text-slate-400 italic">GA4 key events not configured</span>}
              </div>
            </div>
          )}

          {/* By Conversion Type */}
          {ga4.byType.length > 0 && (
            <TableCard title="By Conversion Type" icon={BarChart3}>
              <div className="divide-y divide-slate-100">
                {ga4.byType.map((t) => (
                  <div key={t.type} className="px-5 py-3 flex items-center gap-4">
                    <span className="text-sm font-semibold text-slate-800 flex-1 capitalize">{t.type.replace("_", " ")}</span>
                    <span className="text-sm font-bold text-slate-900 tabular-nums">{t.count}</span>
                    <span className="text-xs text-slate-400 tabular-nums w-20 text-right">${t.revenue.toLocaleString()}</span>
                    <ChangeBadge change={t.change} />
                  </div>
                ))}
              </div>
            </TableCard>
          )}

          {/* By Channel */}
          {ga4.byChannel.length > 0 && (
            <TableCard title="By Channel" icon={TrendingUp}>
              <div className="divide-y divide-slate-100">
                {ga4.byChannel.map((c) => (
                  <div key={c.channel} className="px-5 py-3 flex items-center gap-4">
                    <span className="text-sm font-semibold text-slate-800 flex-1 capitalize">{c.channel.replace("_", " ")}</span>
                    <span className="text-sm font-bold text-slate-900 tabular-nums">{c.count}</span>
                    <span className="text-xs text-slate-400 tabular-nums w-20 text-right">${c.revenue.toLocaleString()}</span>
                    <ChangeBadge change={c.change} />
                  </div>
                ))}
              </div>
            </TableCard>
          )}

          {/* Top Converting Pages (GA4) */}
          {ga4.topPages.length > 0 && (
            <TableCard title="Top Converting Pages (GA4)" icon={TrendingUp}>
              <div className="divide-y divide-slate-100">
                {ga4.topPages.map((p) => (
                  <div key={p.name} className="px-5 py-3 flex items-center gap-4">
                    <span className="text-sm font-mono text-brand-600 truncate flex-1">{p.name}</span>
                    <span className="text-sm font-bold text-slate-900 tabular-nums">{p.count}</span>
                    <span className="text-xs text-slate-400 tabular-nums">${p.revenue.toLocaleString()}</span>
                  </div>
                ))}
              </div>
            </TableCard>
          )}
        </>
      )}

      {/* Nothing at all */}
      {!hasTag && !hasGa4 && (
        <div className="bg-white rounded-xl border border-slate-200 p-8 text-center">
          <BarChart3 className="w-12 h-12 text-slate-200 mx-auto mb-3" />
          <h2 className="text-lg font-bold text-slate-900 mb-1">No Conversion Data</h2>
          <p className="text-sm text-slate-500 max-w-md mx-auto">
            Install the meSEO Site Tag or connect GA4 to see conversion analytics.
          </p>
        </div>
      )}
    </div>
  );
}

// ─── Shared Components ──────────────────────────────────────────────────────

function SectionHeading({ title, subtitle }: { title: string; subtitle: string }) {
  return (
    <div className="pt-2">
      <h2 className="text-base font-bold text-slate-900">{title}</h2>
      <p className="text-xs text-slate-500 mt-0.5">{subtitle}</p>
    </div>
  );
}

function SummaryCard({ label, value, icon: Icon, change, subtitle }: {
  label: string; value: string; icon?: typeof TrendingUp;
  change?: { pct: number; direction: string } | null;
  subtitle?: string;
}) {
  return (
    <div className="bg-white rounded-xl border border-slate-200 px-5 py-4">
      <div className="flex items-center justify-between mb-2">
        <p className="text-xs font-semibold text-slate-500 uppercase tracking-wide">{label}</p>
        {Icon && <Icon className="w-4 h-4 text-slate-300" />}
      </div>
      <p className="text-2xl font-bold text-slate-900 leading-none">{value}</p>
      {subtitle && <p className="text-[10px] text-slate-400 mt-1">{subtitle}</p>}
      {change && (
        <p className={`text-xs font-medium mt-1.5 flex items-center gap-0.5 ${change.direction === "up" ? "text-green-600" : change.direction === "down" ? "text-red-500" : "text-slate-400"}`}>
          {change.direction === "up" ? <ArrowUpRight className="w-3 h-3" /> : change.direction === "down" ? <ArrowDownRight className="w-3 h-3" /> : <Minus className="w-3 h-3" />}
          {Math.abs(change.pct)}% vs previous
        </p>
      )}
    </div>
  );
}

function TableCard({ title, icon: Icon, children }: { title: string; icon: typeof TrendingUp; children: React.ReactNode }) {
  return (
    <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
      <div className="px-5 py-3.5 border-b border-slate-100 flex items-center gap-2">
        <Icon className="w-4 h-4 text-brand-600" />
        <h3 className="font-bold text-slate-800 text-sm">{title}</h3>
      </div>
      {children}
    </div>
  );
}

function ChangeBadge({ change }: { change: { pct: number; direction: string } }) {
  if (change.direction === "flat") return <Minus className="w-3 h-3 text-slate-300" />;
  const up = change.direction === "up";
  return (
    <span className={`flex items-center gap-0.5 text-[11px] font-semibold ${up ? "text-green-600" : "text-red-500"}`}>
      {up ? <ArrowUpRight className="w-3 h-3" /> : <ArrowDownRight className="w-3 h-3" />}
      {Math.abs(change.pct)}%
    </span>
  );
}

function formatType(type: string): string {
  return type.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
}
