'use client';

import { useCallback, useEffect, useState } from 'react';
import toast from 'react-hot-toast';
import { Search, Plus, ExternalLink, Pencil, Trash2, Library, BookmarkPlus, ListChecks, Users } from 'lucide-react';
import { Card, Btn, Field, TextInput, TextArea, Select, Notice, api } from '@/components/admin/marketing/ui';
import AdSkeleton from '@/components/admin/marketing/ads/AdSkeleton';
import CompetitorAdCard, { type CompetitorAdRow } from './CompetitorAdCard';

interface Competitor { id: string; name: string; fb_page_id: string | null; page_url: string | null; website_url: string | null; notes: string | null; ads: number }
interface LibraryAd {
  libraryAdId: string; pageId: string | null; pageName: string | null; headline: string | null; primaryText: string | null;
  description: string | null; snapshotUrl: string | null; platforms: string[]; startedAt: string | null; endedAt: string | null;
  euReach: number | null; saved: boolean; raw: unknown;
}

type Tab = 'saved' | 'library' | 'manual' | 'competitors';

const EMPTY_MANUAL = {
  competitor_id: '', page_name: '', headline: '', primary_text: '', description: '', cta: '', image_url: '',
  snapshot_url: '', landing_url: '', platforms: '', countries: '', started_at: '', ended_at: '', notes: '',
};
const EMPTY_COMPETITOR = { name: '', fb_page_id: '', page_url: '', website_url: '', notes: '' };

export default function CompetitorsWorkspace({ canCreateAds }: { canCreateAds: boolean }) {
  const [tab, setTab] = useState<Tab>('saved');
  const [competitors, setCompetitors] = useState<Competitor[]>([]);
  const [ads, setAds] = useState<CompetitorAdRow[] | null>(null);
  const [filterCompetitor, setFilterCompetitor] = useState('');
  const [q, setQ] = useState('');

  const loadCompetitors = useCallback(async () => {
    const res = await api<Competitor[]>('/api/competitors');
    if (res.ok) setCompetitors(res.data);
  }, []);
  const loadAds = useCallback(async () => {
    const params = new URLSearchParams({ ...(filterCompetitor ? { competitor_id: filterCompetitor } : {}), ...(q ? { q } : {}) });
    const res = await api<CompetitorAdRow[]>(`/api/competitor-ads?${params}`);
    if (res.ok) setAds(res.data); else { toast.error(res.message); setAds([]); }
  }, [filterCompetitor, q]);

  useEffect(() => {
    // eslint-disable-next-line react-hooks/set-state-in-effect -- initial fetch
    loadCompetitors();
  }, [loadCompetitors]);
  useEffect(() => { const t = setTimeout(loadAds, q ? 300 : 0); return () => clearTimeout(t); }, [loadAds, q]);

  // ── Ad Library search ────────────────────────────────────────────────
  const [lib, setLib] = useState({ q: '', page_ids: '', countries: 'GB', status: 'ACTIVE', ad_type: 'ALL' });
  const [libResults, setLibResults] = useState<LibraryAd[]>([]);
  const [libAfter, setLibAfter] = useState<string | null>(null);
  const [libLoading, setLibLoading] = useState(false);
  const [picked, setPicked] = useState<string[]>([]);
  const [importTo, setImportTo] = useState('');
  const [importing, setImporting] = useState(false);

  const searchLibrary = async (after?: string) => {
    setLibLoading(true);
    const params = new URLSearchParams({
      ...(lib.q ? { q: lib.q } : {}), ...(lib.page_ids ? { page_ids: lib.page_ids } : {}),
      countries: lib.countries, status: lib.status, ad_type: lib.ad_type, ...(after ? { after } : {}),
    });
    const res = await api<{ ads: LibraryAd[]; after: string | null }>(`/api/competitor-ads/library-search?${params}`);
    setLibLoading(false);
    if (!res.ok) return toast.error(res.message, { duration: 8000 });
    setLibResults((prev) => (after ? [...prev, ...res.data.ads] : res.data.ads));
    setLibAfter(res.data.after);
    if (!after) setPicked([]);
    if (!after && res.data.ads.length === 0) toast('No ads found. Remember: ordinary product ads only appear for EU/UK countries.');
  };

  const importPicked = async () => {
    const chosen = libResults.filter((a) => picked.includes(a.libraryAdId));
    if (!chosen.length) return;
    setImporting(true);
    const res = await api('/api/competitor-ads/import', {
      method: 'POST',
      body: JSON.stringify({ competitor_id: importTo || null, countries: lib.countries, ads: chosen }),
    });
    setImporting(false);
    if (!res.ok) return toast.error(res.message);
    toast.success(res.message);
    setLibResults((r) => r.map((a) => (picked.includes(a.libraryAdId) ? { ...a, saved: true } : a)));
    setPicked([]);
    loadAds();
    loadCompetitors();
  };

  // ── Manual ad ────────────────────────────────────────────────────────
  const [manual, setManual] = useState(EMPTY_MANUAL);
  const [savingManual, setSavingManual] = useState(false);
  const saveManual = async () => {
    setSavingManual(true);
    const res = await api('/api/competitor-ads', { method: 'POST', body: JSON.stringify(manual) });
    setSavingManual(false);
    if (!res.ok) return toast.error(res.message);
    toast.success(res.message);
    setManual({ ...EMPTY_MANUAL, competitor_id: manual.competitor_id });
    loadAds();
    loadCompetitors();
    setTab('saved');
  };

  // ── Competitors ──────────────────────────────────────────────────────
  const [compForm, setCompForm] = useState(EMPTY_COMPETITOR);
  const [editingId, setEditingId] = useState<string | null>(null);
  const [savingComp, setSavingComp] = useState(false);
  const saveCompetitor = async () => {
    setSavingComp(true);
    const res = await api(editingId ? `/api/competitors/${editingId}` : '/api/competitors', {
      method: editingId ? 'PATCH' : 'POST', body: JSON.stringify(compForm),
    });
    setSavingComp(false);
    if (!res.ok) return toast.error(res.message);
    toast.success(res.message);
    setCompForm(EMPTY_COMPETITOR);
    setEditingId(null);
    loadCompetitors();
  };
  const removeCompetitor = async (c: Competitor) => {
    if (!window.confirm(`Remove ${c.name}? Their saved ads stay.`)) return;
    const res = await api(`/api/competitors/${c.id}`, { method: 'DELETE' });
    if (res.ok) { toast.success(res.message); loadCompetitors(); } else toast.error(res.message);
  };

  const tabs: Array<{ key: Tab; label: string; icon: React.ReactNode }> = [
    { key: 'saved', label: `Saved ads${ads ? ` (${ads.length})` : ''}`, icon: <ListChecks size={15} /> },
    { key: 'library', label: 'Search Ad Library', icon: <Library size={15} /> },
    { key: 'manual', label: 'Add manually', icon: <BookmarkPlus size={15} /> },
    { key: 'competitors', label: `Competitors (${competitors.length})`, icon: <Users size={15} /> },
  ];

  const competitorSelect = (value: string, onChange: (v: string) => void, emptyLabel = 'No competitor') => (
    <Select value={value} onChange={(e) => onChange(e.target.value)}>
      <option value="">{emptyLabel}</option>
      {competitors.map((c) => <option key={c.id} value={c.id}>{c.name}</option>)}
    </Select>
  );

  return (
    <div className="space-y-4">
      <div className="flex flex-wrap gap-1.5">
        {tabs.map((t) => (
          <button key={t.key} type="button" onClick={() => setTab(t.key)}
            className="inline-flex items-center gap-1.5 rounded-full px-3.5 py-1.5 text-sm font-medium cursor-pointer"
            style={tab === t.key ? { background: 'var(--color-cta)', color: '#fff' } : { background: 'var(--color-surface)', color: 'var(--color-text-secondary)', border: '1px solid var(--color-border)' }}>
            {t.icon}{t.label}
          </button>
        ))}
      </div>

      {tab === 'saved' && (
        <Card title="Saved competitor ads" subtitle="Analyse an ad with AI to see its hook, angle and offer — then turn what works into your own ad.">
          <div className="flex flex-wrap gap-2 mb-4">
            <div className="relative 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)} placeholder="Search saved ads…" className="ps-9" />
            </div>
            <div className="w-full sm:w-56">{competitorSelect(filterCompetitor, setFilterCompetitor, 'All competitors')}</div>
          </div>
          {ads === null ? <AdSkeleton rows={3} /> : ads.length === 0 ? (
            <p className="py-10 text-center text-sm" style={{ color: 'var(--color-text-secondary)' }}>
              No saved ads yet — search the Ad Library or add one by hand.
            </p>
          ) : (
            <div className="grid gap-3 md:grid-cols-2 xl:grid-cols-3">
              {ads.map((ad) => <CompetitorAdCard key={ad.id} ad={ad} onChanged={loadAds} canCreateAds={canCreateAds} />)}
            </div>
          )}
        </Card>
      )}

      {tab === 'library' && (
        <Card title="Search the Meta Ad Library" subtitle="Find what competitors are running and save the interesting ones.">
          <Notice tone="warning">
            Meta&apos;s Ad Library API only returns ordinary product ads that ran in the <b>EU or UK</b> (and political/issue ads everywhere).
            Pick those countries below. For Pakistan and other markets, open{' '}
            <a className="underline" href="https://www.facebook.com/ads/library/?active_status=active&ad_type=all&country=PK" target="_blank" rel="noopener noreferrer">facebook.com/ads/library</a>{' '}
            and use <b>Add manually</b>. The API also needs a Meta account that completed identity confirmation.
          </Notice>
          <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-5 mt-4">
            <Field label="Keywords" className="lg:col-span-2"><TextInput value={lib.q} onChange={(e) => setLib({ ...lib, q: e.target.value })} placeholder="e.g. organic honey" /></Field>
            <Field label="Page ids (optional)" hint="Comma separated">
              <TextInput value={lib.page_ids} onChange={(e) => setLib({ ...lib, page_ids: e.target.value })} placeholder="1234567890" />
            </Field>
            <Field label="Reached countries" hint="e.g. GB, DE, FR">
              <TextInput value={lib.countries} onChange={(e) => setLib({ ...lib, countries: e.target.value.toUpperCase() })} />
            </Field>
            <Field label="Status">
              <Select value={lib.status} onChange={(e) => setLib({ ...lib, status: e.target.value })}>
                <option value="ACTIVE">Running now</option><option value="INACTIVE">Stopped</option><option value="ALL">All</option>
              </Select>
            </Field>
          </div>
          <div className="flex flex-wrap items-center gap-2 mt-3">
            <Select value={lib.ad_type} onChange={(e) => setLib({ ...lib, ad_type: e.target.value })} style={{ width: 'auto' }}>
              <option value="ALL">All ads</option><option value="POLITICAL_AND_ISSUE_ADS">Political / issue ads</option>
            </Select>
            <Btn variant="primary" onClick={() => searchLibrary()} loading={libLoading && !libResults.length}><Search size={15} /> Search</Btn>
          </div>

          {libResults.length > 0 && (
            <>
              <div className="flex flex-wrap items-center gap-2 mt-5 mb-3">
                <span className="text-sm" style={{ color: 'var(--color-text-secondary)' }}>{picked.length} picked</span>
                <div className="w-56">{competitorSelect(importTo, setImportTo, 'Save without a competitor')}</div>
                <Btn variant="primary" onClick={importPicked} loading={importing} disabled={!picked.length}><BookmarkPlus size={15} /> Save picked</Btn>
              </div>
              <div className="grid gap-3 md:grid-cols-2 xl:grid-cols-3">
                {libResults.map((a) => {
                  const on = picked.includes(a.libraryAdId);
                  return (
                    <label key={a.libraryAdId} className="rounded-xl p-3 text-sm flex flex-col gap-1.5 cursor-pointer"
                      style={{ background: 'var(--color-surface-alt)', border: `1px solid ${on ? 'var(--color-cta)' : 'transparent'}`, opacity: a.saved ? 0.6 : 1 }}>
                      <span className="flex items-center gap-2">
                        <input type="checkbox" disabled={a.saved} checked={on}
                          onChange={() => setPicked((p) => (on ? p.filter((x) => x !== a.libraryAdId) : [...p, a.libraryAdId]))} />
                        <b className="truncate" style={{ color: 'var(--color-text)' }}>{a.pageName ?? 'Unknown page'}</b>
                        {a.saved && <span className="text-xs ms-auto" style={{ color: '#047857' }}>saved</span>}
                      </span>
                      <span className="text-xs" style={{ color: 'var(--color-text-tertiary)' }}>
                        {a.startedAt ?? '?'} → {a.endedAt ?? 'running'} · {a.platforms.join(', ')}{a.euReach ? ` · EU reach ${a.euReach.toLocaleString()}` : ''}
                      </span>
                      {a.headline && <span className="font-medium" style={{ color: 'var(--color-text)' }}>{a.headline}</span>}
                      {a.primaryText && <span className="line-clamp-4 whitespace-pre-line" style={{ color: 'var(--color-text-secondary)' }}>{a.primaryText}</span>}
                      {a.snapshotUrl && (
                        <a href={a.snapshotUrl} target="_blank" rel="noopener noreferrer" className="inline-flex items-center gap-1 text-xs underline mt-auto" style={{ color: 'var(--color-text-secondary)' }}>
                          <ExternalLink size={12} /> View in Ad Library
                        </a>
                      )}
                    </label>
                  );
                })}
              </div>
              {libAfter && <div className="flex justify-center mt-4"><Btn onClick={() => searchLibrary(libAfter)} loading={libLoading}>Load more</Btn></div>}
            </>
          )}
        </Card>
      )}

      {tab === 'manual' && (
        <Card title="Save a competitor ad by hand"
          subtitle={<>Open <a className="underline" href="https://www.facebook.com/ads/library/?active_status=active&ad_type=all&country=PK" target="_blank" rel="noopener noreferrer">facebook.com/ads/library</a>, find the ad, and copy its text here. The ad&apos;s “See ad details” link goes in “Ad link”.</>}>
          <div className="grid gap-3 sm:grid-cols-2">
            <Field label="Competitor">{competitorSelect(manual.competitor_id, (v) => setManual({ ...manual, competitor_id: v }))}</Field>
            <Field label="Page name"><TextInput value={manual.page_name} onChange={(e) => setManual({ ...manual, page_name: e.target.value })} /></Field>
            <Field label="Headline" className="sm:col-span-2"><TextInput value={manual.headline} onChange={(e) => setManual({ ...manual, headline: e.target.value })} /></Field>
            <Field label="Ad text" className="sm:col-span-2"><TextArea rows={5} value={manual.primary_text} onChange={(e) => setManual({ ...manual, primary_text: e.target.value })} /></Field>
            <Field label="Description"><TextInput value={manual.description} onChange={(e) => setManual({ ...manual, description: e.target.value })} /></Field>
            <Field label="Button text"><TextInput value={manual.cta} onChange={(e) => setManual({ ...manual, cta: e.target.value })} placeholder="e.g. Shop now" /></Field>
            <Field label="Image URL (optional)"><TextInput value={manual.image_url} onChange={(e) => setManual({ ...manual, image_url: e.target.value })} /></Field>
            <Field label="Ad link (Ad Library)"><TextInput value={manual.snapshot_url} onChange={(e) => setManual({ ...manual, snapshot_url: e.target.value })} /></Field>
            <Field label="Landing page"><TextInput value={manual.landing_url} onChange={(e) => setManual({ ...manual, landing_url: e.target.value })} /></Field>
            <Field label="Platforms"><TextInput value={manual.platforms} onChange={(e) => setManual({ ...manual, platforms: e.target.value })} placeholder="facebook, instagram" /></Field>
            <Field label="Started running"><TextInput type="date" value={manual.started_at} onChange={(e) => setManual({ ...manual, started_at: e.target.value })} /></Field>
            <Field label="Stopped (if ended)"><TextInput type="date" value={manual.ended_at} onChange={(e) => setManual({ ...manual, ended_at: e.target.value })} /></Field>
            <Field label="Your notes" className="sm:col-span-2"><TextArea rows={2} value={manual.notes} onChange={(e) => setManual({ ...manual, notes: e.target.value })} placeholder="What caught your eye?" /></Field>
          </div>
          <div className="flex justify-end mt-4">
            <Btn variant="primary" onClick={saveManual} loading={savingManual}><Plus size={15} /> Save ad</Btn>
          </div>
        </Card>
      )}

      {tab === 'competitors' && (
        <div className="grid gap-4 lg:grid-cols-[1fr_380px]">
          <Card title="Competitors you watch">
            {competitors.length === 0 ? (
              <p className="text-sm" style={{ color: 'var(--color-text-secondary)' }}>None yet — add one on the right.</p>
            ) : (
              <ul className="divide-y" style={{ borderColor: 'var(--color-border)' }}>
                {competitors.map((c) => (
                  <li key={c.id} className="py-3 flex flex-wrap items-center gap-2">
                    <div className="min-w-0 flex-1">
                      <p className="font-medium" style={{ color: 'var(--color-text)' }}>{c.name} <span className="text-xs font-normal" style={{ color: 'var(--color-text-tertiary)' }}>· {c.ads} saved ads</span></p>
                      <p className="text-xs truncate" style={{ color: 'var(--color-text-tertiary)' }}>{[c.fb_page_id && `Page ${c.fb_page_id}`, c.website_url].filter(Boolean).join(' · ') || '—'}</p>
                    </div>
                    {c.fb_page_id && (
                      <Btn onClick={() => { setLib({ ...lib, page_ids: c.fb_page_id!, q: '' }); setTab('library'); }}><Library size={14} /> Their ads</Btn>
                    )}
                    <a href={`https://www.facebook.com/ads/library/?active_status=all&ad_type=all&country=ALL&q=${encodeURIComponent(c.name)}`} target="_blank" rel="noopener noreferrer">
                      <Btn variant="ghost"><ExternalLink size={14} /></Btn>
                    </a>
                    <Btn variant="ghost" onClick={() => { setEditingId(c.id); setCompForm({ name: c.name, fb_page_id: c.fb_page_id ?? '', page_url: c.page_url ?? '', website_url: c.website_url ?? '', notes: c.notes ?? '' }); }}><Pencil size={14} /></Btn>
                    <Btn variant="ghost" onClick={() => removeCompetitor(c)}><Trash2 size={14} /></Btn>
                  </li>
                ))}
              </ul>
            )}
          </Card>
          <Card title={editingId ? 'Edit competitor' : 'Add competitor'}>
            <div className="space-y-3">
              <Field label="Name"><TextInput value={compForm.name} onChange={(e) => setCompForm({ ...compForm, name: e.target.value })} /></Field>
              <Field label="Facebook page id" hint="Page → About → Page transparency. Lets the Ad Library search their page.">
                <TextInput value={compForm.fb_page_id} onChange={(e) => setCompForm({ ...compForm, fb_page_id: e.target.value })} />
              </Field>
              <Field label="Facebook page URL"><TextInput value={compForm.page_url} onChange={(e) => setCompForm({ ...compForm, page_url: e.target.value })} /></Field>
              <Field label="Website"><TextInput value={compForm.website_url} onChange={(e) => setCompForm({ ...compForm, website_url: e.target.value })} /></Field>
              <Field label="Notes"><TextArea rows={2} value={compForm.notes} onChange={(e) => setCompForm({ ...compForm, notes: e.target.value })} /></Field>
              <div className="flex justify-end gap-2">
                {editingId && <Btn onClick={() => { setEditingId(null); setCompForm(EMPTY_COMPETITOR); }}>Cancel</Btn>}
                <Btn variant="primary" onClick={saveCompetitor} loading={savingComp}>{editingId ? 'Save' : 'Add competitor'}</Btn>
              </div>
            </div>
          </Card>
        </div>
      )}
    </div>
  );
}
