'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, StatCardSkeleton } from '@/components/Skeletons';
import Modal from '@/components/Modal';

type AssetRow = {
  id: number; assetTag: string; name: string; type: string; status: string;
  serviceDueDate: string | null; purchaseDate: string | null; valueTzs: string | null; notes: string | null;
  assignedTo: { id: number; name: string; employeeNo: string } | null;
};
type Employee = { id: number; name: string; employeeNo: string };
const TYPE_LABEL: Record<string, string> = { VEHICLE: 'Vehicle', TOOL: 'Tool', EQUIPMENT: 'Equipment' };
const STATUS_BADGE: Record<string, string> = { ACTIVE: 'bg-emerald-100 text-emerald-700', IN_SERVICE: 'bg-amber-100 text-amber-700', RETIRED: 'bg-gray-100 text-gray-500' };
const emptyForm = { name: '', type: 'VEHICLE', assignedToId: '', serviceDueDate: '', purchaseDate: '', valueTzs: '', notes: '' };

export default function AssetsPage() {
  const { accessToken, appSecretProof } = useAuth();
  const { show } = useToast();
  const [assets, setAssets] = useState<AssetRow[]>([]);
  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 [employees, setEmployees] = useState<Employee[]>([]);
  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/assets', accessToken, appSecretProof);
      setAssets(d.assets || []);
      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

  useEffect(() => {
    if (!accessToken || !appSecretProof) return;
    adminApiFetch('/admin/assets/lookups/employees', accessToken, appSecretProof).then((d) => setEmployees(d.employees || [])).catch(() => {});
  }, [accessToken, appSecretProof]);

  async function openForm() {
    setShowForm(true);
  }

  async function submit(e: React.FormEvent) {
    e.preventDefault();
    if (!accessToken || !appSecretProof || !form.name) return;
    setSaving(true);
    try {
      await adminApiFetch('/admin/assets', accessToken, appSecretProof, {
        method: 'POST',
        body: JSON.stringify({
          name: form.name, type: form.type, assignedToId: form.assignedToId ? Number(form.assignedToId) : undefined,
          serviceDueDate: form.serviceDueDate || undefined, purchaseDate: form.purchaseDate || undefined,
          valueTzs: form.valueTzs ? Number(form.valueTzs) : undefined, notes: form.notes || undefined,
        }),
      });
      show('success', 'Asset registered.');
      setForm(emptyForm); setShowForm(false);
      load();
    } catch { show('error', 'Could not register that asset.'); }
    finally { setSaving(false); }
  }

  async function reassign(asset: AssetRow, employeeId: string) {
    if (!accessToken || !appSecretProof) return;
    try {
      await adminApiFetch(`/admin/assets/${asset.id}`, accessToken, appSecretProof, { method: 'PATCH', body: JSON.stringify({ assignedToId: employeeId ? Number(employeeId) : null }) });
      load();
    } catch { show('error', 'Could not reassign that asset.'); }
  }

  async function setStatus(id: number, status: string) {
    if (!accessToken || !appSecretProof) return;
    try {
      await adminApiFetch(`/admin/assets/${id}`, accessToken, appSecretProof, { method: 'PATCH', body: JSON.stringify({ status }) });
      show('success', `Marked ${status.replace('_', ' ').toLowerCase()}.`);
      load();
    } catch { show('error', 'Could not update that asset.'); }
  }

  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">Assets / Fleet &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]">+ Register Asset</button>
      </div>

      {loading ? <StatCardSkeleton count={4} /> : (
        <div className="grid grid-cols-2 md:grid-cols-4 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-amber-50 border border-amber-200 rounded-xl p-4"><p className="text-[10px] uppercase text-amber-600">In Service</p><p className="text-lg font-bold text-amber-700">{funnel.IN_SERVICE ?? 0}</p></div>
          <div className="bg-red-50 border border-red-200 rounded-xl p-4"><p className="text-[10px] uppercase text-red-500">Service Due</p><p className="text-lg font-bold text-red-700">{funnel.SERVICE_DUE ?? 0}</p></div>
          <div className="bg-white border border-brand-border rounded-xl p-4"><p className="text-[10px] uppercase text-gray-400">Retired</p><p className="text-lg font-bold">{funnel.RETIRED ?? 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">Asset Tag &bull; Name</th><th className="p-3 text-left">Type</th>
              <th className="p-3 text-left">Assigned To</th><th className="p-3 text-left">Service Due</th>
              <th className="p-3 text-left">Status</th><th className="p-3 text-left">Actions</th>
            </tr></thead>
            <tbody>
              {assets.map((a) => {
                const overdue = a.serviceDueDate && new Date(a.serviceDueDate) <= new Date();
                return (
                  <tr key={a.id} className="border-t border-brand-border hover:bg-brand-bg">
                    <td className="p-3 font-semibold">{a.assetTag}<br /><span className="text-gray-400 font-normal">{a.name}</span></td>
                    <td className="p-3">{TYPE_LABEL[a.type]}</td>
                    <td className="p-3">
                      <select value={a.assignedTo?.id || ''} onChange={(e) => reassign(a, e.target.value)} className="border border-brand-border rounded px-1 py-0.5 text-[11px]">
                        <option value="">Unassigned</option>
                        {employees.map((e) => <option key={e.id} value={e.id}>{e.name}</option>)}
                      </select>
                    </td>
                    <td className="p-3">{a.serviceDueDate ? <span className={overdue ? 'text-red-600 font-semibold' : ''}>{new Date(a.serviceDueDate).toLocaleDateString()}</span> : '—'}</td>
                    <td className="p-3"><span className={`px-2 py-0.5 rounded-full text-[10px] ${STATUS_BADGE[a.status]}`}>{a.status.replace('_', ' ')}</span></td>
                    <td className="p-3 space-x-2">
                      {a.status !== 'IN_SERVICE' && <button onClick={() => setStatus(a.id, 'IN_SERVICE')} className="text-amber-600">In Service</button>}
                      {a.status !== 'ACTIVE' && <button onClick={() => setStatus(a.id, 'ACTIVE')} className="text-emerald-600">Reactivate</button>}
                      {a.status !== 'RETIRED' && <button onClick={() => setStatus(a.id, 'RETIRED')} className="text-brand-red">Retire</button>}
                    </td>
                  </tr>
                );
              })}
              {assets.length === 0 && <tr><td colSpan={6} className="p-6 text-center text-gray-400">No assets registered yet.</td></tr>}
            </tbody>
          </table>
        </div>
      )}

      {showForm && (
        <Modal title="Register Asset" onClose={() => setShowForm(false)}>
          <form onSubmit={submit} className="space-y-2">
            <input required placeholder="Name (e.g. Toyota Hilux — T123 ABC)" value={form.name} onChange={(e) => setForm({ ...form, name: 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 value={form.type} onChange={(e) => setForm({ ...form, type: e.target.value })} className="border border-brand-border rounded-lg px-2 py-1.5 text-xs">
                {Object.entries(TYPE_LABEL).map(([k, v]) => <option key={k} value={k}>{v}</option>)}
              </select>
              <select value={form.assignedToId} onChange={(e) => setForm({ ...form, assignedToId: e.target.value })} className="border border-brand-border rounded-lg px-2 py-1.5 text-xs">
                <option value="">Unassigned</option>
                {employees.map((e) => <option key={e.id} value={e.id}>{e.name}</option>)}
              </select>
            </div>
            <div className="grid grid-cols-3 gap-2">
              <div><label className="text-[10px] text-gray-400 uppercase">Purchased</label><input type="date" value={form.purchaseDate} onChange={(e) => setForm({ ...form, purchaseDate: 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">Service due</label><input type="date" value={form.serviceDueDate} onChange={(e) => setForm({ ...form, serviceDueDate: 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">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>
            <textarea placeholder="Notes" value={form.notes} onChange={(e) => setForm({ ...form, notes: e.target.value })} className="w-full border border-brand-border rounded-lg px-2 py-1.5 text-xs" rows={2} />
            <button disabled={saving} className="w-full bg-brand-charcoal text-white text-xs py-2 rounded-lg disabled:opacity-60">{saving ? 'Saving…' : 'Register Asset'}</button>
          </form>
        </Modal>
      )}
    </div>
  );
}
