'use client';

import { useCallback, useEffect, useState } from 'react';
import toast from 'react-hot-toast';
import { Megaphone, Bot, Library, ShieldCheck, Timer, Plug, Unplug, FlaskConical, Play, RefreshCw } from 'lucide-react';
import { Card, Btn, Field, TextInput, Select, Notice, money, api } from '@/components/admin/marketing/ui';

interface Settings {
  autoApproveEnabled: boolean; autoApproveAfterManualCount: number; maxDailyBudgetPerAd: number; maxActiveAds: number;
  allowedCountries: string[]; autoPauseRoasThreshold: number; autoPauseMinSpend: number;
  aiProvider: 'deepseek' | 'anthropic'; aiModel: string | null; hasAiKey: boolean; hasAdLibraryToken: boolean;
  lastAutopilotRunAt: string | null; lastInsightsSyncAt: string | null;
  manualApprovals: number; envKeys: { deepseek: boolean; anthropic: boolean }; cronConfigured: boolean;
}
interface Connection { fb_ad_account_id: string; fb_page_id: string; account_name: string | null; page_name: string | null; currency: string | null; timezone_name: string | null; token_expires_at: string | null; updated_at: string }

const MODEL_HINT = { deepseek: 'deepseek-chat', anthropic: 'claude-opus-5' };

export default function AutopilotSettingsForm({ appUrl }: { appUrl: string }) {
  const [s, setS] = useState<Settings | null>(null);
  const [conn, setConn] = useState<Connection | null | undefined>(undefined);
  const [busy, setBusy] = useState<string | null>(null);

  const [fb, setFb] = useState({ fb_ad_account_id: '', fb_page_id: '', business_manager_id: '', access_token: '' });
  const [ai, setAi] = useState({ ai_provider: 'deepseek' as 'deepseek' | 'anthropic', ai_model: '', ai_api_key: '' });
  const [libToken, setLibToken] = useState('');
  const [guard, setGuard] = useState({ max_daily_budget_per_ad: 0, max_active_ads: 0, allowed_countries: '', auto_pause_roas_threshold: 0, auto_pause_min_spend: 0, auto_approve_after_manual_count: 50 });

  const load = useCallback(async () => {
    const [a, b] = await Promise.all([api<Settings>('/api/autopilot/settings'), api<Connection | null>('/api/facebook/connection')]);
    if (!a.ok) return toast.error(a.message);
    setS(a.data);
    setConn(b.ok ? b.data : null);
    setAi({ ai_provider: a.data.aiProvider, ai_model: a.data.aiModel ?? '', ai_api_key: '' });
    setGuard({
      max_daily_budget_per_ad: a.data.maxDailyBudgetPerAd, max_active_ads: a.data.maxActiveAds,
      allowed_countries: a.data.allowedCountries.join(', '), auto_pause_roas_threshold: a.data.autoPauseRoasThreshold,
      auto_pause_min_spend: a.data.autoPauseMinSpend, auto_approve_after_manual_count: a.data.autoApproveAfterManualCount,
    });
  }, []);
  useEffect(() => {
    // eslint-disable-next-line react-hooks/set-state-in-effect -- initial fetch
    load();
  }, [load]);

  const run = async (key: string, url: string, init: RequestInit, onOk?: () => void) => {
    setBusy(key);
    const res = await api(url, init);
    setBusy(null);
    if (res.ok) { toast.success(res.message, { duration: 6000 }); onOk?.(); load(); }
    else toast.error(res.message, { duration: 8000 });
    return res;
  };
  const patch = (key: string, body: Record<string, unknown>, onOk?: () => void) =>
    run(key, '/api/autopilot/settings', { method: 'PATCH', body: JSON.stringify(body) }, onOk);

  if (!s || conn === undefined) return <Card><p className="text-sm" style={{ color: 'var(--color-text-secondary)' }}>Loading…</p></Card>;
  const currency = conn?.currency ?? null;
  const keySource = s.hasAiKey ? 'A key is saved' : s.envKeys[ai.ai_provider] ? `Using the ${ai.ai_provider === 'anthropic' ? 'ANTHROPIC_API_KEY' : 'DEEPSEEK_API_KEY'} from .env` : 'No key yet';
  const autoApproveLocked = s.manualApprovals < s.autoApproveAfterManualCount;

  return (
    <div className="space-y-4">
      {/* ── Facebook ─────────────────────────────────────────────── */}
      <Card title={<span className="inline-flex items-center gap-2"><Megaphone size={17} /> Facebook ad account</span>}
        subtitle="Ads are published through the Meta Marketing API with a System User token. The token is stored encrypted.">
        {conn ? (
          <div className="flex flex-wrap items-center gap-3">
            <div className="min-w-0 flex-1 text-sm" style={{ color: 'var(--color-text)' }}>
              <p><b>{conn.account_name}</b> (act_{conn.fb_ad_account_id}) · currency <b>{conn.currency}</b> · {conn.timezone_name}</p>
              <p style={{ color: 'var(--color-text-secondary)' }}>Page: {conn.page_name} ({conn.fb_page_id})
                {conn.token_expires_at ? ` · token expires ${new Date(conn.token_expires_at).toLocaleDateString()}` : ''}</p>
            </div>
            <Btn variant="danger" loading={busy === 'disconnect'} onClick={() => { if (window.confirm('Disconnect Facebook? Live ads keep running on Facebook.')) run('disconnect', '/api/facebook/connection', { method: 'DELETE' }); }}>
              <Unplug size={15} /> Disconnect
            </Btn>
          </div>
        ) : (
          <div className="space-y-3">
            <Notice>
              <ol className="list-decimal ps-5 space-y-0.5">
                <li>In <a className="underline" href="https://business.facebook.com/settings/system-users" target="_blank" rel="noopener noreferrer">Business Settings → System users</a>, add a system user and give it your ad account and page.</li>
                <li>Generate a token for your Meta app with <b>ads_management</b>, <b>ads_read</b>, <b>business_management</b> and <b>pages_read_engagement</b>.</li>
                <li>Paste it below with the ad account id (Ads Manager URL: act_…) and the page id.</li>
              </ol>
            </Notice>
            <div className="grid gap-3 sm:grid-cols-2">
              <Field label="Ad account id"><TextInput value={fb.fb_ad_account_id} onChange={(e) => setFb({ ...fb, fb_ad_account_id: e.target.value })} placeholder="act_1234567890" /></Field>
              <Field label="Facebook page id"><TextInput value={fb.fb_page_id} onChange={(e) => setFb({ ...fb, fb_page_id: e.target.value })} placeholder="1234567890" /></Field>
              <Field label="Business Manager id (optional)"><TextInput value={fb.business_manager_id} onChange={(e) => setFb({ ...fb, business_manager_id: e.target.value })} /></Field>
              <Field label="System User access token"><TextInput type="password" value={fb.access_token} onChange={(e) => setFb({ ...fb, access_token: e.target.value })} placeholder="EAAG…" /></Field>
            </div>
            <div className="flex justify-end">
              <Btn variant="primary" loading={busy === 'connect'} onClick={() => run('connect', '/api/facebook/connection', { method: 'POST', body: JSON.stringify(fb) }, () => setFb({ fb_ad_account_id: '', fb_page_id: '', business_manager_id: '', access_token: '' }))}>
                <Plug size={15} /> Verify & connect
              </Btn>
            </div>
          </div>
        )}
      </Card>

      {/* ── AI ───────────────────────────────────────────────────── */}
      <Card title={<span className="inline-flex items-center gap-2"><Bot size={17} /> AI for writing and analysing ads</span>}
        subtitle="DeepSeek for testing (cheap), Claude for the best copy. The key is stored encrypted; leave it empty to keep the saved one.">
        <div className="grid gap-3 sm:grid-cols-3">
          <Field label="Provider">
            <Select value={ai.ai_provider} onChange={(e) => setAi({ ...ai, ai_provider: e.target.value as 'deepseek' | 'anthropic' })}>
              <option value="deepseek">DeepSeek</option>
              <option value="anthropic">Anthropic (Claude)</option>
            </Select>
          </Field>
          <Field label="Model" hint={`Empty = ${MODEL_HINT[ai.ai_provider]}`}>
            <TextInput value={ai.ai_model} onChange={(e) => setAi({ ...ai, ai_model: e.target.value })} placeholder={MODEL_HINT[ai.ai_provider]} />
          </Field>
          <Field label="API key" hint={keySource}>
            <TextInput type="password" value={ai.ai_api_key} onChange={(e) => setAi({ ...ai, ai_api_key: e.target.value })} placeholder={s.hasAiKey ? '•••••••• (saved)' : 'sk-…'} />
          </Field>
        </div>
        <div className="flex flex-wrap justify-end gap-2 mt-3">
          {s.hasAiKey && <Btn variant="ghost" onClick={() => patch('clearkey', { ai_api_key: '' })}>Remove saved key</Btn>}
          <Btn loading={busy === 'testai'} onClick={() => run('testai', '/api/autopilot/test-ai', { method: 'POST', body: JSON.stringify({ ai_provider: ai.ai_provider, ai_model: ai.ai_model || null, ...(ai.ai_api_key ? { ai_api_key: ai.ai_api_key } : {}) }) })}>
            <FlaskConical size={15} /> Test
          </Btn>
          <Btn variant="primary" loading={busy === 'ai'} onClick={() => patch('ai', { ai_provider: ai.ai_provider, ai_model: ai.ai_model || null, ...(ai.ai_api_key ? { ai_api_key: ai.ai_api_key } : {}) })}>
            Save AI settings
          </Btn>
        </div>
      </Card>

      {/* ── Ad Library ───────────────────────────────────────────── */}
      <Card title={<span className="inline-flex items-center gap-2"><Library size={17} /> Ad Library token (optional)</span>}
        subtitle="For competitor search. Needs a Meta user who completed identity confirmation (facebook.com/id). Without it, the ad account token is used.">
        <div className="flex flex-wrap items-end gap-2">
          <Field label="Access token" className="flex-1 min-w-[240px]" hint={s.hasAdLibraryToken ? 'A token is saved' : 'Not set'}>
            <TextInput type="password" value={libToken} onChange={(e) => setLibToken(e.target.value)} placeholder={s.hasAdLibraryToken ? '•••••••• (saved)' : 'EAAG…'} />
          </Field>
          {s.hasAdLibraryToken && <Btn variant="ghost" onClick={() => patch('libclear', { ad_library_token: '' })}>Remove</Btn>}
          <Btn variant="primary" loading={busy === 'lib'} disabled={!libToken} onClick={() => patch('lib', { ad_library_token: libToken }, () => setLibToken(''))}>Save token</Btn>
        </div>
      </Card>

      {/* ── Guardrails ───────────────────────────────────────────── */}
      <Card title={<span className="inline-flex items-center gap-2"><ShieldCheck size={17} /> Safety limits & autopilot</span>}
        subtitle={`Checked again every time an ad is approved — by a person or the autopilot. Money is in the ad account currency${currency ? ` (${currency})` : ''}.`}>
        <div className="grid gap-3 sm:grid-cols-3">
          <Field label="Max daily budget per ad" hint="0 = no limit"><TextInput type="number" min={0} value={guard.max_daily_budget_per_ad} onChange={(e) => setGuard({ ...guard, max_daily_budget_per_ad: Number(e.target.value) })} /></Field>
          <Field label="Max active ads" hint="0 = no limit"><TextInput type="number" min={0} value={guard.max_active_ads} onChange={(e) => setGuard({ ...guard, max_active_ads: Number(e.target.value) })} /></Field>
          <Field label="Allowed countries" hint="2-letter codes, comma separated; empty = any"><TextInput value={guard.allowed_countries} onChange={(e) => setGuard({ ...guard, allowed_countries: e.target.value.toUpperCase() })} /></Field>
          <Field label="Pause ads with ROAS below" hint="Revenue ÷ spend, from Facebook purchase tracking"><TextInput type="number" step="0.1" min={0} value={guard.auto_pause_roas_threshold} onChange={(e) => setGuard({ ...guard, auto_pause_roas_threshold: Number(e.target.value) })} /></Field>
          <Field label="…after spending at least" hint="0 turns the ROAS rule off"><TextInput type="number" min={0} value={guard.auto_pause_min_spend} onChange={(e) => setGuard({ ...guard, auto_pause_min_spend: Number(e.target.value) })} /></Field>
          <Field label="Manual approvals before auto-approve" hint={`${s.manualApprovals} approved by people so far`}><TextInput type="number" min={0} value={guard.auto_approve_after_manual_count} onChange={(e) => setGuard({ ...guard, auto_approve_after_manual_count: Number(e.target.value) })} /></Field>
        </div>
        <div className="flex justify-end mt-3">
          <Btn variant="primary" loading={busy === 'guard'} onClick={() => patch('guard', {
            ...guard,
            allowed_countries: guard.allowed_countries.split(',').map((c) => c.trim()).filter(Boolean),
          })}>Save limits</Btn>
        </div>

        <div className="mt-5 rounded-xl p-4" style={{ background: 'var(--color-surface-alt)' }}>
          <div className="flex flex-wrap items-center gap-3">
            <div className="min-w-0 flex-1">
              <p className="font-medium" style={{ color: 'var(--color-text)' }}>Auto-approve AI ads: <b>{s.autoApproveEnabled ? 'ON' : 'OFF'}</b></p>
              <p className="text-xs" style={{ color: 'var(--color-text-secondary)' }}>
                {autoApproveLocked && !s.autoApproveEnabled
                  ? `Unlocks after ${s.autoApproveAfterManualCount} ads approved by people (${s.manualApprovals} so far).`
                  : 'When on, each autopilot run publishes AI-written ads waiting for review — only if they pass every limit above.'}
              </p>
            </div>
            <Btn variant={s.autoApproveEnabled ? 'danger' : 'primary'} disabled={!s.autoApproveEnabled && autoApproveLocked} loading={busy === 'toggle'}
              onClick={() => patch('toggle', { auto_approve_enabled: !s.autoApproveEnabled })}>
              {s.autoApproveEnabled ? 'Turn off' : 'Turn on'}
            </Btn>
          </div>
        </div>
      </Card>

      {/* ── Automation ───────────────────────────────────────────── */}
      <Card title={<span className="inline-flex items-center gap-2"><Timer size={17} /> Scheduled jobs</span>}
        subtitle="Insights sync and the autopilot run on a schedule (cron). You can also run them now.">
        <div className="grid gap-3 sm:grid-cols-2 text-sm">
          <div className="rounded-xl p-3" style={{ background: 'var(--color-surface-alt)' }}>
            <p className="font-medium" style={{ color: 'var(--color-text)' }}>Sync insights</p>
            <p className="text-xs" style={{ color: 'var(--color-text-secondary)' }}>Last: {s.lastInsightsSyncAt ? new Date(s.lastInsightsSyncAt).toLocaleString() : 'never'}</p>
            <Btn className="mt-2" loading={busy === 'sync'} disabled={!conn} onClick={() => run('sync', '/api/facebook/insights', { method: 'POST' })}><RefreshCw size={15} /> Sync now</Btn>
          </div>
          <div className="rounded-xl p-3" style={{ background: 'var(--color-surface-alt)' }}>
            <p className="font-medium" style={{ color: 'var(--color-text)' }}>Autopilot cycle</p>
            <p className="text-xs" style={{ color: 'var(--color-text-secondary)' }}>Last: {s.lastAutopilotRunAt ? new Date(s.lastAutopilotRunAt).toLocaleString() : 'never'}</p>
            <Btn className="mt-2" loading={busy === 'run'} onClick={() => run('run', '/api/autopilot/run', { method: 'POST' })}><Play size={15} /> Run now</Btn>
          </div>
        </div>
        <div className="mt-3">
          {s.cronConfigured ? (
            <Notice tone="success">CRON_SECRET is set. Schedule these with the header <code>Authorization: Bearer &lt;CRON_SECRET&gt;</code>:</Notice>
          ) : (
            <Notice tone="warning">Add <code>CRON_SECRET</code> (at least 16 random characters) to .env, then schedule these with the header <code>Authorization: Bearer &lt;CRON_SECRET&gt;</code>:</Notice>
          )}
          <ul className="mt-2 text-xs space-y-1 break-all" style={{ color: 'var(--color-text-secondary)' }}>
            <li><code>GET {appUrl}/api/facebook/insights</code> — every 6 hours</li>
            <li><code>GET {appUrl}/api/autopilot/run</code> — every hour (also syncs the last 3 days first)</li>
          </ul>
        </div>
        {s.maxDailyBudgetPerAd > 0 && (
          <p className="text-xs mt-3" style={{ color: 'var(--color-text-tertiary)' }}>
            Worst case daily spend with current limits: {money(s.maxDailyBudgetPerAd * Math.max(1, s.maxActiveAds), currency)}.
          </p>
        )}
      </Card>
    </div>
  );
}
