"use client";

import { useState, useEffect, useCallback } from "react";
import {
  Smartphone, Globe, TrendingUp, BarChart3, Layers, ChevronDown,
  ExternalLink, X, ArrowUpRight, ArrowDownRight, Minus, Filter,
} from "lucide-react";
import {
  ResponsiveContainer, BarChart, Bar, XAxis, YAxis, CartesianGrid,
  Tooltip as RTooltip, Cell, PieChart, Pie, Legend,
} from "recharts";

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

interface StatsStrip {
  totalEmbedded: { count: number; trendPct: number | null };
  totalIframeForms: { count: number };
  totalSmsOptins: { count: number };
  topChannel: { channel: string; count: number; percentOfTotal: number } | null;
  topUrl: { url: string; count: number } | null;
}

interface TimeSeriesPoint { date: string; category: string; count: number }

interface ProviderRow {
  provider: string;
  category: string;
  categoryLabel: string;
  completions: number;
  trendSparkline: number[];
}

interface UrlRow {
  url: string;
  totalConversions: number;
  categoryBreakdown: Record<string, number>;
  topProvider: string;
  topChannel: string;
  topChannelPct: number;
}

interface ChannelRow {
  channel: string;
  count: number;
  percentOfTotal: number;
  topProvider?: string;
  topCategory?: string;
}

interface EmbeddedData {
  statsStrip: StatsStrip;
  timeSeriesByCategory: TimeSeriesPoint[];
  providerBreakdown: ProviderRow[];
  topUrls: UrlRow[];
  channelAttribution: ChannelRow[];
  channelTable: ChannelRow[];
  meta: { days: number; from: string; categoryFilter: string; channelFilter: string };
}

interface DrillDownConversion {
  id: string;
  conversionType: string;
  formProvider: string | null;
  providerCategory: string | null;
  pageUrl: string;
  firstTouchChannel: string | null;
  sessionId: string;
  smsKeyword: string | null;
  smsConsentMethod: string | null;
  detectionMethod: string | null;
  timestamp: string;
}

interface DrillDownData {
  conversions: DrillDownConversion[];
  pagination: { total: number; page: number; pageSize: number; totalPages: number };
}

// ─── Constants ───────────────────────────────────────────────────────────────

const CATEGORY_COLORS: Record<string, string> = {
  booking: "#6366f1",
  form: "#8b5cf6",
  sms: "#10b981",
  chat: "#f59e0b",
  checkout: "#ef4444",
  donation: "#f97316",
  civic: "#3b82f6",
  survey: "#06b6d4",
  other: "#94a3b8",
};

const CATEGORY_LABELS: Record<string, string> = {
  booking: "Booking", form: "Iframe Form", sms: "SMS Opt-in",
  chat: "Chat Widget", checkout: "Checkout", donation: "Donation",
  civic: "Civic", survey: "Survey", other: "Other",
};

const DAYS_OPTIONS = [7, 30, 90] as const;
const CATEGORY_OPTIONS = ["all", "booking", "form", "sms", "chat", "checkout", "donation", "civic", "survey"] as const;

// ─── Helpers ─────────────────────────────────────────────────────────────────

function TrendBadge({ pct }: { pct: number | null }) {
  if (pct === null) return <span className="text-xs text-slate-400">no prior data</span>;
  if (Math.abs(pct) < 1) return <span className="flex items-center gap-0.5 text-xs text-slate-500"><Minus className="w-3 h-3" />0%</span>;
  if (pct > 0) return <span className="flex items-center gap-0.5 text-xs text-emerald-600 font-semibold"><ArrowUpRight className="w-3 h-3" />+{pct}%</span>;
  return <span className="flex items-center gap-0.5 text-xs text-red-500 font-semibold"><ArrowDownRight className="w-3 h-3" />{pct}%</span>;
}

function Sparkline({ data }: { data: number[] }) {
  if (!data.length) return <span className="text-slate-300">—</span>;
  const max = Math.max(...data, 1);
  return (
    <div className="flex items-end gap-px h-5">
      {data.map((v, i) => (
        <div key={i} className="w-1.5 bg-brand-400 rounded-sm" style={{ height: `${Math.max(10, (v / max) * 100)}%` }} />
      ))}
    </div>
  );
}

// ─── Stat card ───────────────────────────────────────────────────────────────

function StatCard({ label, value, sub, icon: Icon, color }: {
  label: string; value: string | number; sub?: React.ReactNode;
  icon: React.ElementType; color: string;
}) {
  return (
    <div className="bg-white rounded-xl border border-slate-100 p-4 flex items-start gap-3">
      <div className={`w-8 h-8 rounded-lg flex items-center justify-center shrink-0 ${color}`}>
        <Icon className="w-4 h-4 text-white" />
      </div>
      <div className="min-w-0">
        <p className="text-xs text-slate-500 font-medium">{label}</p>
        <p className="text-xl font-bold text-slate-900 tabular-nums">{value}</p>
        {sub && <div className="mt-0.5">{sub}</div>}
      </div>
    </div>
  );
}

// ─── Drill-down Modal ─────────────────────────────────────────────────────────

function DrillDownModal({ brandId, days, filterType, filterValue, onClose }: {
  brandId: string;
  days: number;
  filterType: "provider" | "url" | "channel";
  filterValue: string;
  onClose: () => void;
}) {
  const [data, setData] = useState<DrillDownData | null>(null);
  const [page, setPage] = useState(0);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    setLoading(true);
    fetch(`/api/site-tag-analytics/embedded-conversions/details?brandId=${brandId}&days=${days}&filterType=${filterType}&filterValue=${encodeURIComponent(filterValue)}&page=${page}`)
      .then((r) => r.json())
      .then((d) => { setData(d as DrillDownData); setLoading(false); })
      .catch(() => setLoading(false));
  }, [brandId, days, filterType, filterValue, page]);

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/40" onClick={onClose}>
      <div className="bg-white rounded-2xl shadow-2xl w-full max-w-3xl max-h-[80vh] overflow-hidden flex flex-col" onClick={(e) => e.stopPropagation()}>
        <div className="flex items-center justify-between px-5 py-4 border-b border-slate-100">
          <div>
            <h3 className="text-sm font-bold text-slate-900">Conversion Details</h3>
            <p className="text-xs text-slate-500 mt-0.5">
              {filterType === "provider" ? "Provider" : filterType === "url" ? "Page" : "Channel"}: <span className="font-mono text-slate-700">{filterValue}</span>
            </p>
          </div>
          <button onClick={onClose} className="p-1.5 hover:bg-slate-100 rounded-lg transition-colors">
            <X className="w-4 h-4 text-slate-500" />
          </button>
        </div>
        <div className="overflow-auto flex-1">
          {loading ? (
            <div className="flex items-center justify-center h-40">
              <div className="w-6 h-6 border-2 border-brand-100 border-t-brand-600 rounded-full animate-spin" />
            </div>
          ) : !data || data.conversions.length === 0 ? (
            <div className="p-8 text-center text-sm text-slate-400">No conversions found for this filter.</div>
          ) : (
            <table className="w-full text-xs">
              <thead className="sticky top-0 bg-slate-50 border-b border-slate-100">
                <tr className="text-left text-[10px] font-semibold uppercase tracking-wider text-slate-400">
                  <th className="px-4 py-2.5">Time</th>
                  <th className="px-4 py-2.5">Type</th>
                  <th className="px-4 py-2.5">Provider</th>
                  <th className="px-4 py-2.5">Page</th>
                  <th className="px-4 py-2.5">Channel</th>
                  <th className="px-4 py-2.5">SMS Info</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-50">
                {data.conversions.map((c) => (
                  <tr key={c.id} className="hover:bg-slate-50">
                    <td className="px-4 py-2.5 text-slate-500 whitespace-nowrap">{new Date(c.timestamp).toLocaleDateString()} {new Date(c.timestamp).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })}</td>
                    <td className="px-4 py-2.5 font-mono text-slate-700">{c.conversionType}</td>
                    <td className="px-4 py-2.5 text-slate-700">{c.formProvider ?? "—"}</td>
                    <td className="px-4 py-2.5 max-w-[160px] truncate font-mono text-brand-600">{c.pageUrl}</td>
                    <td className="px-4 py-2.5 text-slate-600">{c.firstTouchChannel ?? "direct"}</td>
                    <td className="px-4 py-2.5 text-slate-500">{c.smsKeyword ? `keyword: ${c.smsKeyword}` : c.smsConsentMethod ? c.smsConsentMethod : "—"}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </div>
        {data && data.pagination.totalPages > 1 && (
          <div className="flex items-center justify-between px-5 py-3 border-t border-slate-100 text-xs text-slate-500">
            <span>{data.pagination.total} total</span>
            <div className="flex items-center gap-2">
              <button disabled={page === 0} onClick={() => setPage((p) => p - 1)}
                className="px-2.5 py-1 rounded-lg border border-slate-200 disabled:opacity-40 hover:bg-slate-50">Prev</button>
              <span>Page {page + 1} / {data.pagination.totalPages}</span>
              <button disabled={page >= data.pagination.totalPages - 1} onClick={() => setPage((p) => p + 1)}
                className="px-2.5 py-1 rounded-lg border border-slate-200 disabled:opacity-40 hover:bg-slate-50">Next</button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

// ─── Main Tab Component ───────────────────────────────────────────────────────

export function EmbeddedConversionsTab({ brandId }: { brandId: string }) {
  const [days, setDays] = useState<7 | 30 | 90>(30);
  const [category, setCategory] = useState<typeof CATEGORY_OPTIONS[number]>("all");
  const [data, setData] = useState<EmbeddedData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [drillDown, setDrillDown] = useState<{ type: "provider" | "url" | "channel"; value: string } | null>(null);

  const loadData = useCallback(() => {
    if (!brandId) return;
    setLoading(true);
    setError(null);
    fetch(`/api/site-tag-analytics/embedded-conversions?brandId=${brandId}&days=${days}&category=${category}`)
      .then((r) => r.ok ? r.json() : Promise.reject(new Error(`HTTP ${r.status}`)))
      .then((d) => { setData(d as EmbeddedData); setLoading(false); })
      .catch((e) => { setError(e.message); setLoading(false); });
  }, [brandId, days, category]);

  useEffect(() => { loadData(); }, [loadData]);

  if (loading) {
    return (
      <div className="flex items-center justify-center h-48">
        <div className="w-7 h-7 border-2 border-brand-100 border-t-brand-600 rounded-full animate-spin" />
      </div>
    );
  }

  if (error || !data) {
    return (
      <div className="rounded-xl border border-red-200 bg-red-50 p-6 text-center">
        <p className="text-sm text-red-700">{error ?? "No data available."}</p>
        <button onClick={loadData} className="mt-3 text-xs font-semibold text-red-600 underline">Retry</button>
      </div>
    );
  }

  const { statsStrip, timeSeriesByCategory, providerBreakdown, topUrls, channelAttribution, channelTable } = data;

  // Build pivot table for stacked bar chart
  const dates = [...new Set(timeSeriesByCategory.map((p) => p.date))].sort();
  const categories = [...new Set(timeSeriesByCategory.map((p) => p.category))];
  const chartData = dates.map((date) => {
    const row: Record<string, string | number> = { date };
    for (const cat of categories) {
      row[cat] = timeSeriesByCategory.find((p) => p.date === date && p.category === cat)?.count ?? 0;
    }
    return row;
  });

  const totalEmbedded = statsStrip.totalEmbedded.count;

  return (
    <div className="space-y-6">
      {/* Filters */}
      <div className="flex items-center gap-3 flex-wrap">
        <div className="flex items-center bg-slate-100 rounded-lg p-1 gap-1">
          {DAYS_OPTIONS.map((d) => (
            <button key={d} onClick={() => setDays(d)}
              className={`px-3 py-1.5 rounded-md text-xs font-semibold transition-colors ${days === d ? "bg-white text-slate-900 shadow-sm" : "text-slate-500 hover:text-slate-700"}`}>
              {d}d
            </button>
          ))}
        </div>
        <div className="relative">
          <select value={category} onChange={(e) => setCategory(e.target.value as typeof category)}
            className="appearance-none text-xs font-semibold bg-white border border-slate-200 rounded-lg pl-3 pr-7 py-2 text-slate-700 focus:outline-none focus:ring-2 focus:ring-brand-500">
            {CATEGORY_OPTIONS.map((c) => (
              <option key={c} value={c}>{c === "all" ? "All categories" : CATEGORY_LABELS[c] ?? c}</option>
            ))}
          </select>
          <ChevronDown className="absolute right-2 top-2.5 w-3.5 h-3.5 text-slate-400 pointer-events-none" />
        </div>
        <div className="flex items-center gap-1 text-xs text-slate-400">
          <Filter className="w-3 h-3" />
          {totalEmbedded.toLocaleString()} embedded conversions
        </div>
      </div>

      {/* 1. Stats Strip */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        <StatCard
          label="Total Embedded"
          value={totalEmbedded.toLocaleString()}
          icon={Layers}
          color="bg-brand-600"
          sub={<TrendBadge pct={statsStrip.totalEmbedded.trendPct} />}
        />
        <StatCard
          label="Iframe Forms"
          value={statsStrip.totalIframeForms.count.toLocaleString()}
          icon={Globe}
          color="bg-violet-500"
        />
        <StatCard
          label="SMS Opt-ins"
          value={statsStrip.totalSmsOptins.count.toLocaleString()}
          icon={Smartphone}
          color="bg-emerald-500"
          sub={statsStrip.topChannel && (
            <span className="text-xs text-slate-400">
              Top: {statsStrip.topChannel.channel} ({statsStrip.topChannel.percentOfTotal}%)
            </span>
          )}
        />
        <StatCard
          label="Top Converting Page"
          value={statsStrip.topUrl?.count.toLocaleString() ?? "0"}
          icon={TrendingUp}
          color="bg-amber-500"
          sub={statsStrip.topUrl && (
            <span className="text-xs font-mono text-slate-500 truncate block max-w-[140px]">
              {statsStrip.topUrl.url}
            </span>
          )}
        />
      </div>

      {/* 2. Time Series by Category */}
      {chartData.length > 0 && (
        <div className="bg-white rounded-xl border border-slate-100 p-5">
          <h3 className="text-sm font-bold text-slate-900 mb-4">Embedded Conversions by Category</h3>
          <ResponsiveContainer width="100%" height={220}>
            <BarChart data={chartData} margin={{ top: 0, right: 0, left: -10, bottom: 0 }}>
              <CartesianGrid strokeDasharray="3 3" stroke="#f1f5f9" />
              <XAxis dataKey="date" tick={{ fontSize: 10, fill: "#94a3b8" }} tickLine={false} axisLine={false} />
              <YAxis tick={{ fontSize: 10, fill: "#94a3b8" }} tickLine={false} axisLine={false} />
              <RTooltip contentStyle={{ fontSize: 11, borderRadius: 8, border: "1px solid #e2e8f0" }} />
              {categories.map((cat) => (
                <Bar key={cat} dataKey={cat} stackId="a" name={CATEGORY_LABELS[cat] ?? cat} fill={CATEGORY_COLORS[cat] ?? "#94a3b8"} radius={[0, 0, 0, 0]} />
              ))}
            </BarChart>
          </ResponsiveContainer>
          {/* Legend */}
          <div className="flex flex-wrap gap-3 mt-3">
            {categories.map((cat) => (
              <div key={cat} className="flex items-center gap-1.5">
                <div className="w-2.5 h-2.5 rounded-sm" style={{ backgroundColor: CATEGORY_COLORS[cat] ?? "#94a3b8" }} />
                <span className="text-xs text-slate-600">{CATEGORY_LABELS[cat] ?? cat}</span>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* 3. Provider Performance Table */}
      {providerBreakdown.length > 0 && (
        <div className="bg-white rounded-xl border border-slate-100">
          <div className="px-5 py-4 border-b border-slate-100">
            <h3 className="text-sm font-bold text-slate-900">Provider Performance</h3>
          </div>
          <table className="w-full text-sm">
            <thead>
              <tr className="text-left text-[11px] font-semibold uppercase tracking-wider text-slate-400 border-b border-slate-100">
                <th className="px-5 py-2.5">Provider</th>
                <th className="px-5 py-2.5">Category</th>
                <th className="px-5 py-2.5 text-right">Completions</th>
                <th className="px-5 py-2.5">Trend (7d)</th>
                <th className="px-5 py-2.5 text-right">Actions</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-50">
              {providerBreakdown.map((p) => (
                <tr key={p.provider} className="hover:bg-slate-50">
                  <td className="px-5 py-3 font-medium text-slate-900">{p.provider}</td>
                  <td className="px-5 py-3">
                    <span className="inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-semibold"
                      style={{ backgroundColor: (CATEGORY_COLORS[p.category] ?? "#94a3b8") + "20", color: CATEGORY_COLORS[p.category] ?? "#64748b" }}>
                      {p.categoryLabel}
                    </span>
                  </td>
                  <td className="px-5 py-3 text-right font-bold text-slate-900 tabular-nums">{p.completions.toLocaleString()}</td>
                  <td className="px-5 py-3"><Sparkline data={p.trendSparkline} /></td>
                  <td className="px-5 py-3 text-right">
                    <button onClick={() => setDrillDown({ type: "provider", value: p.provider })}
                      className="text-xs text-brand-600 font-semibold hover:text-brand-700">View</button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {/* 4. Top Converting URLs */}
      {topUrls.length > 0 && (
        <div className="bg-white rounded-xl border border-slate-100">
          <div className="px-5 py-4 border-b border-slate-100">
            <h3 className="text-sm font-bold text-slate-900">Top Converting Pages</h3>
          </div>
          <table className="w-full text-sm">
            <thead>
              <tr className="text-left text-[11px] font-semibold uppercase tracking-wider text-slate-400 border-b border-slate-100">
                <th className="px-5 py-2.5">Page URL</th>
                <th className="px-5 py-2.5 text-right">Conversions</th>
                <th className="px-5 py-2.5">Top Provider</th>
                <th className="px-5 py-2.5">Top Channel</th>
                <th className="px-5 py-2.5 text-right">Actions</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-50">
              {topUrls.map((u) => (
                <tr key={u.url} className="hover:bg-slate-50">
                  <td className="px-5 py-3 max-w-xs">
                    <div className="flex items-center gap-1.5">
                      <span className="font-mono text-brand-600 truncate text-xs">{u.url}</span>
                      <a href={u.url} target="_blank" rel="noopener noreferrer" className="shrink-0 text-slate-300 hover:text-slate-500">
                        <ExternalLink className="w-3 h-3" />
                      </a>
                    </div>
                    {/* Category mini-bar */}
                    <div className="flex h-1.5 rounded-full overflow-hidden mt-1.5 bg-slate-100 w-24">
                      {Object.entries(u.categoryBreakdown).map(([cat, cnt]) => (
                        <div key={cat} title={`${CATEGORY_LABELS[cat] ?? cat}: ${cnt}`}
                          style={{ width: `${(cnt / u.totalConversions) * 100}%`, backgroundColor: CATEGORY_COLORS[cat] ?? "#94a3b8" }} />
                      ))}
                    </div>
                  </td>
                  <td className="px-5 py-3 text-right font-bold text-slate-900 tabular-nums">{u.totalConversions.toLocaleString()}</td>
                  <td className="px-5 py-3 text-slate-700">{u.topProvider}</td>
                  <td className="px-5 py-3 text-slate-600">{u.topChannel} <span className="text-slate-400 text-xs">({u.topChannelPct}%)</span></td>
                  <td className="px-5 py-3 text-right">
                    <button onClick={() => setDrillDown({ type: "url", value: u.url })}
                      className="text-xs text-brand-600 font-semibold hover:text-brand-700">View</button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {/* 5. Channel Attribution */}
      {channelAttribution.length > 0 && (
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-5">
          <div className="bg-white rounded-xl border border-slate-100 p-5">
            <h3 className="text-sm font-bold text-slate-900 mb-4">Channel Attribution</h3>
            <ResponsiveContainer width="100%" height={220}>
              <PieChart>
                <Pie data={channelAttribution} dataKey="count" nameKey="channel" cx="50%" cy="50%" outerRadius={80}
                  label={(props) => `${String((props as unknown as ChannelRow).channel ?? "")} ${String((props as unknown as ChannelRow).percentOfTotal ?? "")}%`}
                  labelLine={false}>
                  {channelAttribution.map((_, i) => (
                    <Cell key={i} fill={["#6366f1", "#10b981", "#f59e0b", "#ef4444", "#3b82f6", "#8b5cf6", "#06b6d4", "#f97316", "#94a3b8"][i % 9]} />
                  ))}
                </Pie>
                <RTooltip contentStyle={{ fontSize: 11, borderRadius: 8 }} />
              </PieChart>
            </ResponsiveContainer>
          </div>
          <div className="bg-white rounded-xl border border-slate-100">
            <div className="px-5 py-4 border-b border-slate-100">
              <h3 className="text-sm font-bold text-slate-900">Channel Breakdown</h3>
            </div>
            <table className="w-full text-sm">
              <thead>
                <tr className="text-left text-[11px] font-semibold uppercase tracking-wider text-slate-400 border-b border-slate-100">
                  <th className="px-4 py-2">Channel</th>
                  <th className="px-4 py-2 text-right">Count</th>
                  <th className="px-4 py-2 text-right">%</th>
                  <th className="px-4 py-2">Top Provider</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-50">
                {channelTable.map((c) => (
                  <tr key={c.channel} className="hover:bg-slate-50 cursor-pointer"
                    onClick={() => setDrillDown({ type: "channel", value: c.channel })}>
                    <td className="px-4 py-2.5 font-medium text-slate-800">{c.channel || "direct"}</td>
                    <td className="px-4 py-2.5 text-right tabular-nums font-bold text-slate-900">{c.count.toLocaleString()}</td>
                    <td className="px-4 py-2.5 text-right text-slate-500 text-xs">{c.percentOfTotal}%</td>
                    <td className="px-4 py-2.5 text-slate-600 text-xs">{c.topProvider ?? "—"}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {/* Empty state */}
      {totalEmbedded === 0 && (
        <div className="bg-white rounded-xl border border-slate-100 p-10 text-center">
          <Layers className="w-10 h-10 text-slate-200 mx-auto mb-3" />
          <h3 className="text-sm font-semibold text-slate-900 mb-1">No embedded conversions yet</h3>
          <p className="text-xs text-slate-500 max-w-sm mx-auto">
            Iframe form completions and SMS opt-ins from Calendly, Attentive, HubSpot, and other embedded providers will appear here once visitors convert through them.
          </p>
        </div>
      )}

      {/* Drill-down Modal */}
      {drillDown && (
        <DrillDownModal
          brandId={brandId}
          days={days}
          filterType={drillDown.type}
          filterValue={drillDown.value}
          onClose={() => setDrillDown(null)}
        />
      )}
    </div>
  );
}
