'use client';

import { useEffect, useState } from 'react';
import { useAuth } from '@/lib/auth-context';
import { adminApiFetch, adminApiOpenPdf } from '@/lib/api';
import { useToast } from '@/lib/toast';
import { TableSkeleton, StatCardSkeleton } from '@/components/Skeletons';
import Modal from '@/components/Modal';
import LineItemBuilder, { LineItem, ProductLookup, computeTotals, toProductsJson } from '@/components/LineItemBuilder';

type QuoteRow = {
  id: number; quoteNo: string; client: { name: string; company: string | null; phone: string };
  projectType: string | null; industry: string | null; site: string | null;
  totalTzs: string; status: string;
};
type ClientLookup = { id: number; name: string; company: string | null; phone: string };

const STATUSES = ['NEW', 'UNDER_REVIEW', 'SITE_VISIT_SCHEDULED', 'QUOTED', 'APPROVED', 'CONVERTED'];
const LABEL: Record<string, string> = {
  NEW: 'New Request', UNDER_REVIEW: 'Under Review', SITE_VISIT_SCHEDULED: 'Site Visit Scheduled',
  QUOTED: 'Quoted', APPROVED: 'Approved', CONVERTED: 'Converted',
};
const emptyForm = { clientId: '', projectType: '', industry: '', site: '', crbRequired: false, siteVisitRequired: false };

export default function QuotesPage() {
  const { accessToken, appSecretProof } = useAuth();
  const { show } = useToast();
  const [quotes, setQuotes] = useState<QuoteRow[]>([]);
  const [funnel, setFunnel] = useState<Record<string, { count: number; totalTzs: number }>>({});
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const [showForm, setShowForm] = useState(false);
  const [clients, setClients] = useState<ClientLookup[]>([]);
  const [products, setProducts] = useState<ProductLookup[]>([]);
  const [form, setForm] = useState(emptyForm);
  const [items, setItems] = useState<LineItem[]>([]);
  const [saving, setSaving] = useState(false);

  async function load() {
    if (!accessToken || !appSecretProof) return;
    setLoading(true);
    try {
      const d = await adminApiFetch('/admin/quotes', accessToken, appSecretProof);
      setQuotes(d.quotes || []);
      setFunnel(d.funnel || {});
    } 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 openForm() {
    setShowForm(true);
    if (!accessToken || !appSecretProof) return;
    try {
      const [c, p] = await Promise.all([
        adminApiFetch('/admin/billing/clients-lookup', accessToken, appSecretProof),
        adminApiFetch('/admin/billing/products-lookup', accessToken, appSecretProof),
      ]);
      setClients(c.clients || []);
      setProducts(p.products || []);
    } catch { show('error', 'Could not load clients/products.'); }
  }

  async function submit(e: React.FormEvent) {
    e.preventDefault();
    if (!accessToken || !appSecretProof || !form.clientId || items.length === 0) return;
    setSaving(true);
    try {
      const { subtotalTzs, vatTzs, totalTzs } = computeTotals(items);
      const d = await adminApiFetch('/admin/quotes', accessToken, appSecretProof, {
        method: 'POST',
        body: JSON.stringify({
          clientId: Number(form.clientId), projectType: form.projectType || undefined,
          industry: form.industry || undefined, site: form.site || undefined,
          crbRequired: form.crbRequired, siteVisitRequired: form.siteVisitRequired,
          productsJson: toProductsJson(items), subtotalTzs, vatTzs, totalTzs,
        }),
      });
      show('success', `${d.quote.quoteNo} created.`);
      setForm(emptyForm);
      setItems([]);
      setShowForm(false);
      load();
    } catch { show('error', 'Could not create that quote.'); }
    finally { setSaving(false); }
  }

  async function advance(id: number, quoteNo: string, status: string) {
    if (!accessToken || !appSecretProof) return;
    try {
      await adminApiFetch(`/admin/quotes/${id}/status`, accessToken, appSecretProof, { method: 'PATCH', body: JSON.stringify({ status }) });
      setQuotes((q) => q.map((row) => row.id === id ? { ...row, status } : row));
      show('success', `${quoteNo} moved to ${LABEL[status]}.`);
    } catch { show('error', 'Could not update that quote.'); }
  }

  async function downloadPdf(id: number) {
    if (!accessToken || !appSecretProof) return;
    try { await adminApiOpenPdf(`/admin/quotes/${id}/pdf`, accessToken, appSecretProof); }
    catch { show('error', 'Could not open the quotation PDF.'); }
  }

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

  return (
    <div className="space-y-4">
      <div className="flex justify-between items-center">
        <h1 className="text-xl font-bold">Quotes &bull; admin.lussavara.co.tz</h1>
        <button onClick={openForm} className="bg-brand-red text-white px-4 py-2 rounded-full text-sm transition-transform hover:scale-[1.03]">+ New Quote</button>
      </div>

      {loading ? <StatCardSkeleton count={4} /> : (
        <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
          {['NEW', 'UNDER_REVIEW', 'QUOTED', 'CONVERTED'].map((s) => (
            <div key={s} className="bg-white p-3 rounded-xl border border-brand-border transition-all hover:shadow-md hover:-translate-y-0.5">
              <p className="text-xs text-gray-500">{LABEL[s]}</p>
              <p className="text-xl font-bold">{funnel[s]?.count ?? 0} &bull; TZS {(funnel[s]?.totalTzs ?? 0).toLocaleString()}</p>
            </div>
          ))}
        </div>
      )}

      {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">Quote No</th><th className="p-3 text-left">Client</th>
              <th className="p-3 text-left">Project</th><th className="p-3 text-left">Total TZS</th>
              <th className="p-3 text-left"></th>
              <th className="p-3 text-left">Status</th>
            </tr></thead>
            <tbody>
              {quotes.map((q) => (
                <tr key={q.id} className="border-t border-brand-border transition-colors hover:bg-brand-bg">
                  <td className="p-3 font-mono font-bold">{q.quoteNo}</td>
                  <td className="p-3">{q.client.name} {q.client.company && `• ${q.client.company}`}<br /><span className="text-gray-400">{q.client.phone}</span></td>
                  <td className="p-3">{q.projectType} &bull; {q.industry} &bull; {q.site}</td>
                  <td className="p-3 font-bold">TZS {Number(q.totalTzs).toLocaleString()}</td>
                  <td className="p-3">
                    <button onClick={() => downloadPdf(q.id)} className="border px-2 py-1 rounded text-[10px] mr-1 transition-colors hover:bg-brand-bg">PDF</button>
                  </td>
                  <td className="p-3">
                    <select value={q.status} onChange={(e) => advance(q.id, q.quoteNo, e.target.value)} className="text-[10px] rounded-full px-2 py-1 bg-yellow-100 text-yellow-800 border-0">
                      {STATUSES.map((s) => <option key={s} value={s}>{LABEL[s]}</option>)}
                    </select>
                  </td>
                </tr>
              ))}
              {quotes.length === 0 && <tr><td colSpan={6} className="p-6 text-center text-gray-400">No quotes yet.</td></tr>}
            </tbody>
          </table>
        </div>
      )}
      <p className="text-[11px] text-gray-400">Workflow: New → Under Review (assigned) → Site Visit Scheduled → Quoted → Approved → Converted to Invoice.</p>

      {showForm && (
        <Modal title="New Quote" onClose={() => setShowForm(false)} wide>
          <form onSubmit={submit} className="space-y-3">
            <div className="grid grid-cols-2 gap-2">
              <select required value={form.clientId} onChange={(e) => setForm({ ...form, clientId: e.target.value })}
                className="border border-brand-border rounded-lg px-2 py-1.5 text-sm">
                <option value="">Select client…</option>
                {clients.map((c) => <option key={c.id} value={c.id}>{c.name} {c.company && `• ${c.company}`}</option>)}
              </select>
              <select value={form.projectType} onChange={(e) => setForm({ ...form, projectType: e.target.value })}
                className="border border-brand-border rounded-lg px-2 py-1.5 text-sm">
                <option value="">Project type…</option>
                <option>New Installation</option><option>Supply Only</option><option>Maintenance</option>
              </select>
              <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-sm" />
              <input placeholder="Site / location" value={form.site} onChange={(e) => setForm({ ...form, site: e.target.value })}
                className="border border-brand-border rounded-lg px-2 py-1.5 text-sm" />
            </div>
            <div className="flex gap-4 text-xs text-gray-600">
              <label className="flex items-center gap-1"><input type="checkbox" checked={form.crbRequired} onChange={(e) => setForm({ ...form, crbRequired: e.target.checked })} /> CRB required</label>
              <label className="flex items-center gap-1"><input type="checkbox" checked={form.siteVisitRequired} onChange={(e) => setForm({ ...form, siteVisitRequired: e.target.checked })} /> Site visit required</label>
            </div>

            <LineItemBuilder items={items} onChange={setItems} products={products} />

            <button disabled={saving || !form.clientId || items.length === 0} className="w-full bg-brand-red text-white text-sm font-semibold py-2.5 rounded-lg disabled:opacity-60">
              {saving ? 'Creating…' : 'Create Quote'}
            </button>
          </form>
        </Modal>
      )}
    </div>
  );
}
