"use client";

import { useState, useEffect, type ComponentType } from "react";
import {
  Puzzle, Loader2, AlertCircle, RefreshCw,
  BarChart3, Target, Search, FileText, Layout, Calendar,
  MessageCircle, Star, Users, Zap, Shield, ShoppingCart, UserPlus, Globe,
} from "lucide-react";

interface DetectedIntegration {
  id: string;
  name: string;
  category: string;
  vendor: string | null;
  version: string | null;
  description: string | null;
  firstDetectedAt: string;
  lastDetectedAt: string;
  detectionSources: string[];
  pageCount: number;
  samplePages: string[];
  status: string;
  isActive: boolean;
}

interface IntegrationsData {
  integrations: DetectedIntegration[];
  total: number;
  byCategory: Record<string, number>;
}

const CATEGORY_LABELS: Record<string, string> = {
  analytics: "Analytics",
  pixel: "Tracking Pixel",
  seo: "SEO",
  form: "Form Provider",
  page_builder: "Page Builder",
  booking: "Booking",
  chat: "Chat Widget",
  reviews: "Reviews",
  crm: "CRM",
  cache: "Cache",
  security: "Security",
  ecommerce: "E-commerce",
  lead_gen: "Lead Generation",
  other: "Other",
};

const CATEGORY_ICONS: Record<string, ComponentType<{ className?: string }>> = {
  analytics: BarChart3,
  pixel: Target,
  seo: Search,
  form: FileText,
  page_builder: Layout,
  booking: Calendar,
  chat: MessageCircle,
  reviews: Star,
  crm: Users,
  cache: Zap,
  security: Shield,
  ecommerce: ShoppingCart,
  lead_gen: UserPlus,
  other: Puzzle,
};

const CATEGORY_ORDER = [
  "analytics", "pixel", "seo", "form", "booking", "chat",
  "reviews", "lead_gen", "crm", "ecommerce", "page_builder",
  "cache", "security", "other",
];

function formatDate(iso: string): string {
  return new Date(iso).toLocaleDateString(undefined, {
    month: "short",
    day: "numeric",
    year: "numeric",
  });
}

function computeStats(integrations: DetectedIntegration[], byCategory: Record<string, number>) {
  const topEntry = Object.entries(byCategory).sort((a, b) => b[1] - a[1])[0];
  const topCategory = topEntry ? { key: topEntry[0], count: topEntry[1] } : null;

  const newest = integrations.length
    ? integrations.reduce((a, b) =>
        new Date(a.lastDetectedAt) > new Date(b.lastDetectedAt) ? a : b
      )
    : null;

  const vendorCount = new Set(
    integrations.map((i) => i.vendor).filter(Boolean)
  ).size;

  return { topCategory, newest, vendorCount };
}

interface SitePlatformData {
  name: string | null;
  version: string | null;
  confidence: string | null; // "high" | "medium" | "low"
  category: string | null;
  detectedAt: string | null;
  hosting: string | null;
  hostingDetectedAt: string | null;
}

const PLATFORM_LABELS: Record<string, string> = {
  wordpress: "WordPress", woocommerce: "WooCommerce", shopify: "Shopify",
  wix: "Wix", webflow: "Webflow", squarespace: "Squarespace", weebly: "Weebly",
  duda: "Duda", drupal: "Drupal", joomla: "Joomla!", ghost: "Ghost",
  magento: "Magento", bigcommerce: "BigCommerce", nextjs: "Next.js",
  nuxt: "Nuxt", gatsby: "Gatsby", remix: "Remix", astro: "Astro",
  sveltekit: "SvelteKit", vue: "Vue", react: "React", angular: "Angular",
  jekyll: "Jekyll", hugo: "Hugo", eleventy: "Eleventy",
};

const HOSTING_LABELS: Record<string, string> = {
  vercel: "Vercel", netlify: "Netlify", github_pages: "GitHub Pages",
  cloudflare_cdn: "Cloudflare CDN", wpengine: "WP Engine", kinsta: "Kinsta",
};

function PlatformCard({ platform }: { platform: SitePlatformData }) {
  const name = platform.name ?? "Unknown";
  const label = PLATFORM_LABELS[name] ?? name;
  const hostingLabel = platform.hosting ? (HOSTING_LABELS[platform.hosting] ?? platform.hosting) : null;
  const category = platform.category ?? "";
  const categoryLabel = category === "cms" ? "CMS" : category === "ecommerce" ? "E-commerce" :
    category === "js_framework" ? "JS Framework" : category === "static_site" ? "Static Site" : "Platform";
  const detectedDate = platform.detectedAt ? new Date(platform.detectedAt).toLocaleDateString(undefined, { month: "short", day: "numeric", year: "numeric" }) : null;

  return (
    <div className="rounded-xl border border-indigo-100 bg-indigo-50/50 p-4 mb-6">
      <div className="flex items-start gap-3">
        <div className="rounded-lg bg-indigo-100 p-2 shrink-0">
          <Globe className="h-5 w-5 text-indigo-600" />
        </div>
        <div className="flex-1 min-w-0">
          <div className="flex items-center gap-2 flex-wrap">
            <p className="text-xs font-semibold uppercase tracking-wider text-indigo-500">Site Platform</p>
            <span className="rounded-full bg-indigo-100 px-2 py-0.5 text-[10px] font-medium text-indigo-600">{categoryLabel}</span>
          </div>
          <div className="mt-1 flex items-baseline gap-2 flex-wrap">
            <span className="text-lg font-bold text-gray-900">{label}</span>
            {platform.version && <span className="text-sm text-gray-500">v{platform.version}</span>}
          </div>
          <div className="mt-1 flex items-center gap-3 text-xs text-gray-500 flex-wrap">
            {hostingLabel && <span>Hosted on <span className="font-medium text-gray-700">{hostingLabel}</span></span>}
            {detectedDate && <span>Detected {detectedDate}</span>}
            {platform.confidence && <span className="text-gray-400">{platform.confidence} confidence</span>}
          </div>
        </div>
      </div>
    </div>
  );
}

export function IntegrationsTab({ brandId, sitePlatform }: { brandId: string; sitePlatform?: SitePlatformData | null }) {
  const [data, setData] = useState<IntegrationsData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [categoryFilter, setCategoryFilter] = useState<string>("all");

  const load = async () => {
    setLoading(true);
    setError(null);
    try {
      const params = new URLSearchParams({ brandId, status: "active" });
      const res = await fetch(`/api/site-tag-analytics/integrations?${params}`);
      if (!res.ok) throw new Error("Failed to load integrations");
      setData(await res.json());
    } catch (e) {
      setError(e instanceof Error ? e.message : "Unknown error");
    } finally {
      setLoading(false);
    }
  };

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

  if (loading) {
    return (
      <div className="flex items-center justify-center py-20">
        <Loader2 className="h-6 w-6 animate-spin text-gray-400" />
      </div>
    );
  }

  if (error) {
    return (
      <div className="rounded-lg border border-red-200 bg-red-50 p-6 flex items-center gap-3">
        <AlertCircle className="h-5 w-5 text-red-500 shrink-0" />
        <p className="text-sm text-red-700">{error}</p>
        <button onClick={load} className="ml-auto text-sm text-red-600 hover:underline flex items-center gap-1">
          <RefreshCw className="h-3.5 w-3.5" /> Retry
        </button>
      </div>
    );
  }

  const integrations = data?.integrations ?? [];
  const byCategory = data?.byCategory ?? {};
  const total = data?.total ?? 0;

  const presentCategories = CATEGORY_ORDER.filter((c) => byCategory[c]);

  const visibleCategories =
    categoryFilter === "all"
      ? presentCategories
      : presentCategories.filter((c) => c === categoryFilter);

  const grouped = presentCategories.reduce<Record<string, DetectedIntegration[]>>((acc, cat) => {
    acc[cat] = integrations.filter((i) => i.category === cat);
    return acc;
  }, {});

  const { topCategory, newest, vendorCount } = computeStats(integrations, byCategory);

  return (
    <div className="space-y-6">
      {sitePlatform?.name && <PlatformCard platform={sitePlatform} />}

      {/* Header row */}
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-lg font-semibold text-gray-900">Detected Integrations</h2>
          <p className="text-sm text-gray-500 mt-0.5">
            {total === 0
              ? "No integrations detected yet"
              : `${total} integration${total !== 1 ? "s" : ""} detected across your site`}
          </p>
        </div>
        <button
          onClick={load}
          className="flex items-center gap-1.5 rounded-md border border-gray-200 bg-white px-3 py-1.5 text-sm text-gray-600 hover:bg-gray-50"
        >
          <RefreshCw className="h-3.5 w-3.5" />
          Refresh
        </button>
      </div>

      {/* Stats strip */}
      {total > 0 && (
        <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
          <div className="rounded-xl border border-gray-200 bg-white px-4 py-3">
            <p className="text-xs text-gray-500">Total</p>
            <p className="mt-0.5 text-xl font-semibold text-gray-900">{total}</p>
            <p className="text-xs text-gray-400">integrations</p>
          </div>
          <div className="rounded-xl border border-gray-200 bg-white px-4 py-3">
            <p className="text-xs text-gray-500">Top category</p>
            <p className="mt-0.5 text-sm font-semibold text-gray-900 truncate">
              {topCategory ? (CATEGORY_LABELS[topCategory.key] ?? topCategory.key) : "-"}
            </p>
            <p className="text-xs text-gray-400">
              {topCategory ? `${topCategory.count} integration${topCategory.count !== 1 ? "s" : ""}` : ""}
            </p>
          </div>
          <div className="rounded-xl border border-gray-200 bg-white px-4 py-3">
            <p className="text-xs text-gray-500">Newest detection</p>
            <p className="mt-0.5 text-sm font-semibold text-gray-900 truncate">
              {newest ? newest.name : "-"}
            </p>
            <p className="text-xs text-gray-400">
              {newest ? formatDate(newest.lastDetectedAt) : ""}
            </p>
          </div>
          <div className="rounded-xl border border-gray-200 bg-white px-4 py-3">
            <p className="text-xs text-gray-500">Vendors</p>
            <p className="mt-0.5 text-xl font-semibold text-gray-900">{vendorCount}</p>
            <p className="text-xs text-gray-400">distinct</p>
          </div>
        </div>
      )}

      {/* Category filter pills */}
      {presentCategories.length > 1 && (
        <div className="flex flex-wrap gap-2">
          <button
            onClick={() => setCategoryFilter("all")}
            className={`rounded-full px-3 py-1 text-xs font-medium transition-colors ${
              categoryFilter === "all"
                ? "bg-indigo-600 text-white"
                : "bg-gray-100 text-gray-600 hover:bg-gray-200"
            }`}
          >
            All ({total})
          </button>
          {presentCategories.map((cat) => {
            const Icon = CATEGORY_ICONS[cat] ?? Puzzle;
            return (
              <button
                key={cat}
                onClick={() => setCategoryFilter(cat === categoryFilter ? "all" : cat)}
                className={`flex items-center gap-1.5 rounded-full px-3 py-1 text-xs font-medium transition-colors ${
                  categoryFilter === cat
                    ? "bg-indigo-600 text-white"
                    : "bg-gray-100 text-gray-600 hover:bg-gray-200"
                }`}
              >
                <Icon className="h-3 w-3" />
                {CATEGORY_LABELS[cat] ?? cat} ({byCategory[cat]})
              </button>
            );
          })}
        </div>
      )}

      {total === 0 ? (
        <div className="rounded-xl border border-gray-200 bg-gray-50 py-16 text-center">
          <Puzzle className="mx-auto h-10 w-10 text-gray-300" />
          <p className="mt-3 text-sm font-medium text-gray-500">No integrations detected</p>
          <p className="mt-1 text-xs text-gray-400">
            Integrations are detected automatically as visitors interact with your site.
          </p>
        </div>
      ) : (
        <div className="space-y-8">
          {visibleCategories.map((cat) => {
            const rows = grouped[cat];
            if (!rows?.length) return null;
            const Icon = CATEGORY_ICONS[cat] ?? Puzzle;
            return (
              <section key={cat}>
                <h3 className="mb-3 flex items-center gap-2 text-xs font-semibold uppercase tracking-wider text-gray-400">
                  <Icon className="h-3.5 w-3.5" />
                  {CATEGORY_LABELS[cat] ?? cat}
                  <span className="ml-1 rounded-full bg-gray-100 px-1.5 py-0.5 text-gray-500 normal-case tracking-normal">
                    {rows.length}
                  </span>
                </h3>
                <div className="overflow-hidden rounded-xl border border-gray-200 bg-white">
                  <table className="w-full text-sm">
                    <thead>
                      <tr className="border-b border-gray-100 bg-gray-50 text-left">
                        <th className="px-4 py-3 font-medium text-gray-500">Name</th>
                        <th className="px-4 py-3 font-medium text-gray-500">Vendor</th>
                        <th className="px-4 py-3 font-medium text-gray-500">Pages</th>
                        <th className="px-4 py-3 font-medium text-gray-500">First seen</th>
                        <th className="px-4 py-3 font-medium text-gray-500">Last seen</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-gray-100">
                      {rows.map((integration) => (
                        <tr key={integration.id} className="hover:bg-gray-50">
                          <td className="px-4 py-3">
                            <span
                              className="font-medium text-gray-900"
                              title={integration.description ?? undefined}
                            >
                              {integration.name}
                            </span>
                            {integration.version && (
                              <span className="ml-1.5 text-[11px] text-gray-400 font-mono">
                                v{integration.version}
                              </span>
                            )}
                          </td>
                          <td className="px-4 py-3 text-gray-500">{integration.vendor ?? "-"}</td>
                          <td className="px-4 py-3 text-gray-500">{integration.pageCount}</td>
                          <td className="px-4 py-3 text-gray-400 text-xs">{formatDate(integration.firstDetectedAt)}</td>
                          <td className="px-4 py-3 text-gray-400 text-xs">{formatDate(integration.lastDetectedAt)}</td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </section>
            );
          })}
        </div>
      )}
    </div>
  );
}
