'use client';

import { useEffect, useState } from 'react';
import { Send, Users, Loader2, Eye } from 'lucide-react';
import { useAuth } from '@/lib/auth-context';
import { adminApiFetch } from '@/lib/api';
import { useToast } from '@/lib/toast';
import { useLiveRefresh } from '@/lib/realtime';
import AttachmentPicker, { Attachment } from '@/components/AttachmentPicker';
import AiPolishButton from '@/components/AiPolishButton';
import { TableSkeleton } from '@/components/Skeletons';

type Campaign = { id: number; subject: string; status: string; totalCount: number; sentCount: number; failedCount: number; sentAt: string | null; createdAt: string };
type Subscriber = { id: number; email: string; fullName: string | null; company: string | null; isActive: boolean; createdAt: string };

const emptyForm = { subject: '', heading: '', body: '', ctaLabel: '', ctaUrl: '' };

export default function NewsPage() {
  const { accessToken, appSecretProof } = useAuth();
  const { show } = useToast();
  const [active, setActive] = useState(0);
  const [total, setTotal] = useState(0);
  const [mailboxConfigured, setMailboxConfigured] = useState(true);
  const [campaigns, setCampaigns] = useState<Campaign[]>([]);
  const [subscribers, setSubscribers] = useState<Subscriber[]>([]);
  const [loading, setLoading] = useState(true);
  const [form, setForm] = useState(emptyForm);
  const [attachments, setAttachments] = useState<Attachment[]>([]);
  const [sending, setSending] = useState(false);
  const [preview, setPreview] = useState<string | null>(null);
  const [tab, setTab] = useState<'COMPOSE' | 'SUBSCRIBERS'>('COMPOSE');

  async function load() {
    if (!accessToken || !appSecretProof) return;
    try {
      const [s, subs] = await Promise.all([
        adminApiFetch('/admin/news/summary', accessToken, appSecretProof),
        adminApiFetch('/admin/news/subscribers', accessToken, appSecretProof),
      ]);
      setActive(s.active); setTotal(s.total); setMailboxConfigured(s.mailboxConfigured); setCampaigns(s.campaigns || []);
      setSubscribers(subs.subscribers || []);
    } finally { setLoading(false); }
  }
  useEffect(() => { load(); }, [accessToken, appSecretProof]); // eslint-disable-line react-hooks/exhaustive-deps
  useLiveRefresh(['news'], load);

  async function showPreview() {
    if (!accessToken || !appSecretProof) return;
    try { setPreview((await adminApiFetch('/admin/news/preview', accessToken, appSecretProof, { method: 'POST', body: JSON.stringify(form) })).html); }
    catch { show('error', 'Fill in a subject and message first.'); }
  }

  async function send() {
    if (!accessToken || !appSecretProof) return;
    if (!window.confirm(`Send "${form.subject}" to ${active} active subscriber(s) from news@lussavara.co.tz?`)) return;
    setSending(true);
    try {
      await adminApiFetch('/admin/news', accessToken, appSecretProof, { method: 'POST', body: JSON.stringify({ ...form, attachments }) });
      show('success', 'Sending started — watch progress below.');
      setForm(emptyForm); setAttachments([]);
      load();
    } catch (e) {
      const m = (e as Error).message;
      show('error', m === 'NEWS_MAILBOX_NOT_CONFIGURED' ? 'The news@ mailbox has no SMTP login yet.' : m === 'NO_SUBSCRIBERS' ? 'There are no active subscribers yet.' : 'Could not start the campaign.');
    } finally { setSending(false); }
  }

  return (
    <div className="space-y-4">
      <h1 className="text-xl font-bold">News &amp; Updates &bull; sent from news@lussavara.co.tz</h1>

      {!loading && !mailboxConfigured && (
        <div className="bg-yellow-50 border border-yellow-200 rounded-xl p-3 text-xs text-yellow-800">
          The <strong>news@lussavara.co.tz</strong> mailbox has no SMTP login yet — campaigns cannot be sent until <code>SMTP_NEWS_USER</code> / <code>SMTP_NEWS_PASS</code> are set in <code>services/api/.env</code>.
        </div>
      )}

      <div className="grid grid-cols-3 gap-3">
        <div className="bg-white border border-brand-border rounded-xl p-4"><p className="text-xs text-gray-500">Active subscribers</p><p className="text-2xl font-bold">{active}</p></div>
        <div className="bg-white border border-brand-border rounded-xl p-4"><p className="text-xs text-gray-500">Total ever subscribed</p><p className="text-2xl font-bold">{total}</p></div>
        <div className="bg-white border border-brand-border rounded-xl p-4"><p className="text-xs text-gray-500">Campaigns sent</p><p className="text-2xl font-bold">{campaigns.filter((c) => c.status === 'SENT' || c.status === 'PARTIAL').length}</p></div>
      </div>

      <div className="flex gap-1">
        {(['COMPOSE', 'SUBSCRIBERS'] as const).map((t) => (
          <button key={t} onClick={() => setTab(t)} className={`text-xs font-semibold px-3 py-1.5 rounded-lg ${tab === t ? 'bg-brand-charcoal text-white' : 'bg-white border border-brand-border text-gray-600'}`}>
            {t === 'COMPOSE' ? 'Compose' : `Subscribers (${subscribers.length})`}
          </button>
        ))}
      </div>

      {tab === 'COMPOSE' && (
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
          <div className="lg:col-span-2 bg-white border border-brand-border rounded-xl p-4 space-y-3">
            <input required placeholder="Subject line" value={form.subject} onChange={(e) => setForm({ ...form, subject: e.target.value })} className="w-full border border-brand-border rounded-lg px-3 py-2 text-sm" />
            <input placeholder="Big heading (optional — defaults to the subject)" value={form.heading} onChange={(e) => setForm({ ...form, heading: e.target.value })} className="w-full border border-brand-border rounded-lg px-3 py-2 text-sm" />
            <textarea required placeholder="Message — use {{name}} to greet each subscriber by name" value={form.body} onChange={(e) => setForm({ ...form, body: e.target.value })} rows={9} className="w-full border border-brand-border rounded-lg px-3 py-2 text-sm" />
            <AiPolishButton text={form.body} kind="announcement" onAccept={(t) => setForm((f) => ({ ...f, body: t }))} />
            <div className="grid grid-cols-2 gap-2">
              <input placeholder="Button label (optional)" value={form.ctaLabel} onChange={(e) => setForm({ ...form, ctaLabel: e.target.value })} className="border border-brand-border rounded-lg px-3 py-2 text-sm" />
              <input placeholder="Button link (https://…)" value={form.ctaUrl} onChange={(e) => setForm({ ...form, ctaUrl: e.target.value })} className="border border-brand-border rounded-lg px-3 py-2 text-sm" />
            </div>
            <AttachmentPicker attachments={attachments} onChange={setAttachments} />
            <div className="flex gap-2">
              <button type="button" onClick={showPreview} className="flex-1 flex items-center justify-center gap-1.5 border border-brand-border rounded-lg py-2.5 text-sm font-semibold hover:bg-brand-bg"><Eye size={14} /> Preview</button>
              <button type="button" onClick={send} disabled={sending || !mailboxConfigured} className="flex-[2] flex items-center justify-center gap-1.5 bg-brand-red text-white text-sm font-semibold py-2.5 rounded-lg disabled:opacity-60">
                {sending ? <Loader2 size={14} className="animate-spin" /> : <Send size={14} />} Send to {active} subscriber{active === 1 ? '' : 's'}
              </button>
            </div>
          </div>
          <div className="bg-white border border-brand-border rounded-xl p-4">
            <p className="text-sm font-semibold mb-2">Recent Campaigns</p>
            {loading ? <TableSkeleton rows={4} cols={1} /> : (
              <div className="space-y-2 max-h-[420px] overflow-y-auto">
                {campaigns.map((c) => (
                  <div key={c.id} className="text-xs border-t border-brand-border pt-2 first:border-t-0 first:pt-0">
                    <div className="flex justify-between"><p className="font-medium truncate">{c.subject}</p>
                      <span className={`text-[9px] px-1.5 py-0.5 rounded-full shrink-0 ${c.status === 'SENT' ? 'bg-green-100 text-green-700' : c.status === 'SENDING' ? 'bg-blue-100 text-blue-700' : c.status === 'PARTIAL' ? 'bg-yellow-100 text-yellow-700' : 'bg-red-100 text-red-700'}`}>{c.status}</span>
                    </div>
                    <p className="text-gray-400">{c.sentCount}/{c.totalCount} delivered{c.failedCount ? `, ${c.failedCount} failed` : ''}</p>
                  </div>
                ))}
                {campaigns.length === 0 && <p className="text-xs text-gray-400">No campaigns yet.</p>}
              </div>
            )}
          </div>
        </div>
      )}

      {tab === 'SUBSCRIBERS' && (
        <div className="bg-white border border-brand-border rounded-xl overflow-hidden">
          <table className="w-full text-xs">
            <thead className="bg-brand-bg text-gray-500"><tr><th className="text-left p-2">Email</th><th className="text-left p-2">Name</th><th className="text-left p-2">Company</th><th className="text-left p-2">Status</th></tr></thead>
            <tbody>
              {subscribers.map((s) => (
                <tr key={s.id} className="border-t border-brand-border">
                  <td className="p-2">{s.email}</td><td className="p-2">{s.fullName || '—'}</td><td className="p-2">{s.company || '—'}</td>
                  <td className="p-2">{s.isActive ? <span className="text-green-700">Active</span> : <span className="text-gray-400">Unsubscribed</span>}</td>
                </tr>
              ))}
            </tbody>
          </table>
          {subscribers.length === 0 && <p className="text-xs text-gray-400 p-4">No subscribers yet — people join via the website&apos;s newsletter form.</p>}
        </div>
      )}

      {preview && (
        <div className="fixed inset-0 z-40 flex items-center justify-center p-4 bg-black/40" onClick={() => setPreview(null)}>
          <div className="bg-white rounded-2xl shadow-2xl max-w-2xl w-full max-h-[85vh] overflow-y-auto" onClick={(e) => e.stopPropagation()}>
            <div className="flex items-center gap-1.5 p-3 text-xs font-semibold border-b border-brand-border sticky top-0 bg-white"><Users size={13} /> Preview (sample name: Asha)</div>
            <iframe title="preview" srcDoc={preview} className="w-full h-[70vh] border-0" />
          </div>
        </div>
      )}
    </div>
  );
}
