'use client';

import { useCallback, useEffect, useState } from 'react';
import Link from 'next/link';
import { Search, Sparkles, RefreshCw, ImageOff, Bot, User } from 'lucide-react';
import toast from 'react-hot-toast';
import { Card, StatusBadge, Btn, TextInput, money, api, Notice } from '@/components/admin/marketing/ui';
import AdSkeleton from './AdSkeleton';

interface AdRow {
  id: string;
  headline: string;
  primary_text: string;
  image_url: string | null;
  status: string;
  generated_by_type: 'ai' | 'employee';
  publish_error: string | null;
  created_at: string;
  daily_budget: number;
  campaign_name: string;
  product_name: string | null;
  spend: number;
  clicks: number;
  impressions: number;
}

const TABS = [
  { key: 'pending_review', label: 'Pending review' },
  { key: 'approved', label: 'Approved' },
  { key: 'active', label: 'Active' },
  { key: 'paused', label: 'Paused' },
  { key: 'rejected', label: 'Rejected' },
  { key: 'all', label: 'All' },
];

export default function AdsTable({ canCreate, canSync, currency, connected }: {
  canCreate: boolean; canSync: boolean; currency: string | null; connected: boolean;
}) {
  const [status, setStatus] = useState('pending_review');
  const [q, setQ] = useState('');
  const [page, setPage] = useState(1);
  const [rows, setRows] = useState<AdRow[] | null>(null);
  const [totalPages, setTotalPages] = useState(1);
  const [counts, setCounts] = useState<Record<string, number>>({});
  const [syncing, setSyncing] = useState(false);

  const load = useCallback(async () => {
    setRows(null);
    const params = new URLSearchParams({ status, page: String(page), limit: '20', ...(q ? { q } : {}) });
    const [list, c] = await Promise.all([
      api<{ ads: AdRow[]; pagination: { totalPages: number } }>(`/api/ads?${params}`),
      api<Record<string, number>>('/api/ads/counts'),
    ]);
    if (!list.ok) {
      toast.error(list.message);
      setRows([]);
      return;
    }
    setRows(list.data.ads);
    setTotalPages(Math.max(1, list.data.pagination.totalPages));
    if (c.ok) setCounts(c.data);
  }, [status, page, q]);

  useEffect(() => {
    const t = setTimeout(load, q ? 300 : 0);
    return () => clearTimeout(t);
  }, [load, q]);

  const sync = async () => {
    setSyncing(true);
    const res = await api('/api/facebook/insights', { method: 'POST' });
    setSyncing(false);
    if (res.ok) {
      toast.success(res.message);
      load();
    } else toast.error(res.message);
  };

  return (
    <div className="space-y-4">
      {!connected && (
        <Notice tone="warning">
          Facebook isn&apos;t connected yet. You can generate and review ads, but connect your ad account in{' '}
          <Link href="/admin/dashboard/marketing/settings" className="underline font-medium">Marketing Settings</Link> before saving or publishing them.
        </Notice>
      )}

      <Card
        title="Ads"
        subtitle="Every ad waits here for a person (or the autopilot) to approve it before it goes live on Facebook."
        actions={
          <>
            {canSync && <Btn onClick={sync} loading={syncing}><RefreshCw size={15} /> Sync insights</Btn>}
            {canCreate && (
              <Link href="/admin/dashboard/marketing/generate">
                <Btn variant="primary"><Sparkles size={15} /> Generate ad</Btn>
              </Link>
            )}
          </>
        }
      >
        <div className="flex flex-wrap items-center gap-2 mb-4">
          <div className="flex flex-wrap gap-1.5">
            {TABS.map((t) => (
              <button
                key={t.key}
                type="button"
                onClick={() => { setStatus(t.key); setPage(1); }}
                className="rounded-full px-3 py-1.5 text-sm font-medium cursor-pointer"
                style={status === t.key
                  ? { background: 'var(--color-cta)', color: '#fff' }
                  : { background: 'var(--color-surface-alt)', color: 'var(--color-text-secondary)' }}
              >
                {t.label}{counts[t.key] !== undefined ? ` (${counts[t.key]})` : ''}
              </button>
            ))}
          </div>
          <div className="relative ms-auto w-full sm:w-64">
            <Search size={15} className="absolute start-3 top-1/2 -translate-y-1/2" style={{ color: 'var(--color-text-tertiary)' }} />
            <TextInput value={q} onChange={(e) => { setQ(e.target.value); setPage(1); }} placeholder="Search ads…" className="ps-9" />
          </div>
        </div>

        {rows === null ? (
          <AdSkeleton />
        ) : rows.length === 0 ? (
          <p className="py-10 text-center text-sm" style={{ color: 'var(--color-text-secondary)' }}>
            No ads here yet.{canCreate && status === 'pending_review' ? ' Generate one with AI to get started.' : ''}
          </p>
        ) : (
          <ul className="divide-y" style={{ borderColor: 'var(--color-border)' }}>
            {rows.map((ad) => (
              <li key={ad.id}>
                <Link href={`/admin/dashboard/marketing/ads/${ad.id}`} className="flex gap-3 py-3 hover:opacity-90">
                  <div className="h-16 w-16 shrink-0 overflow-hidden rounded-lg" style={{ background: 'var(--color-surface-alt)' }}>
                    {ad.image_url ? (
                      // eslint-disable-next-line @next/next/no-img-element -- external ad image
                      <img src={ad.image_url} alt="" className="h-full w-full object-cover" />
                    ) : (
                      <div className="flex h-full items-center justify-center" style={{ color: 'var(--color-text-tertiary)' }}><ImageOff size={20} /></div>
                    )}
                  </div>
                  <div className="min-w-0 flex-1">
                    <div className="flex flex-wrap items-center gap-2">
                      <p className="truncate font-medium" style={{ color: 'var(--color-text)' }}>{ad.headline}</p>
                      <StatusBadge status={ad.status} />
                      <span className="inline-flex items-center gap-1 text-xs" style={{ color: 'var(--color-text-tertiary)' }}>
                        {ad.generated_by_type === 'ai' ? <><Bot size={12} /> AI</> : <><User size={12} /> Manual</>}
                      </span>
                    </div>
                    <p className="truncate text-sm" style={{ color: 'var(--color-text-secondary)' }}>{ad.primary_text}</p>
                    <p className="text-xs mt-0.5" style={{ color: 'var(--color-text-tertiary)' }}>
                      {ad.campaign_name}{ad.product_name ? ` · ${ad.product_name}` : ''} · {money(ad.daily_budget, currency)}/day
                      {ad.impressions > 0 && ` · ${ad.impressions.toLocaleString()} views · ${ad.clicks.toLocaleString()} clicks · ${money(ad.spend, currency)} spent`}
                    </p>
                    {ad.publish_error && (
                      <p className="text-xs mt-0.5 truncate" style={{ color: 'var(--color-danger)' }}>Publishing failed: {ad.publish_error}</p>
                    )}
                  </div>
                </Link>
              </li>
            ))}
          </ul>
        )}

        {totalPages > 1 && (
          <div className="flex items-center justify-end gap-2 mt-4">
            <Btn onClick={() => setPage((p) => Math.max(1, p - 1))} disabled={page <= 1}>Previous</Btn>
            <span className="text-sm" style={{ color: 'var(--color-text-secondary)' }}>Page {page} of {totalPages}</span>
            <Btn onClick={() => setPage((p) => Math.min(totalPages, p + 1))} disabled={page >= totalPages}>Next</Btn>
          </div>
        )}
      </Card>
    </div>
  );
}
