"use client";

import { useState, useEffect } from "react";
import { Layers, TrendingUp, TrendingDown, Minus, ArrowRight } from "lucide-react";

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

export function EmbeddedConversionsSummaryCard({
  brandId,
  onNavigate,
}: {
  brandId: string;
  onNavigate?: () => void;
}) {
  const [data, setData] = useState<SummaryData | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (!brandId) return;
    let cancelled = false;
    setLoading(true);
    fetch(`/api/site-tag-analytics/embedded-conversions?brandId=${brandId}&days=30`)
      .then((r) => r.ok ? r.json() : null)
      .then((json) => {
        if (!cancelled && json?.statsStrip) setData(json.statsStrip);
      })
      .catch(() => {})
      .finally(() => { if (!cancelled) setLoading(false); });
    return () => { cancelled = true; };
  }, [brandId]);

  if (loading) {
    return (
      <div className="bg-white rounded-xl border border-slate-200 p-5 animate-pulse">
        <div className="flex items-center gap-2 mb-3">
          <div className="w-4 h-4 bg-slate-200 rounded" />
          <div className="h-4 w-40 bg-slate-200 rounded" />
        </div>
        <div className="grid grid-cols-3 gap-4">
          {[0, 1, 2].map((i) => (
            <div key={i} className="h-14 bg-slate-100 rounded-lg" />
          ))}
        </div>
      </div>
    );
  }

  if (!data || data.totalEmbedded.count === 0) return null;

  const { totalEmbedded, totalIframeForms, totalSmsOptins, topChannel } = data;
  const trend = totalEmbedded.trendPct;

  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 justify-between">
        <div className="flex items-center gap-2">
          <Layers className="w-4 h-4 text-indigo-500" />
          <h3 className="font-bold text-slate-800 text-sm">Embedded Conversions</h3>
          <span className="text-[10px] text-slate-400 font-medium">last 30 days</span>
        </div>
        {onNavigate && (
          <button
            onClick={onNavigate}
            className="flex items-center gap-1 text-[11px] font-semibold text-indigo-600 hover:text-indigo-700 transition-colors"
          >
            View full report
            <ArrowRight className="w-3 h-3" />
          </button>
        )}
      </div>

      <div className="px-5 py-4 grid grid-cols-2 sm:grid-cols-4 gap-4">
        <div>
          <p className="text-[10px] font-semibold text-slate-400 uppercase tracking-wide mb-1">Total Embedded</p>
          <p className="text-2xl font-bold text-slate-900 leading-none tabular-nums">
            {totalEmbedded.count.toLocaleString()}
          </p>
          {trend !== null && (
            <p className={`text-xs font-medium mt-1 flex items-center gap-0.5 ${trend > 0 ? "text-green-600" : trend < 0 ? "text-red-500" : "text-slate-400"}`}>
              {trend > 0 ? <TrendingUp className="w-3 h-3" /> : trend < 0 ? <TrendingDown className="w-3 h-3" /> : <Minus className="w-3 h-3" />}
              {trend > 0 ? "+" : ""}{trend}% vs prior
            </p>
          )}
        </div>

        <div>
          <p className="text-[10px] font-semibold text-slate-400 uppercase tracking-wide mb-1">Iframe Forms</p>
          <p className="text-2xl font-bold text-slate-900 leading-none tabular-nums">
            {totalIframeForms.count.toLocaleString()}
          </p>
          <p className="text-[10px] text-slate-400 mt-1">bookings + form fills</p>
        </div>

        <div>
          <p className="text-[10px] font-semibold text-slate-400 uppercase tracking-wide mb-1">SMS Opt-ins</p>
          <p className="text-2xl font-bold text-emerald-600 leading-none tabular-nums">
            {totalSmsOptins.count.toLocaleString()}
          </p>
          <p className="text-[10px] text-slate-400 mt-1">consent captures</p>
        </div>

        <div>
          <p className="text-[10px] font-semibold text-slate-400 uppercase tracking-wide mb-1">Top Channel</p>
          {topChannel ? (
            <>
              <p className="text-sm font-bold text-slate-900 capitalize leading-snug">
                {topChannel.channel.replace(/_/g, " ")}
              </p>
              <p className="text-[10px] text-slate-400 mt-0.5">
                {topChannel.count.toLocaleString()} ({topChannel.percentOfTotal}%)
              </p>
            </>
          ) : (
            <p className="text-sm text-slate-400">--</p>
          )}
        </div>
      </div>
    </div>
  );
}
