'use client';

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

type ClientRow = {
  id: number; name: string; company: string | null; phone: string; poBox: string | null;
  industry: string | null; tags: string[] | null; lastContactAt: string | null; lastContactChannel: string | null;
  _count: { orders: number; quotes: number };
};

export default function ClientsPage() {
  const { accessToken, appSecretProof } = useAuth();
  const { show } = useToast();
  const [clients, setClients] = useState<ClientRow[]>([]);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [showForm, setShowForm] = useState(false);
  const [form, setForm] = useState({ name: '', company: '', phone: '', poBox: '', industry: '' });

  async function load() {
    if (!accessToken || !appSecretProof) return;
    setLoading(true);
    try {
      const d = await adminApiFetch('/admin/clients', accessToken, appSecretProof);
      setClients(d.clients || []);
    } 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) return;
    setSaving(true);
    try {
      await adminApiFetch('/admin/clients', accessToken, appSecretProof, { method: 'POST', body: JSON.stringify(form) });
      show('success', `${form.name} added to CRM.`);
      setForm({ name: '', company: '', phone: '', poBox: '', industry: '' });
      setShowForm(false);
      load();
    } catch { show('error', 'Could not save that client.'); }
    finally { setSaving(false); }
  }

  async function logContact(id: number, name: string, channel: string) {
    if (!accessToken || !appSecretProof) return;
    try {
      await adminApiFetch(`/admin/clients/${id}/contact`, accessToken, appSecretProof, { method: 'PATCH', body: JSON.stringify({ channel }) });
      show('success', `Logged ${channel} contact with ${name}.`);
      load();
    } catch { show('error', 'Could not log that contact.'); }
  }

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

  return (
    <div className="space-y-4">
      <div className="flex justify-between">
        <h1 className="text-xl font-bold">Clients CRM &bull; admin.lussavara.co.tz</h1>
        <button onClick={() => setShowForm((s) => !s)} className="border px-3 py-1.5 rounded-full text-xs transition-colors hover:bg-brand-bg">{showForm ? 'Close' : '+ Add Client'}</button>
      </div>

      {showForm && (
        <form onSubmit={submit} className="bg-white border border-brand-border rounded-xl p-4 grid grid-cols-2 md:grid-cols-5 gap-2 animate-scaleIn">
          <input required placeholder="Name" value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} className="border border-brand-border rounded-lg px-2 py-1.5 text-xs" />
          <input placeholder="Company" value={form.company} onChange={(e) => setForm({ ...form, company: e.target.value })} className="border border-brand-border rounded-lg px-2 py-1.5 text-xs" />
          <input required placeholder="Phone +255…" value={form.phone} onChange={(e) => setForm({ ...form, phone: e.target.value })} className="border border-brand-border rounded-lg px-2 py-1.5 text-xs" />
          <input placeholder="P.O Box" value={form.poBox} onChange={(e) => setForm({ ...form, poBox: e.target.value })} className="border border-brand-border rounded-lg px-2 py-1.5 text-xs" />
          <input placeholder="Industry" value={form.industry} onChange={(e) => setForm({ ...form, industry: e.target.value })} className="border border-brand-border rounded-lg px-2 py-1.5 text-xs" />
          <button disabled={saving} className="col-span-2 md:col-span-5 bg-brand-charcoal text-white text-xs py-2 rounded-lg disabled:opacity-60">{saving ? 'Saving…' : 'Save Client'}</button>
        </form>
      )}

      {loading ? <TableSkeleton rows={5} cols={5} /> : (
        <div className="bg-white rounded-xl border border-brand-border overflow-hidden">
          <table className="w-full text-xs">
            <thead className="bg-brand-bg"><tr>
              <th className="p-3 text-left">Name &bull; Company &bull; Phone</th><th className="p-3 text-left">Industry &bull; Tags</th>
              <th className="p-3 text-left">Orders / Quotes</th><th className="p-3 text-left">Last Contact</th><th className="p-3 text-left">Actions</th>
            </tr></thead>
            <tbody>
              {clients.map((c) => (
                <tr key={c.id} className="border-t border-brand-border transition-colors hover:bg-brand-bg">
                  <td className="p-3">{c.name} {c.company && `• ${c.company}`}<br /><span className="text-gray-400">{c.phone} • {c.poBox}</span></td>
                  <td className="p-3">{c.industry && <span className="bg-blue-100 text-blue-700 px-2 py-0.5 rounded-full text-[10px] mr-1">{c.industry}</span>}{c.tags?.map((t) => <span key={t} className="bg-brand-red/10 text-brand-red px-2 py-0.5 rounded-full text-[10px] mr-1">{t}</span>)}</td>
                  <td className="p-3">{c._count.orders} orders &bull; {c._count.quotes} quotes</td>
                  <td className="p-3 text-gray-500">{c.lastContactAt ? `${new Date(c.lastContactAt).toLocaleDateString()} • ${c.lastContactChannel}` : '—'}</td>
                  <td className="p-3 space-x-1">
                    <button onClick={() => logContact(c.id, c.name, 'Email')} className="bg-brand-charcoal text-white px-2 py-1 rounded text-[10px] transition-transform hover:scale-105">Email</button>
                    <button onClick={() => logContact(c.id, c.name, 'WhatsApp')} className="bg-brand-red text-white px-2 py-1 rounded text-[10px] transition-transform hover:scale-105">WhatsApp</button>
                  </td>
                </tr>
              ))}
              {clients.length === 0 && <tr><td colSpan={5} className="p-6 text-center text-gray-400">No clients yet.</td></tr>}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}
