import { useState, useMemo } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useAuth } from '../../contexts/AuthContext';
import { AppLayout } from '../../components/layout/AppLayout';
import { LoadingSpinner } from '../../components/ui/LoadingSpinner';
import {
  leadGenApi,
  type AdTemplate,
  type AdCreative,
  type OptimizationRule,
  type OptimizationLog,
  type LeadAttribution,
  type DashboardStats,
} from '../../api/leadGen';
import {
  Target,
  TrendingUp,
  TrendingDown,
  AlertTriangle,
  CheckCircle2,
  Eye,
  DollarSign,
  RefreshCw,
  Search,
  Filter,
  X,
  Plus,
  Zap,
  Palette,
  Settings2,
  BarChart3,
  ZapOff,
  Activity,
  Layers,
  Tag,
  EyeOff,
  MousePointerClick,
  ArrowUpRight,
  ArrowDownRight,
  Info,
  ExternalLink,
} from 'lucide-react';

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

function formatCurrency(value: number | null): string {
  if (value == null) return '—';
  if (Math.abs(value) >= 1_000_000) return `$${(value / 1_000_000).toFixed(1)}M`;
  if (Math.abs(value) >= 1_000) return `$${(value / 1_000).toFixed(1)}K`;
  return `$${value.toFixed(2)}`;
}

function formatNumber(value: number | null): string {
  if (value == null) return '—';
  if (value >= 1_000_000) return `${(value / 1_000_000).toFixed(1)}M`;
  if (value >= 1_000) return `${(value / 1_000).toFixed(1)}K`;
  return value.toLocaleString();
}

function formatPercent(value: number | null): string {
  if (value == null) return '—';
  return `${(value * 100).toFixed(2)}%`;
}

function formatROI(value: number | null): string {
  if (value == null) return '—';
  return `${value.toFixed(1)}%`;
}

function timeAgo(dateStr: string | null | undefined): string {
  if (!dateStr) return '—';
  const now = Date.now();
  const then = new Date(dateStr).getTime();
  const diff = Math.abs(now - then);
  const days = Math.floor(diff / 86400000);
  if (days === 0) return 'today';
  if (days === 1) return 'yesterday';
  if (days < 30) return `${days}d ago`;
  return new Date(dateStr).toLocaleDateString();
}

function statusColor(status: string): string {
  const map: Record<string, string> = {
    ENABLED: 'bg-emerald-100 text-emerald-700',
    ACTIVE: 'bg-emerald-100 text-emerald-700',
    PAUSED: 'bg-amber-100 text-amber-700',
    REMOVED: 'bg-gray-100 text-gray-500',
    success: 'bg-emerald-100 text-emerald-700',
    error: 'bg-red-100 text-red-700',
    lead: 'bg-blue-100 text-blue-700',
    deal: 'bg-emerald-100 text-emerald-700',
    click: 'bg-violet-100 text-violet-700',
  };
  return map[status] || 'bg-gray-100 text-gray-600';
}

function verticalLabel(v: string): string {
  const map: Record<string, string> = {
    hvac: 'HVAC',
    plumbing: 'Plumbing',
    roofing: 'Roofing',
  };
  return map[v.toLowerCase()] || v;
}

function platformLabel(p: string): string {
  const map: Record<string, string> = {
    google_ads: 'Google Ads',
    facebook_ads: 'Facebook Ads',
  };
  return map[p] || p;
}

// ─── Tab Types ────────────────────────────────────────────────────────────

type TabKey = 'overview' | 'creatives' | 'templates' | 'rules' | 'log' | 'attribution';

// ─── Overview Tab ─────────────────────────────────────────────────────────

function OverviewTab({ stats }: { stats: DashboardStats }) {
  const cards = [
    { label: 'Total Campaigns', value: stats.total_campaigns, icon: BarChart3, color: 'text-blue-600 bg-blue-50' },
    { label: 'Active Campaigns', value: stats.active_campaigns, icon: Activity, color: 'text-emerald-600 bg-emerald-50' },
    { label: 'Spend (30d)', value: formatCurrency(stats.total_spend_30d), icon: DollarSign, color: 'text-violet-600 bg-violet-50' },
    { label: 'Leads (30d)', value: formatNumber(stats.total_leads_30d), icon: Target, color: 'text-cyan-600 bg-cyan-50' },
    { label: 'Total Attributions', value: stats.total_attributions, icon: MousePointerClick, color: 'text-amber-600 bg-amber-50' },
    { label: 'Avg Cost / Lead', value: formatCurrency(stats.avg_cost_per_lead), icon: TrendingDown, color: 'text-orange-600 bg-orange-50' },
    { label: 'Total ROI', value: formatROI(stats.total_roi), icon: TrendingUp, color: 'text-green-600 bg-green-50' },
    { label: 'Active Rules', value: stats.active_rules, icon: Zap, color: 'text-indigo-600 bg-indigo-50' },
    { label: 'Creatives', value: stats.total_creatives, icon: Palette, color: 'text-pink-600 bg-pink-50' },
  ];

  return (
    <div className="space-y-6">
      {/* Stats Grid */}
      <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-4">
        {cards.map((card) => (
          <div key={card.label} className="rounded-xl border border-surface-200 bg-white p-4">
            <div className={`inline-flex rounded-lg p-2 mb-2 ${card.color}`}>
              <card.icon className="h-4 w-4" />
            </div>
            <p className="text-xs text-surface-500">{card.label}</p>
            <p className="text-lg font-bold text-surface-900 mt-0.5">{card.value}</p>
          </div>
        ))}
      </div>

      {/* Summary Panels */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        <div className="rounded-xl border border-surface-200 bg-white p-6">
          <h3 className="text-sm font-medium text-surface-500 mb-4 flex items-center gap-2">
            <Target className="h-4 w-4" /> Campaign Health
          </h3>
          <div className="space-y-3">
            <div className="flex justify-between items-center">
              <span className="text-sm text-surface-600">Active Rate</span>
              <span className="font-semibold text-emerald-600">
                {stats.total_campaigns > 0
                  ? `${Math.round(stats.active_campaigns / stats.total_campaigns * 100)}%`
                  : '—'}
              </span>
            </div>
            <div className="flex justify-between items-center">
              <span className="text-sm text-surface-600">Cost Per Lead</span>
              <span className="font-semibold text-blue-600">{formatCurrency(stats.avg_cost_per_lead)}</span>
            </div>
            <div className="flex justify-between items-center">
              <span className="text-sm text-surface-600">30-Day Spend</span>
              <span className="font-semibold text-violet-600">{formatCurrency(stats.total_spend_30d)}</span>
            </div>
          </div>
        </div>

        <div className="rounded-xl border border-surface-200 bg-white p-6">
          <h3 className="text-sm font-medium text-surface-500 mb-4 flex items-center gap-2">
            <Zap className="h-4 w-4" /> Optimization
          </h3>
          <div className="space-y-3">
            <div className="flex justify-between items-center">
              <span className="text-sm text-surface-600">Active Rules</span>
              <span className="font-semibold text-indigo-600">{stats.active_rules}</span>
            </div>
            <div className="flex justify-between items-center">
              <span className="text-sm text-surface-600">Total Creatives</span>
              <span className="font-semibold text-pink-600">{stats.total_creatives}</span>
            </div>
            <div className="flex justify-between items-center">
              <span className="text-sm text-surface-600">Total ROI</span>
              <span className="font-semibold text-green-600">{formatROI(stats.total_roi)}</span>
            </div>
          </div>
        </div>
      </div>

      {/* Quick Info */}
      <div className="rounded-xl border border-surface-200 bg-blue-50 p-6">
        <div className="flex items-start gap-3">
          <Info className="h-5 w-5 text-blue-600 mt-0.5 flex-shrink-0" />
          <div>
            <h4 className="text-sm font-medium text-blue-900 mb-1">Lead Gen Dashboard</h4>
            <p className="text-sm text-blue-700">
              This dashboard tracks your ad creative templates, live campaigns, automated optimization rules, and lead attribution data.
              Use the tabs above to manage creatives, configure rules, and monitor attribution ROI across Google Ads and Facebook Ads.
            </p>
          </div>
        </div>
      </div>
    </div>
  );
}

// ─── Templates Tab ────────────────────────────────────────────────────────

function TemplatesTab() {
  const [search, setSearch] = useState('');
  const [verticalFilter, setVerticalFilter] = useState('');
  const [selectedTemplate, setSelectedTemplate] = useState<AdTemplate | null>(null);

  const { data, isLoading } = useQuery({
    queryKey: ['lead-gen-templates'],
    queryFn: () => leadGenApi.getTemplates(),
    staleTime: 120_000,
  });

  const templates = data?.data?.templates || [];

  const filtered = useMemo(() => {
    return templates.filter(t => {
      if (verticalFilter && t.vertical !== verticalFilter) return false;
      if (search && !t.name.toLowerCase().includes(search.toLowerCase()) && !t.slug.toLowerCase().includes(search.toLowerCase())) return false;
      return true;
    });
  }, [templates, verticalFilter, search]);

  return (
    <div>
      {/* Filters */}
      <div className="flex flex-wrap items-center gap-3 mb-4">
        <div className="relative flex-1 min-w-[200px]">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-surface-400" />
          <input
            type="text"
            placeholder="Search templates..."
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            className="w-full rounded-lg border border-surface-300 bg-white pl-10 pr-3 py-2 text-sm outline-none focus:border-brand-500"
          />
        </div>
        <select
          value={verticalFilter}
          onChange={(e) => setVerticalFilter(e.target.value)}
          className="rounded-lg border border-surface-300 bg-white px-3 py-2 text-sm outline-none focus:border-brand-500"
        >
          <option value="">All Verticals</option>
          <option value="hvac">HVAC</option>
          <option value="plumbing">Plumbing</option>
          <option value="roofing">Roofing</option>
        </select>
      </div>

      {/* Table */}
      {isLoading ? (
        <div className="flex justify-center py-12"><LoadingSpinner /></div>
      ) : (
        <div className="overflow-x-auto rounded-xl border border-surface-200">
          <table className="w-full text-sm">
            <thead>
              <tr className="bg-surface-50">
                <th className="text-left px-4 py-3 font-medium text-surface-500">Template</th>
                <th className="text-left px-4 py-3 font-medium text-surface-500">Vertical</th>
                <th className="text-left px-4 py-3 font-medium text-surface-500">Service</th>
                <th className="text-left px-4 py-3 font-medium text-surface-500">Headline</th>
                <th className="text-left px-4 py-3 font-medium text-surface-500">Platform</th>
                <th className="text-left px-4 py-3 font-medium text-surface-500">Created</th>
              </tr>
            </thead>
            <tbody>
              {filtered.length === 0 ? (
                <tr><td colSpan={6} className="text-center py-8 text-surface-400">No templates found</td></tr>
              ) : (
                filtered.map((t) => (
                  <tr
                    key={t.id}
                    onClick={() => setSelectedTemplate(t)}
                    className="border-t border-surface-100 hover:bg-surface-50 cursor-pointer"
                  >
                    <td className="px-4 py-3 font-medium text-surface-900">{t.name}</td>
                    <td className="px-4 py-3">
                      <span className="inline-block rounded-full bg-surface-100 px-2 py-0.5 text-xs font-semibold text-surface-700">
                        {verticalLabel(t.vertical)}
                      </span>
                    </td>
                    <td className="px-4 py-3 text-surface-500">{t.service_type}</td>
                    <td className="px-4 py-3 text-surface-600 max-w-[250px] truncate">{t.headline_primary}</td>
                    <td className="px-4 py-3 text-surface-500">{platformLabel(t.target_platform)}</td>
                    <td className="px-4 py-3 text-surface-400">{timeAgo(t.created_at)}</td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      )}

      {/* Detail Panel */}
      {selectedTemplate && (
        <div className="fixed inset-0 z-50 flex justify-end" role="dialog" aria-modal="true">
          <div className="absolute inset-0 bg-black/30" onClick={() => setSelectedTemplate(null)} />
          <div className="relative z-10 flex h-full w-full max-w-lg flex-col overflow-y-auto bg-white shadow-xl border-l border-surface-200">
            <div className="flex items-center justify-between border-b border-surface-200 px-6 py-4">
              <div>
                <h2 className="text-lg font-semibold text-surface-900">{selectedTemplate.name}</h2>
                <p className="text-sm text-surface-500">
                  {verticalLabel(selectedTemplate.vertical)} · {selectedTemplate.service_type}
                </p>
              </div>
              <button
                onClick={() => setSelectedTemplate(null)}
                className="rounded-lg p-2 text-surface-400 hover:bg-surface-100 min-h-[44px] min-w-[44px] flex items-center justify-center"
              >
                <X className="h-5 w-5" />
              </button>
            </div>

            <div className="px-6 py-4 space-y-4">
              {/* Headlines */}
              <div>
                <p className="text-xs font-medium text-surface-500 uppercase tracking-wide mb-2">Headline</p>
                <p className="text-sm text-surface-900 font-medium">{selectedTemplate.headline_primary}</p>
                {selectedTemplate.headline_secondary && (
                  <p className="text-sm text-surface-600">{selectedTemplate.headline_secondary}</p>
                )}
              </div>

              {/* Description */}
              <div>
                <p className="text-xs font-medium text-surface-500 uppercase tracking-wide mb-2">Description</p>
                <p className="text-sm text-surface-700">{selectedTemplate.description}</p>
              </div>

              {/* CTA */}
              <div>
                <p className="text-xs font-medium text-surface-500 uppercase tracking-wide mb-2">Call to Action</p>
                <p className="text-sm text-surface-900">{selectedTemplate.call_to_action}</p>
              </div>

              {/* Display URL */}
              {selectedTemplate.display_url && (
                <div>
                  <p className="text-xs font-medium text-surface-500 uppercase tracking-wide mb-2">Display URL</p>
                  <p className="text-sm text-surface-700">{selectedTemplate.display_url}</p>
                </div>
              )}

              {/* Sitelinks */}
              {selectedTemplate.sitelinks && selectedTemplate.sitelinks.length > 0 && (
                <div>
                  <p className="text-xs font-medium text-surface-500 uppercase tracking-wide mb-2">Sitelinks</p>
                  <div className="flex flex-wrap gap-1.5">
                    {selectedTemplate.sitelinks.map((link, i) => (
                      <span key={i} className="inline-block rounded-full bg-blue-50 px-2.5 py-0.5 text-xs text-blue-700">{link}</span>
                    ))}
                  </div>
                </div>
              )}

              {/* Callouts */}
              {selectedTemplate.callouts && selectedTemplate.callouts.length > 0 && (
                <div>
                  <p className="text-xs font-medium text-surface-500 uppercase tracking-wide mb-2">Callouts</p>
                  <div className="flex flex-wrap gap-1.5">
                    {selectedTemplate.callouts.map((co, i) => (
                      <span key={i} className="inline-block rounded-full bg-violet-50 px-2.5 py-0.5 text-xs text-violet-700">{co}</span>
                    ))}
                  </div>
                </div>
              )}

              {/* Platform */}
              <div className="rounded-lg bg-surface-50 p-3">
                <p className="text-xs text-surface-500">Platform</p>
                <p className="text-sm font-medium">{platformLabel(selectedTemplate.target_platform)}</p>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

// ─── Creatives Tab ────────────────────────────────────────────────────────

function CreativesTab({ companyId }: { companyId: string }) {
  const [search, setSearch] = useState('');
  const [verticalFilter, setVerticalFilter] = useState('');

  const { data, isLoading } = useQuery({
    queryKey: ['lead-gen-creatives', companyId],
    queryFn: () => leadGenApi.getCreatives(companyId),
    staleTime: 60_000,
  });

  const creatives = data?.data?.creatives || [];

  const filtered = useMemo(() => {
    return creatives.filter(c => {
      if (verticalFilter && c.vertical !== verticalFilter) return false;
      if (search && !c.headline_primary.toLowerCase().includes(search.toLowerCase())) return false;
      return true;
    });
  }, [creatives, verticalFilter, search]);

  return (
    <div>
      <div className="flex flex-wrap items-center gap-3 mb-4">
        <div className="relative flex-1 min-w-[200px]">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-surface-400" />
          <input
            type="text"
            placeholder="Search creatives..."
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            className="w-full rounded-lg border border-surface-300 bg-white pl-10 pr-3 py-2 text-sm outline-none focus:border-brand-500"
          />
        </div>
        <select
          value={verticalFilter}
          onChange={(e) => setVerticalFilter(e.target.value)}
          className="rounded-lg border border-surface-300 bg-white px-3 py-2 text-sm outline-none focus:border-brand-500"
        >
          <option value="">All Verticals</option>
          <option value="hvac">HVAC</option>
          <option value="plumbing">Plumbing</option>
          <option value="roofing">Roofing</option>
        </select>
      </div>

      {isLoading ? (
        <div className="flex justify-center py-12"><LoadingSpinner /></div>
      ) : (
        <div className="overflow-x-auto rounded-xl border border-surface-200">
          <table className="w-full text-sm">
            <thead>
              <tr className="bg-surface-50">
                <th className="text-left px-4 py-3 font-medium text-surface-500">Headline</th>
                <th className="text-left px-4 py-3 font-medium text-surface-500">Vertical</th>
                <th className="text-left px-4 py-3 font-medium text-surface-500">Service</th>
                <th className="text-left px-4 py-3 font-medium text-surface-500">Platform</th>
                <th className="text-left px-4 py-3 font-medium text-surface-500">Status</th>
                <th className="text-left px-4 py-3 font-medium text-surface-500">Updated</th>
              </tr>
            </thead>
            <tbody>
              {filtered.length === 0 ? (
                <tr><td colSpan={6} className="text-center py-8 text-surface-400">No creatives found</td></tr>
              ) : (
                filtered.map((c) => (
                  <tr key={c.id} className="border-t border-surface-100 hover:bg-surface-50">
                    <td className="px-4 py-3 font-medium text-surface-900 max-w-[250px] truncate">{c.headline_primary}</td>
                    <td className="px-4 py-3">
                      <span className="inline-block rounded-full bg-surface-100 px-2 py-0.5 text-xs font-semibold text-surface-700">
                        {verticalLabel(c.vertical)}
                      </span>
                    </td>
                    <td className="px-4 py-3 text-surface-500">{c.service_type}</td>
                    <td className="px-4 py-3 text-surface-500">{platformLabel(c.target_platform)}</td>
                    <td className="px-4 py-3">
                      <span className={`inline-block rounded-full px-2 py-0.5 text-xs font-semibold ${c.is_active ? 'bg-emerald-100 text-emerald-700' : 'bg-gray-100 text-gray-500'}`}>
                        {c.is_active ? 'Active' : 'Inactive'}
                      </span>
                    </td>
                    <td className="px-4 py-3 text-surface-400">{timeAgo(c.updated_at)}</td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}

// ─── Rules Tab ────────────────────────────────────────────────────────────

function RulesTab({ companyId }: { companyId: string }) {
  const [search, setSearch] = useState('');
  const [statusFilter, setStatusFilter] = useState('');
  const queryClient = useQueryClient();

  const { data, isLoading } = useQuery({
    queryKey: ['lead-gen-rules', companyId],
    queryFn: () => leadGenApi.getRules(companyId),
    staleTime: 60_000,
  });

  const rules = data?.data?.rules || [];

  const toggleRule = useMutation({
    mutationFn: async ({ ruleId, isActive }: { ruleId: string; isActive: boolean }) => {
      await leadGenApi.updateRule(companyId, ruleId, { is_active: !isActive });
    },
    onSuccess: () => queryClient.invalidateQueries({ queryKey: ['lead-gen-rules', companyId] }),
  });

  const runRule = useMutation({
    mutationFn: async (ruleId: string) => leadGenApi.runRule(companyId, ruleId),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['lead-gen-rules', companyId] });
      queryClient.invalidateQueries({ queryKey: ['lead-gen-log', companyId] });
    },
  });

  const filtered = useMemo(() => {
    return rules.filter(r => {
      if (statusFilter === 'active' && !r.is_active) return false;
      if (statusFilter === 'inactive' && r.is_active) return false;
      if (search && !r.name.toLowerCase().includes(search.toLowerCase())) return false;
      return true;
    });
  }, [rules, statusFilter, search]);

  return (
    <div>
      <div className="flex flex-wrap items-center gap-3 mb-4">
        <div className="relative flex-1 min-w-[200px]">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-surface-400" />
          <input
            type="text"
            placeholder="Search rules..."
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            className="w-full rounded-lg border border-surface-300 bg-white pl-10 pr-3 py-2 text-sm outline-none focus:border-brand-500"
          />
        </div>
        <select
          value={statusFilter}
          onChange={(e) => setStatusFilter(e.target.value)}
          className="rounded-lg border border-surface-300 bg-white px-3 py-2 text-sm outline-none focus:border-brand-500"
        >
          <option value="">All Rules</option>
          <option value="active">Active</option>
          <option value="inactive">Inactive</option>
        </select>
      </div>

      {isLoading ? (
        <div className="flex justify-center py-12"><LoadingSpinner /></div>
      ) : (
        <div className="overflow-x-auto rounded-xl border border-surface-200">
          <table className="w-full text-sm">
            <thead>
              <tr className="bg-surface-50">
                <th className="text-left px-4 py-3 font-medium text-surface-500">Rule</th>
                <th className="text-left px-4 py-3 font-medium text-surface-500">Type</th>
                <th className="text-left px-4 py-3 font-medium text-surface-500">Condition</th>
                <th className="text-left px-4 py-3 font-medium text-surface-500">Action</th>
                <th className="text-left px-4 py-3 font-medium text-surface-500">Status</th>
                <th className="text-right px-4 py-3 font-medium text-surface-500">Actions</th>
              </tr>
            </thead>
            <tbody>
              {filtered.length === 0 ? (
                <tr><td colSpan={6} className="text-center py-8 text-surface-400">No rules found</td></tr>
              ) : (
                filtered.map((rule) => (
                  <tr key={rule.id} className="border-t border-surface-100 hover:bg-surface-50">
                    <td className="px-4 py-3 font-medium text-surface-900">{rule.name}</td>
                    <td className="px-4 py-3">
                      <span className="inline-block rounded-full bg-indigo-50 px-2 py-0.5 text-xs font-semibold text-indigo-700">
                        {rule.rule_type}
                      </span>
                    </td>
                    <td className="px-4 py-3 text-surface-500 max-w-[200px] truncate">
                      {rule.condition_field} {rule.condition_operator} {rule.condition_value ?? '—'}
                    </td>
                    <td className="px-4 py-3 text-surface-500">
                      {rule.action_type}{rule.action_value ? ` ${rule.action_value}` : ''}
                    </td>
                    <td className="px-4 py-3">
                      <span className={`inline-block rounded-full px-2 py-0.5 text-xs font-semibold ${rule.is_active ? 'bg-emerald-100 text-emerald-700' : 'bg-gray-100 text-gray-500'}`}>
                        {rule.is_active ? 'Active' : 'Inactive'}
                      </span>
                    </td>
                    <td className="px-4 py-3 text-right">
                      <div className="flex items-center justify-end gap-1">
                        <button
                          onClick={() => runRule.mutate(rule.id)}
                          disabled={runRule.isPending || !rule.is_active}
                          className="inline-flex items-center gap-1 rounded-lg px-2 py-1 text-xs font-medium text-indigo-600 hover:bg-indigo-50 disabled:opacity-40 disabled:cursor-not-allowed min-h-[32px]"
                          title="Run rule now"
                        >
                          {runRule.isPending ? <RefreshCw className="h-3 w-3 animate-spin" /> : <Zap className="h-3 w-3" />}
                          Run
                        </button>
                        <button
                          onClick={() => toggleRule.mutate({ ruleId: rule.id, isActive: rule.is_active })}
                          disabled={toggleRule.isPending}
                          className={`inline-flex items-center gap-1 rounded-lg px-2 py-1 text-xs font-medium min-h-[32px] disabled:opacity-40 ${
                            rule.is_active
                              ? 'text-amber-600 hover:bg-amber-50'
                              : 'text-emerald-600 hover:bg-emerald-50'
                          }`}
                          title={rule.is_active ? 'Deactivate' : 'Activate'}
                        >
                          {rule.is_active ? <ZapOff className="h-3 w-3" /> : <Zap className="h-3 w-3" />}
                          {rule.is_active ? 'Off' : 'On'}
                        </button>
                      </div>
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}

// ─── Log Tab ──────────────────────────────────────────────────────────────

function LogTab({ companyId }: { companyId: string }) {
  const [sourceFilter, setSourceFilter] = useState('');

  const { data, isLoading } = useQuery({
    queryKey: ['lead-gen-log', companyId],
    queryFn: () => leadGenApi.getOptimizationLog(companyId, { limit: 100 }),
    staleTime: 60_000,
  });

  const logs = data?.data?.logs || [];

  const filtered = useMemo(() => {
    if (!sourceFilter) return logs;
    return logs.filter(l => l.source_service === sourceFilter);
  }, [logs, sourceFilter]);

  return (
    <div>
      <div className="flex flex-wrap items-center gap-3 mb-4">
        <select
          value={sourceFilter}
          onChange={(e) => setSourceFilter(e.target.value)}
          className="rounded-lg border border-surface-300 bg-white px-3 py-2 text-sm outline-none focus:border-brand-500"
        >
          <option value="">All Sources</option>
          <option value="google_ads">Google Ads</option>
          <option value="facebook_ads">Facebook Ads</option>
        </select>
      </div>

      {isLoading ? (
        <div className="flex justify-center py-12"><LoadingSpinner /></div>
      ) : (
        <div className="overflow-x-auto rounded-xl border border-surface-200">
          <table className="w-full text-sm">
            <thead>
              <tr className="bg-surface-50">
                <th className="text-left px-4 py-3 font-medium text-surface-500">Target</th>
                <th className="text-left px-4 py-3 font-medium text-surface-500">Action</th>
                <th className="text-left px-4 py-3 font-medium text-surface-500">Source</th>
                <th className="text-left px-4 py-3 font-medium text-surface-500">Reason</th>
                <th className="text-left px-4 py-3 font-medium text-surface-500">Status</th>
                <th className="text-left px-4 py-3 font-medium text-surface-500">When</th>
              </tr>
            </thead>
            <tbody>
              {filtered.length === 0 ? (
                <tr><td colSpan={6} className="text-center py-8 text-surface-400">No optimization logs</td></tr>
              ) : (
                filtered.map((log) => (
                  <tr key={log.id} className="border-t border-surface-100 hover:bg-surface-50">
                    <td className="px-4 py-3 font-medium text-surface-900 max-w-[200px] truncate">{log.target_id}</td>
                    <td className="px-4 py-3">
                      <span className={`inline-block rounded-full px-2 py-0.5 text-xs font-semibold ${
                        log.action === 'pause' ? 'bg-amber-100 text-amber-700' :
                        log.action === 'delete' ? 'bg-red-100 text-red-700' :
                        log.action === 'scaled' ? 'bg-emerald-100 text-emerald-700' :
                        log.action === 'rebudgeted' ? 'bg-blue-100 text-blue-700' :
                        'bg-gray-100 text-gray-600'
                      }`}>
                        {log.action}
                      </span>
                    </td>
                    <td className="px-4 py-3 text-surface-500">{platformLabel(log.source_service)}</td>
                    <td className="px-4 py-3 text-surface-500 max-w-[200px] truncate">{log.reason || '—'}</td>
                    <td className="px-4 py-3">
                      <span className={`inline-block rounded-full px-2 py-0.5 text-xs font-semibold ${
                        log.previous_value ? 'bg-emerald-100 text-emerald-700' : 'bg-gray-100 text-gray-500'
                      }`}>
                        {log.previous_value ? 'Applied' : 'Pending'}
                      </span>
                    </td>
                    <td className="px-4 py-3 text-surface-400">{timeAgo(log.created_at)}</td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}

// ─── Attribution Tab ──────────────────────────────────────────────────────

function AttributionTab({ companyId }: { companyId: string }) {
  const [sourceFilter, setSourceFilter] = useState('');
  const [statusFilter, setStatusFilter] = useState('');

  const { data, isLoading } = useQuery({
    queryKey: ['lead-gen-attribution', companyId, sourceFilter, statusFilter],
    queryFn: () => leadGenApi.getAttributions(companyId, {
      source: sourceFilter || undefined,
      status: statusFilter || undefined,
    }),
    staleTime: 60_000,
  });

  const attributions = data?.data?.attributions || [];

  const totalValue = useMemo(() => attributions.reduce((sum, a) => sum + (a.lead_value || 0), 0), [attributions]);
  const avgROI = useMemo(() => {
    const withRoi = attributions.filter(a => a.estimated_roi != null);
    if (withRoi.length === 0) return 0;
    return withRoi.reduce((sum, a) => sum + (a.estimated_roi || 0), 0) / withRoi.length;
  }, [attributions]);

  return (
    <div>
      {/* Summary */}
      <div className="grid grid-cols-2 md:grid-cols-3 gap-4 mb-4">
        <div className="rounded-xl border border-surface-200 bg-white p-4">
          <p className="text-xs text-surface-500">Total Attributions</p>
          <p className="text-lg font-bold text-surface-900 mt-0.5">{attributions.length}</p>
        </div>
        <div className="rounded-xl border border-surface-200 bg-white p-4">
          <p className="text-xs text-surface-500">Total Value</p>
          <p className="text-lg font-bold text-emerald-600 mt-0.5">{formatCurrency(totalValue)}</p>
        </div>
        <div className="rounded-xl border border-surface-200 bg-white p-4">
          <p className="text-xs text-surface-500">Avg ROI</p>
          <p className="text-lg font-bold text-blue-600 mt-0.5">{formatROI(avgROI)}</p>
        </div>
      </div>

      {/* Filters */}
      <div className="flex flex-wrap items-center gap-3 mb-4">
        <select
          value={sourceFilter}
          onChange={(e) => setSourceFilter(e.target.value)}
          className="rounded-lg border border-surface-300 bg-white px-3 py-2 text-sm outline-none focus:border-brand-500"
        >
          <option value="">All Sources</option>
          <option value="google_ads">Google Ads</option>
          <option value="facebook_ads">Facebook Ads</option>
          <option value="web_form">Web Form</option>
          <option value="phone_call">Phone Call</option>
        </select>
        <select
          value={statusFilter}
          onChange={(e) => setStatusFilter(e.target.value)}
          className="rounded-lg border border-surface-300 bg-white px-3 py-2 text-sm outline-none focus:border-brand-500"
        >
          <option value="">All Statuses</option>
          <option value="lead">Lead</option>
          <option value="deal">Deal</option>
          <option value="click">Click</option>
        </select>
      </div>

      {/* Table */}
      {isLoading ? (
        <div className="flex justify-center py-12"><LoadingSpinner /></div>
      ) : (
        <div className="overflow-x-auto rounded-xl border border-surface-200">
          <table className="w-full text-sm">
            <thead>
              <tr className="bg-surface-50">
                <th className="text-left px-4 py-3 font-medium text-surface-500">Lead ID</th>
                <th className="text-left px-4 py-3 font-medium text-surface-500">Source</th>
                <th className="text-left px-4 py-3 font-medium text-surface-500">Campaign</th>
                <th className="text-left px-4 py-3 font-medium text-surface-500">UTM</th>
                <th className="text-right px-4 py-3 font-medium text-surface-500">Value</th>
                <th className="text-right px-4 py-3 font-medium text-surface-500">ROI</th>
                <th className="text-left px-4 py-3 font-medium text-surface-500">Status</th>
                <th className="text-left px-4 py-3 font-medium text-surface-500">When</th>
              </tr>
            </thead>
            <tbody>
              {attributions.length === 0 ? (
                <tr><td colSpan={8} className="text-center py-8 text-surface-400">No attributions found</td></tr>
              ) : (
                attributions.map((a) => (
                  <tr key={a.id} className="border-t border-surface-100 hover:bg-surface-50">
                    <td className="px-4 py-3 font-medium text-surface-900 max-w-[120px] truncate">{a.external_lead_id}</td>
                    <td className="px-4 py-3 text-surface-500">{platformLabel(a.source_service)}</td>
                    <td className="px-4 py-3 text-surface-600 max-w-[150px] truncate">{a.utm_campaign || '—'}</td>
                    <td className="px-4 py-3 text-surface-400 text-xs">{a.utm_source || '—'}</td>
                    <td className="px-4 py-3 text-right font-medium text-emerald-600">{formatCurrency(a.lead_value)}</td>
                    <td className="px-4 py-3 text-right text-surface-500">{formatROI(a.estimated_roi)}</td>
                    <td className="px-4 py-3">
                      <span className={`inline-block rounded-full px-2 py-0.5 text-xs font-semibold ${statusColor(a.lead_status)}`}>
                        {a.lead_status}
                      </span>
                    </td>
                    <td className="px-4 py-3 text-surface-400">{timeAgo(a.created_at)}</td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}

// ─── Main Page ────────────────────────────────────────────────────────────

export function LeadGenDashboardPage() {
  const { user } = useAuth();
  const companyId = user?.companyId || '';

  const [activeTab, setActiveTab] = useState<TabKey>('overview');

  const { data, isLoading } = useQuery({
    queryKey: ['lead-gen-dashboard', companyId],
    queryFn: () => leadGenApi.getDashboard(companyId),
    staleTime: 60_000,
    enabled: !!companyId,
  });

  const stats = data?.data || {
    total_campaigns: 0,
    active_campaigns: 0,
    total_spend_30d: 0,
    total_leads_30d: 0,
    total_attributions: 0,
    avg_cost_per_lead: 0,
    total_roi: 0,
    active_rules: 0,
    total_creatives: 0,
  };

  const tabs: { key: TabKey; label: string; icon: React.ElementType }[] = [
    { key: 'overview', label: 'Overview', icon: BarChart3 },
    { key: 'templates', label: 'Templates', icon: Layers },
    { key: 'creatives', label: 'Creatives', icon: Palette },
    { key: 'rules', label: 'Rules', icon: Settings2 },
    { key: 'log', label: 'Log', icon: Activity },
    { key: 'attribution', label: 'Attribution', icon: Target },
  ];

  const renderTab = () => {
    switch (activeTab) {
      case 'overview':
        return <OverviewTab stats={stats} />;
      case 'templates':
        return <TemplatesTab />;
      case 'creatives':
        return <CreativesTab companyId={companyId} />;
      case 'rules':
        return <RulesTab companyId={companyId} />;
      case 'log':
        return <LogTab companyId={companyId} />;
      case 'attribution':
        return <AttributionTab companyId={companyId} />;
      default:
        return <OverviewTab stats={stats} />;
    }
  };

  return (
    <AppLayout title="Lead Gen">
      <div className="space-y-6">
        {/* Header */}
        <div>
          <h1 className="text-xl font-semibold text-surface-900">Lead Generation</h1>
          <p className="text-sm text-surface-500 mt-1">
            Manage ad templates, creatives, optimization rules, and lead attribution.
          </p>
        </div>

        {/* Tabs */}
        <div className="border-b border-surface-200">
          <div className="flex overflow-x-auto scrollbar-hide">
            {tabs.map((tab) => (
              <button
                key={tab.key}
                onClick={() => setActiveTab(tab.key)}
                className={`flex items-center gap-2 px-4 py-3 text-sm font-medium border-b-2 transition-colors whitespace-nowrap min-h-[48px] ${
                  activeTab === tab.key
                    ? 'border-brand-500 text-brand-700'
                    : 'border-transparent text-surface-500 hover:text-surface-700 hover:border-surface-300'
                }`}
              >
                <tab.icon className="h-4 w-4" />
                {tab.label}
              </button>
            ))}
          </div>
        </div>

        {/* Content */}
        {isLoading && activeTab === 'overview' ? (
          <div className="flex justify-center py-12"><LoadingSpinner /></div>
        ) : (
          renderTab()
        )}
      </div>
    </AppLayout>
  );
}
