"use client";

import { useState, useEffect, useCallback } from "react";
import { Puzzle, CheckCircle2, AlertTriangle, ExternalLink, Plus, Loader2, MessageSquare } from "lucide-react";

interface PluginDetected {
  name: string;
  key: string;
  category: string;
  firstSeenAt: string;
  lastSeenAt: string;
  trackingLevel: "full" | "limited";
  trackingNote: string;
}

interface ExternalConverter {
  domain: string;
  nickname: string;
  isActive: boolean;
  registeredAt: string;
}

interface SuggestedConverter {
  domain: string;
  clickCount: number;
  isRegistered: boolean;
}

export function DetectedIntegrationsPanel({ brandId, sections = "all" }: { brandId: string; sections?: "all" | "active" | "external" }) {
  const [plugins, setPlugins] = useState<PluginDetected[] | null>(null);
  const [converters, setConverters] = useState<ExternalConverter[]>([]);
  const [suggestions, setSuggestions] = useState<SuggestedConverter[]>([]);
  const [loading, setLoading] = useState(true);
  const [registering, setRegistering] = useState<string | null>(null);

  const load = useCallback(async () => {
    if (!brandId) return;
    setLoading(true);
    try {
      const [siteRes, convRes, suggestRes] = await Promise.allSettled([
        fetch(`/api/site-tag?brandId=${brandId}`).then((r) => r.ok ? r.json() : Promise.reject()),
        fetch(`/api/brands/${brandId}/external-converters`).then((r) => r.ok ? r.json() : Promise.reject()),
        fetch(`/api/site-tag/suggested-converters?brandId=${brandId}`).then((r) => r.ok ? r.json() : Promise.reject()),
      ]);

      if (siteRes.status === "fulfilled") {
        setPlugins(Array.isArray(siteRes.value.pluginsDetected) ? siteRes.value.pluginsDetected : []);
      } else {
        setPlugins([]);
      }
      if (convRes.status === "fulfilled") {
        setConverters(Array.isArray(convRes.value.converters) ? convRes.value.converters : []);
      }
      if (suggestRes.status === "fulfilled") {
        setSuggestions(Array.isArray(suggestRes.value.suggestions) ? suggestRes.value.suggestions : []);
      }
    } catch (err) {
      console.warn("[DetectedIntegrationsPanel] fetch failed:", err);
      setPlugins([]);
    } finally {
      setLoading(false);
    }
  }, [brandId]);

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

  const registerConverter = async (domain: string) => {
    setRegistering(domain);
    try {
      const res = await fetch(`/api/brands/${brandId}/external-converters`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ domain }),
      });
      if (res.ok) {
        const data = await res.json() as { converter: ExternalConverter };
        setConverters((prev) => {
          const exists = prev.find((c) => c.domain === domain);
          return exists ? prev.map((c) => c.domain === domain ? data.converter : c) : [...prev, data.converter];
        });
        setSuggestions((prev) => prev.map((s) => s.domain === domain ? { ...s, isRegistered: true } : s));
      }
    } catch (err) {
      console.warn("[DetectedIntegrationsPanel] register failed:", err);
    } finally {
      setRegistering(null);
    }
  };

  if (loading) {
    return (
      <div className="bg-white rounded-xl border border-slate-200 overflow-hidden animate-pulse">
        <div className="px-5 py-3.5 border-b border-slate-100 flex items-center gap-2">
          <div className="w-4 h-4 rounded bg-slate-200" />
          <div className="h-4 w-40 rounded bg-slate-200" />
        </div>
        <div className="px-5 py-3.5 flex items-center gap-3">
          <div className="h-6 w-36 rounded bg-slate-100" />
          <div className="flex-1 h-3 rounded bg-slate-100" />
        </div>
      </div>
    );
  }

  const bookingPlugins = (plugins ?? []).filter((p) => p.category !== "chat");
  const chatWidgets = (plugins ?? []).filter((p) => p.category === "chat");
  const activePlugins = [...bookingPlugins, ...chatWidgets];
  const unregisteredSuggestions = suggestions.filter((s) => !s.isRegistered);

  const hasActive = activePlugins.length > 0;
  const hasExternal = converters.length > 0 || unregisteredSuggestions.length > 0;
  const hasAnything = sections === "active" ? hasActive : sections === "external" ? hasExternal : (hasActive || hasExternal);

  if (!hasAnything) {
    // When showing only external converters, render nothing rather than an empty panel
    if (sections === "external") return null;
    return (
      <div className="bg-white rounded-xl border border-slate-200 px-5 py-4 flex items-center gap-3">
        <Puzzle className="w-4 h-4 text-slate-300 shrink-0" />
        <p className="text-xs text-slate-400">
          No integrations detected yet — Site Tag scans on each page load.
        </p>
      </div>
    );
  }

  return (
    <div className="space-y-3">
      {/* ── Active Integrations ── */}
      {sections !== "external" && activePlugins.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">
            <Puzzle className="w-4 h-4 text-indigo-600" />
            <h2 className="font-bold text-slate-800 text-sm">Active Integrations</h2>
            <span className="ml-auto text-[10px] font-semibold text-slate-400">
              {activePlugins.length} detected
            </span>
          </div>
          <div className="divide-y divide-slate-100">
            {bookingPlugins.length > 0 && (
              <div className="px-5 pt-3 pb-1">
                <p className="text-[9px] font-bold uppercase tracking-widest text-slate-400 mb-2">Booking &amp; Forms</p>
                <div className="space-y-2.5 pb-2">
                  {bookingPlugins.map((p) => (
                    <PluginRow key={p.key} plugin={p} />
                  ))}
                </div>
              </div>
            )}
            {chatWidgets.length > 0 && (
              <div className="px-5 pt-3 pb-1">
                <div className="flex items-center gap-1.5 mb-2">
                  <MessageSquare className="w-3 h-3 text-slate-400" />
                  <p className="text-[9px] font-bold uppercase tracking-widest text-slate-400">Chat Widgets</p>
                </div>
                <div className="space-y-2.5 pb-2">
                  {chatWidgets.map((p) => (
                    <PluginRow key={p.key} plugin={p} />
                  ))}
                </div>
              </div>
            )}
          </div>
          <div className="px-5 py-2.5 border-t border-slate-100 bg-slate-50/40 text-[10px] text-slate-500">
            Detection runs automatically — install a new plugin and it&apos;ll appear here within minutes.
          </div>
        </div>
      )}

      {/* ── External Converters ── */}
      {sections !== "active" && (converters.length > 0 || unregisteredSuggestions.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">
            <ExternalLink className="w-4 h-4 text-emerald-600" />
            <h2 className="font-bold text-slate-800 text-sm">External Converters</h2>
            <span className="ml-auto text-[10px] font-semibold text-slate-400">
              off-domain conversion tracking
            </span>
          </div>

          {converters.length > 0 && (
            <div className="divide-y divide-slate-100">
              {converters.map((c) => (
                <div key={c.domain} className="px-5 py-3 flex items-center gap-3">
                  <span className="inline-flex items-center gap-1.5 text-[11px] font-bold text-emerald-700 bg-emerald-50 border border-emerald-200 px-2 py-0.5 rounded shrink-0 min-w-[160px]">
                    <ExternalLink className="w-3 h-3" />
                    {c.nickname || c.domain}
                  </span>
                  <span className="text-[10px] text-slate-400 font-mono flex-1">{c.domain}</span>
                  <span className="inline-flex items-center gap-1 text-[10px] font-bold uppercase tracking-wide text-emerald-700 bg-emerald-50 border border-emerald-200 rounded px-2 py-0.5 shrink-0">
                    <CheckCircle2 className="w-3 h-3" />
                    Tracking
                  </span>
                </div>
              ))}
            </div>
          )}

          {unregisteredSuggestions.length > 0 && (
            <div className="px-5 pt-3 pb-1 border-t border-slate-100">
              <p className="text-[9px] font-bold uppercase tracking-widest text-slate-400 mb-2">
                Suggested — high-frequency outbound destinations (last 30d)
              </p>
              <div className="space-y-2 pb-3">
                {unregisteredSuggestions.map((s) => (
                  <div key={s.domain} className="flex items-center gap-3">
                    <span className="text-[11px] font-mono text-slate-600 flex-1">{s.domain}</span>
                    <span className="text-[10px] text-slate-400">{s.clickCount} clicks</span>
                    <button
                      type="button"
                      onClick={() => registerConverter(s.domain)}
                      disabled={registering === s.domain}
                      className="inline-flex items-center gap-1 text-[10px] font-bold text-brand-700 bg-brand-50 border border-brand-200 rounded px-2 py-0.5 hover:bg-brand-100 transition-colors disabled:opacity-50"
                    >
                      {registering === s.domain
                        ? <Loader2 className="w-3 h-3 animate-spin" />
                        : <Plus className="w-3 h-3" />}
                      Track as conversion
                    </button>
                  </div>
                ))}
              </div>
            </div>
          )}

          <div className="px-5 py-2.5 border-t border-slate-100 bg-slate-50/40 text-[10px] text-slate-500">
            External converters fire an <span className="font-mono">external_conversion_initiated</span> event when a visitor clicks through — counted in conversion totals.
          </div>
        </div>
      )}
    </div>
  );
}

function PluginRow({ plugin: p }: { plugin: PluginDetected }) {
  return (
    <div className="flex items-center gap-3">
      <span className="inline-flex items-center gap-1.5 text-[11px] font-bold text-indigo-700 bg-indigo-50 border border-indigo-200 px-2 py-0.5 rounded shrink-0 min-w-[140px]">
        <Puzzle className="w-3 h-3" />
        {p.name}
      </span>
      <div className="flex-1 min-w-0">
        <p className="text-[11px] text-slate-500 leading-snug">{p.trackingNote}</p>
      </div>
      {p.trackingLevel === "full" ? (
        <span className="inline-flex items-center gap-1 text-[10px] font-bold uppercase tracking-wide text-emerald-700 bg-emerald-50 border border-emerald-200 rounded px-2 py-0.5 shrink-0">
          <CheckCircle2 className="w-3 h-3" />
          Full tracking
        </span>
      ) : (
        <span className="inline-flex items-center gap-1 text-[10px] font-bold uppercase tracking-wide text-amber-700 bg-amber-50 border border-amber-200 rounded px-2 py-0.5 shrink-0">
          <AlertTriangle className="w-3 h-3" />
          Limited
        </span>
      )}
    </div>
  );
}
