'use client';

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

type ContractRow = {
  id: number; contractNo: string; title: string; status: string; equipmentType: string | null;
  siteAddress: string | null; intervalMonths: number; nextDueDate: string;
  client: { name: string; company: string | null };
};
type ClientLookup = { id: number; name: string; company: string | null; phone: string };
type ProjectLookup = { id: number; projectNo: string; title: string; siteAddress: string | null; client: { id: number; name: string; company: string | null } };

const LABEL: Record<string, string> = { ACTIVE: 'Active', PAUSED: 'Paused', EXPIRED: 'Expired', CANCELLED: 'Cancelled' };
const emptyForm = { clientId: '', projectId: '', title: '', equipmentType: '', siteAddress: '', intervalMonths: '12', valueTzs: '', startDate: '' };

function dueBadge(nextDueDate: string, status: string) {
  if (status !== 'ACTIVE') return 'bg-gray-100 text-gray-500';
  const days = (new Date(nextDueDate).getTime() - Date.now()) / 86400000;
  if (days < 0) return 'bg-red-100 text-red-700';
  if (days <= 30) return 'bg-amber-100 text-amber-700';
  return 'bg-emerald-100 text-emerald-700';
}

export default function MaintenancePage() {
  const { accessToken, appSecretProof } = useAuth();
  const { show } = useToast();
  const [contracts, setContracts] = useState<ContractRow[]>([]);
  const [funnel, setFunnel] = useState<Record<string, number>>({});
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const [showForm, setShowForm] = useState(false);
  const [clients, setClients] = useState<ClientLookup[]>([]);
  const [projects, setProjects] = useState<ProjectLookup[]>([]);
  const [form, setForm] = useState(emptyForm);
  const [saving, setSaving] = useState(false);

  async function load() {
    if (!accessToken || !appSecretProof) return;
    setLoading(true);
    try {
      const d = await adminApiFetch('/admin/maintenance', accessToken, appSecretProof);
      setContracts(d.contracts || []);
      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/maintenance/lookups/clients', accessToken, appSecretProof),
        adminApiFetch('/admin/maintenance/lookups/projects', accessToken, appSecretProof),
      ]);
      setClients(c.clients || []);
      setProjects(p.projects || []);
    } catch { show('error', 'Could not load clients/projects.'); }
  }

  function pickProject(projectId: string) {
    const p = projects.find((x) => String(x.id) === projectId);
    setForm((f) => ({
      ...f, projectId,
      clientId: p ? String(p.client.id) : f.clientId,
      siteAddress: p?.siteAddress || f.siteAddress,
      title: f.title || (p ? `Maintenance — ${p.title}` : f.title),
    }));
  }

  async function submit(e: React.FormEvent) {
    e.preventDefault();
    if (!accessToken || !appSecretProof || !form.clientId || !form.title) return;
    setSaving(true);
    try {
      const d = await adminApiFetch('/admin/maintenance', accessToken, appSecretProof, {
        method: 'POST',
        body: JSON.stringify({
          clientId: Number(form.clientId), title: form.title,
          equipmentType: form.equipmentType || undefined, siteAddress: form.siteAddress || undefined,
          intervalMonths: Number(form.intervalMonths) || 12,
          valueTzs: form.valueTzs ? Number(form.valueTzs) : undefined,
          projectId: form.projectId ? Number(form.projectId) : undefined,
          startDate: form.startDate || undefined,
        }),
      });
      show('success', `${d.contract.contractNo} created.`);
      setForm(emptyForm);
      setShowForm(false);
      load();
    } catch { show('error', 'Could not create that contract.'); }
    finally { setSaving(false); }
  }

  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">Maintenance Contracts &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 Contract</button>
      </div>

      {loading ? <StatCardSkeleton count={5} /> : (
        <div className="grid grid-cols-2 md:grid-cols-5 gap-3">
          <div className="bg-white border border-brand-border rounded-xl p-4"><p className="text-[10px] uppercase text-gray-400">Active</p><p className="text-lg font-bold">{funnel.ACTIVE ?? 0}</p></div>
          <div className="bg-red-50 border border-red-200 rounded-xl p-4"><p className="text-[10px] uppercase text-red-500">Overdue</p><p className="text-lg font-bold text-red-700">{funnel.OVERDUE ?? 0}</p></div>
          <div className="bg-amber-50 border border-amber-200 rounded-xl p-4"><p className="text-[10px] uppercase text-amber-600">Due within 30d</p><p className="text-lg font-bold text-amber-700">{funnel.DUE_SOON ?? 0}</p></div>
          <div className="bg-white border border-brand-border rounded-xl p-4"><p className="text-[10px] uppercase text-gray-400">Paused</p><p className="text-lg font-bold">{funnel.PAUSED ?? 0}</p></div>
          <div className="bg-white border border-brand-border rounded-xl p-4"><p className="text-[10px] uppercase text-gray-400">Expired</p><p className="text-lg font-bold">{funnel.EXPIRED ?? 0}</p></div>
        </div>
      )}

      {loading ? <TableSkeleton rows={6} cols={6} /> : (
        <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">Contract No &bull; Title</th><th className="p-3 text-left">Client</th>
              <th className="p-3 text-left">Equipment / Site</th><th className="p-3 text-left">Interval</th>
              <th className="p-3 text-left">Next Due</th><th className="p-3 text-left">Status</th>
            </tr></thead>
            <tbody>
              {contracts.map((c) => (
                <tr key={c.id} className="border-t border-brand-border transition-colors hover:bg-brand-bg">
                  <td className="p-3"><Link href={`/maintenance/${c.id}`} className="font-semibold hover:text-brand-red">{c.contractNo}</Link><br /><span className="text-gray-400">{c.title}</span></td>
                  <td className="p-3">{c.client.name}{c.client.company && ` • ${c.client.company}`}</td>
                  <td className="p-3">{c.equipmentType || '—'}<br /><span className="text-gray-400">{c.siteAddress || '—'}</span></td>
                  <td className="p-3">Every {c.intervalMonths}mo</td>
                  <td className="p-3"><span className={`px-2 py-0.5 rounded-full text-[10px] ${dueBadge(c.nextDueDate, c.status)}`}>{new Date(c.nextDueDate).toLocaleDateString()}</span></td>
                  <td className="p-3 text-gray-500">{LABEL[c.status]}</td>
                </tr>
              ))}
              {contracts.length === 0 && <tr><td colSpan={6} className="p-6 text-center text-gray-400">No maintenance contracts yet.</td></tr>}
            </tbody>
          </table>
        </div>
      )}

      {showForm && (
        <Modal title="New Maintenance Contract" onClose={() => setShowForm(false)} wide>
          <form onSubmit={submit} className="space-y-3">
            <div>
              <label className="text-[10px] text-gray-400 uppercase">Raise from a completed Project (optional)</label>
              <select value={form.projectId} onChange={(e) => pickProject(e.target.value)} className="w-full border border-brand-border rounded-lg px-2 py-1.5 text-xs">
                <option value="">— Standalone contract —</option>
                {projects.map((p) => <option key={p.id} value={p.id}>{p.projectNo} — {p.client.company || p.client.name}</option>)}
              </select>
            </div>
            <input required placeholder="Contract title (e.g. Annual Extinguisher Servicing)" value={form.title} onChange={(e) => setForm({ ...form, title: e.target.value })} className="w-full border border-brand-border rounded-lg px-2 py-1.5 text-xs" />
            <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-xs" disabled={!!form.projectId}>
                <option value="">Select client…</option>
                {clients.map((c) => <option key={c.id} value={c.id}>{c.name}{c.company ? ` — ${c.company}` : ''}</option>)}
              </select>
              <input placeholder="Equipment type" value={form.equipmentType} onChange={(e) => setForm({ ...form, equipmentType: e.target.value })} className="border border-brand-border rounded-lg px-2 py-1.5 text-xs" />
            </div>
            <input placeholder="Site address" value={form.siteAddress} onChange={(e) => setForm({ ...form, siteAddress: e.target.value })} className="w-full border border-brand-border rounded-lg px-2 py-1.5 text-xs" />
            <div className="grid grid-cols-3 gap-2">
              <div>
                <label className="text-[10px] text-gray-400 uppercase">Service every (months)</label>
                <input type="number" min={1} value={form.intervalMonths} onChange={(e) => setForm({ ...form, intervalMonths: e.target.value })} className="w-full border border-brand-border rounded-lg px-2 py-1.5 text-xs" />
              </div>
              <div>
                <label className="text-[10px] text-gray-400 uppercase">Contract value (TZS)</label>
                <input type="number" min={0} value={form.valueTzs} onChange={(e) => setForm({ ...form, valueTzs: e.target.value })} className="w-full border border-brand-border rounded-lg px-2 py-1.5 text-xs" />
              </div>
              <div>
                <label className="text-[10px] text-gray-400 uppercase">First service due</label>
                <input type="date" value={form.startDate} onChange={(e) => setForm({ ...form, startDate: e.target.value })} className="w-full border border-brand-border rounded-lg px-2 py-1.5 text-xs" />
              </div>
            </div>
            <button disabled={saving} className="w-full bg-brand-charcoal text-white text-xs py-2 rounded-lg disabled:opacity-60">{saving ? 'Creating…' : 'Create Contract'}</button>
          </form>
        </Modal>
      )}
    </div>
  );
}
