'use client';

import { useEffect, useState } from 'react';
import { useAuth } from '@/lib/auth-context';
import { adminApiFetch } from '@/lib/api';
import { useToast } from '@/lib/toast';
import Modal from '@/components/Modal';
import { TableSkeleton } from '@/components/Skeletons';

type Template = { id: string; name: string; status: string };

export default function WhatsAppManagerPage() {
  const { accessToken, appSecretProof } = useAuth();
  const { show } = useToast();
  const [templates, setTemplates] = useState<Template[]>([]);
  const [numbers, setNumbers] = useState<{ label: string; phone: string }[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [showAdd, setShowAdd] = useState(false);
  const [name, setName] = useState('');
  const [saving, setSaving] = useState(false);

  async function load() {
    if (!accessToken || !appSecretProof) return;
    setLoading(true);
    try {
      const [t, n] = await Promise.all([
        adminApiFetch('/admin/whatsapp/templates', accessToken, appSecretProof),
        adminApiFetch('/admin/whatsapp/phone-numbers', accessToken, appSecretProof),
      ]);
      setTemplates(t.templates || []); setNumbers(n.numbers || []);
    } catch { setError('You do not have permission to view this page.'); }
    finally { setLoading(false); }
  }
  useEffect(() => { load(); }, [accessToken, appSecretProof]); // eslint-disable-line react-hooks/exhaustive-deps

  async function submit(e: React.FormEvent) {
    e.preventDefault();
    if (!accessToken || !appSecretProof || !name.trim()) return;
    setSaving(true);
    try {
      await adminApiFetch('/admin/whatsapp/templates', accessToken, appSecretProof, { method: 'POST', body: JSON.stringify({ name }) });
      show('success', `"${name}" submitted for WhatsApp approval.`);
      setName('');
      setShowAdd(false);
      load();
    } catch { show('error', 'Could not submit that template.'); }
    finally { setSaving(false); }
  }

  if (error) return <p className="text-sm text-brand-red">{error}</p>;

  return (
    <div className="space-y-6">
      <div className="flex justify-between">
        <h1 className="text-lg font-bold">WhatsApp Manager</h1>
        <button onClick={() => setShowAdd(true)} className="bg-brand-red text-white px-4 py-2 rounded-lg text-sm transition-transform hover:scale-[1.03]">+ Add Template</button>
      </div>

      {loading ? <TableSkeleton rows={3} cols={2} /> : (
        <>
          <div className="bg-white border border-brand-border rounded-xl p-4">
            <h2 className="text-sm font-semibold mb-2">Phone Numbers</h2>
            {numbers.map((n) => (
              <p key={n.phone} className="text-xs text-gray-600">{n.label}: {n.phone}</p>
            ))}
          </div>

          <div className="bg-white border border-brand-border rounded-xl p-4">
            <h2 className="text-sm font-semibold mb-2">Message Templates</h2>
            {templates.length === 0 && <p className="text-xs text-gray-400">No templates yet — add one to submit for WhatsApp approval.</p>}
            {templates.map((t) => <p key={t.id} className="text-xs text-gray-600">{t.name} · {t.status}</p>)}
          </div>
        </>
      )}

      {showAdd && (
        <Modal title="Add WhatsApp Template" onClose={() => setShowAdd(false)}>
          <form onSubmit={submit} className="space-y-3">
            <div>
              <label className="text-xs font-medium text-gray-600">Template name</label>
              <input required autoFocus value={name} onChange={(e) => setName(e.target.value)}
                className="mt-1 w-full border border-brand-border rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-brand-red"
                placeholder="order_confirmation" />
            </div>
            <p className="text-[11px] text-gray-400">Submitted to WhatsApp Cloud API for approval — actual submission needs your WhatsApp Business credentials wired server-side.</p>
            <button disabled={saving} className="w-full bg-brand-red text-white text-sm font-semibold py-2.5 rounded-lg disabled:opacity-60">
              {saving ? 'Submitting…' : 'Submit for Approval'}
            </button>
          </form>
        </Modal>
      )}
    </div>
  );
}
