'use client';

import { useState } from 'react';
import Link from 'next/link';
import { useEffect } 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 ProjectRow = {
  id: number; projectNo: string; title: string; status: string; projectType: string | null;
  siteAddress: string | null; targetCompletionDate: string | null;
  client: { name: string; company: string | null };
  quote: { quoteNo: string } | null;
  assignments: { employee: { id: number; name: string } }[];
};
type ClientLookup = { id: number; name: string; company: string | null; phone: string };
type QuoteLookup = { id: number; quoteNo: string; projectType: string | null; site: string | null; client: { id: number; name: string; company: string | null } };

const STATUSES = ['PLANNING', 'SCHEDULED', 'IN_PROGRESS', 'ON_HOLD', 'COMPLETED', 'SIGNED_OFF', 'CANCELLED'];
const LABEL: Record<string, string> = {
  PLANNING: 'Planning', SCHEDULED: 'Scheduled', IN_PROGRESS: 'In Progress',
  ON_HOLD: 'On Hold', COMPLETED: 'Completed', SIGNED_OFF: 'Signed Off', CANCELLED: 'Cancelled',
};
const BADGE: Record<string, string> = {
  PLANNING: 'bg-gray-100 text-gray-600', SCHEDULED: 'bg-blue-100 text-blue-700',
  IN_PROGRESS: 'bg-amber-100 text-amber-700', ON_HOLD: 'bg-orange-100 text-orange-700',
  COMPLETED: 'bg-emerald-100 text-emerald-700', SIGNED_OFF: 'bg-emerald-600 text-white',
  CANCELLED: 'bg-red-100 text-red-700',
};
const emptyForm = { title: '', clientId: '', quoteId: '', projectType: '', siteAddress: '', description: '', targetCompletionDate: '' };

export default function ProjectsPage() {
  const { accessToken, appSecretProof } = useAuth();
  const { show } = useToast();
  const [projects, setProjects] = useState<ProjectRow[]>([]);
  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 [quotes, setQuotes] = useState<QuoteLookup[]>([]);
  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/projects', accessToken, appSecretProof);
      setProjects(d.projects || []);
      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, q] = await Promise.all([
        adminApiFetch('/admin/projects/lookups/clients', accessToken, appSecretProof),
        adminApiFetch('/admin/projects/lookups/quotes', accessToken, appSecretProof),
      ]);
      setClients(c.clients || []);
      setQuotes(q.quotes || []);
    } catch { show('error', 'Could not load clients/quotes.'); }
  }

  function pickQuote(quoteId: string) {
    const q = quotes.find((x) => String(x.id) === quoteId);
    setForm((f) => ({
      ...f, quoteId,
      clientId: q ? String(q.client.id) : f.clientId,
      projectType: q?.projectType || f.projectType,
      siteAddress: q?.site || f.siteAddress,
      title: f.title || (q ? `${q.projectType || 'Installation'} — ${q.client.company || q.client.name}` : 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/projects', accessToken, appSecretProof, {
        method: 'POST',
        body: JSON.stringify({
          title: form.title, clientId: Number(form.clientId),
          quoteId: form.quoteId ? Number(form.quoteId) : undefined,
          projectType: form.projectType || undefined, siteAddress: form.siteAddress || undefined,
          description: form.description || undefined,
          targetCompletionDate: form.targetCompletionDate || undefined,
        }),
      });
      show('success', `${d.project.projectNo} created.`);
      setForm(emptyForm);
      setShowForm(false);
      load();
    } catch { show('error', 'Could not create that project.'); }
    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">Projects / Jobs &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 Project</button>
      </div>

      {loading ? <StatCardSkeleton count={5} /> : (
        <div className="grid grid-cols-2 md:grid-cols-5 gap-3">
          {['PLANNING', 'SCHEDULED', 'IN_PROGRESS', 'COMPLETED', 'SIGNED_OFF'].map((s) => (
            <div key={s} className="bg-white border border-brand-border rounded-xl p-4">
              <p className="text-[10px] uppercase text-gray-400">{LABEL[s]}</p>
              <p className="text-lg font-bold">{funnel[s] ?? 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">Project No &bull; Title</th><th className="p-3 text-left">Client</th>
              <th className="p-3 text-left">Type / Site</th><th className="p-3 text-left">Crew</th>
              <th className="p-3 text-left">Target Completion</th><th className="p-3 text-left">Status</th>
            </tr></thead>
            <tbody>
              {projects.map((p) => (
                <tr key={p.id} className="border-t border-brand-border transition-colors hover:bg-brand-bg">
                  <td className="p-3"><Link href={`/projects/${p.id}`} className="font-semibold hover:text-brand-red">{p.projectNo}</Link><br /><span className="text-gray-400">{p.title}</span></td>
                  <td className="p-3">{p.client.name}{p.client.company && ` • ${p.client.company}`}{p.quote && <><br /><span className="text-gray-400">from {p.quote.quoteNo}</span></>}</td>
                  <td className="p-3">{p.projectType || '—'}<br /><span className="text-gray-400">{p.siteAddress || '—'}</span></td>
                  <td className="p-3">{p.assignments.length ? p.assignments.map((a) => a.employee.name).join(', ') : <span className="text-gray-400">Unassigned</span>}</td>
                  <td className="p-3">{p.targetCompletionDate ? new Date(p.targetCompletionDate).toLocaleDateString() : '—'}</td>
                  <td className="p-3"><span className={`px-2 py-0.5 rounded-full text-[10px] ${BADGE[p.status]}`}>{LABEL[p.status]}</span></td>
                </tr>
              ))}
              {projects.length === 0 && <tr><td colSpan={6} className="p-6 text-center text-gray-400">No projects yet.</td></tr>}
            </tbody>
          </table>
        </div>
      )}

      {showForm && (
        <Modal title="New Project" onClose={() => setShowForm(false)} wide>
          <form onSubmit={submit} className="space-y-3">
            <div>
              <label className="text-[10px] text-gray-400 uppercase">Raise from an approved Quote (optional)</label>
              <select value={form.quoteId} onChange={(e) => pickQuote(e.target.value)} className="w-full border border-brand-border rounded-lg px-2 py-1.5 text-xs">
                <option value="">— Standalone project —</option>
                {quotes.map((q) => <option key={q.id} value={q.id}>{q.quoteNo} — {q.client.company || q.client.name}</option>)}
              </select>
            </div>
            <input required placeholder="Project title" 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.quoteId}>
                <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="Project type (e.g. New Installation)" value={form.projectType} onChange={(e) => setForm({ ...form, projectType: 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" />
            <textarea placeholder="Scope / description" value={form.description} onChange={(e) => setForm({ ...form, description: e.target.value })} className="w-full border border-brand-border rounded-lg px-2 py-1.5 text-xs" rows={2} />
            <div>
              <label className="text-[10px] text-gray-400 uppercase">Target completion date</label>
              <input type="date" value={form.targetCompletionDate} onChange={(e) => setForm({ ...form, targetCompletionDate: e.target.value })} className="w-full border border-brand-border rounded-lg px-2 py-1.5 text-xs" />
            </div>
            <button disabled={saving} className="w-full bg-brand-charcoal text-white text-xs py-2 rounded-lg disabled:opacity-60">{saving ? 'Creating…' : 'Create Project'}</button>
          </form>
        </Modal>
      )}
    </div>
  );
}
