'use client';

import { useEffect, useState } from 'react';
import { useParams, useRouter } from 'next/navigation';
import { useAuth } from '@/lib/auth-context';
import { adminApiFetch } from '@/lib/api';
import { useToast } from '@/lib/toast';

type Employee = { id: number; name: string; employeeNo: string };
type Visit = { id: number; scheduledDate: string; completedDate: string | null; status: string; technicianIds: number[] | null; notes: string | null };
type ContractDetail = {
  id: number; contractNo: string; title: string; status: string; equipmentType: string | null;
  siteAddress: string | null; intervalMonths: number; nextDueDate: string; valueTzs: string | null; notes: string | null;
  client: { id: number; name: string; company: string | null; phone: string };
  project: { id: number; projectNo: string; title: string } | null;
  visits: Visit[];
};

const STATUSES = ['ACTIVE', 'PAUSED', 'EXPIRED', 'CANCELLED'];
const VISIT_LABEL: Record<string, string> = { SCHEDULED: 'Scheduled', COMPLETED: 'Completed', MISSED: 'Missed', RESCHEDULED: 'Rescheduled' };
const VISIT_BADGE: Record<string, string> = {
  SCHEDULED: 'bg-blue-100 text-blue-700', COMPLETED: 'bg-emerald-100 text-emerald-700',
  MISSED: 'bg-red-100 text-red-700', RESCHEDULED: 'bg-amber-100 text-amber-700',
};

export default function MaintenanceDetailPage() {
  const params = useParams();
  const router = useRouter();
  const id = Number(params.id);
  const { accessToken, appSecretProof } = useAuth();
  const { show } = useToast();

  const [contract, setContract] = useState<ContractDetail | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [employees, setEmployees] = useState<Employee[]>([]);

  const [scheduleDate, setScheduleDate] = useState('');
  const [scheduleTechnicians, setScheduleTechnicians] = useState<number[]>([]);
  const [scheduleNotes, setScheduleNotes] = useState('');
  const [scheduling, setScheduling] = useState(false);

  async function load() {
    if (!accessToken || !appSecretProof || !id) return;
    setLoading(true);
    try {
      const d = await adminApiFetch(`/admin/maintenance/${id}`, accessToken, appSecretProof);
      setContract(d.contract);
    } catch { setError('Could not load this contract — check your permissions.'); }
    finally { setLoading(false); }
  }
  useEffect(() => { load(); }, [accessToken, appSecretProof, id]); // eslint-disable-line react-hooks/exhaustive-deps

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

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

  async function scheduleVisit(e: React.FormEvent) {
    e.preventDefault();
    if (!accessToken || !appSecretProof || !scheduleDate) return;
    setScheduling(true);
    try {
      await adminApiFetch(`/admin/maintenance/${id}/visits`, accessToken, appSecretProof, {
        method: 'POST', body: JSON.stringify({ scheduledDate: scheduleDate, technicianIds: scheduleTechnicians, notes: scheduleNotes || undefined }),
      });
      setScheduleDate(''); setScheduleTechnicians([]); setScheduleNotes('');
      show('success', 'Visit scheduled.');
      load();
    } catch { show('error', 'Could not schedule that visit.'); }
    finally { setScheduling(false); }
  }

  async function completeVisit(visitId: number) {
    if (!accessToken || !appSecretProof) return;
    try {
      await adminApiFetch(`/admin/maintenance/visits/${visitId}/complete`, accessToken, appSecretProof, { method: 'PATCH', body: JSON.stringify({}) });
      show('success', 'Visit completed — next due date advanced.');
      load();
    } catch { show('error', 'Could not complete that visit.'); }
  }

  async function markVisit(visitId: number, status: 'MISSED' | 'RESCHEDULED') {
    if (!accessToken || !appSecretProof) return;
    try {
      await adminApiFetch(`/admin/maintenance/visits/${visitId}/status`, accessToken, appSecretProof, { method: 'PATCH', body: JSON.stringify({ status }) });
      show('success', `Visit marked ${status.toLowerCase()}.`);
      load();
    } catch { show('error', 'Could not update that visit.'); }
  }

  if (loading) return <p className="text-xs text-gray-400">Loading…</p>;
  if (error || !contract) return <p className="text-sm text-brand-red">{error || 'Not found.'}</p>;

  const daysUntilDue = Math.round((new Date(contract.nextDueDate).getTime() - Date.now()) / 86400000);

  return (
    <div className="space-y-5">
      <div className="flex items-center justify-between">
        <div>
          <button onClick={() => router.push('/maintenance')} className="text-[10px] text-gray-400 hover:text-brand-charcoal mb-1">&larr; All Contracts</button>
          <h1 className="text-xl font-bold">{contract.contractNo} &bull; {contract.title}</h1>
          <p className="text-xs text-gray-500">{contract.client.name}{contract.client.company && ` • ${contract.client.company}`} • {contract.client.phone}</p>
        </div>
        <select value={contract.status} onChange={(e) => setStatus(e.target.value)} className="border border-brand-border rounded-lg px-3 py-2 text-xs font-semibold">
          {STATUSES.map((s) => <option key={s} value={s}>{s}</option>)}
        </select>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-3 gap-4 text-xs">
        <div className="bg-white border border-brand-border rounded-xl p-4 space-y-1">
          <p className="text-[10px] uppercase text-gray-400">Contract Details</p>
          <p><span className="text-gray-400">Equipment:</span> {contract.equipmentType || '—'}</p>
          <p><span className="text-gray-400">Site:</span> {contract.siteAddress || '—'}</p>
          <p><span className="text-gray-400">Interval:</span> every {contract.intervalMonths} months</p>
          {contract.valueTzs && <p><span className="text-gray-400">Value:</span> TZS {Number(contract.valueTzs).toLocaleString()}</p>}
          {contract.project && <p><span className="text-gray-400">From:</span> {contract.project.projectNo}</p>}
        </div>
        <div className={`rounded-xl p-4 space-y-1 border ${daysUntilDue < 0 ? 'bg-red-50 border-red-200' : daysUntilDue <= 30 ? 'bg-amber-50 border-amber-200' : 'bg-emerald-50 border-emerald-200'}`}>
          <p className="text-[10px] uppercase text-gray-500">Next Service Due</p>
          <p className="text-lg font-bold">{new Date(contract.nextDueDate).toLocaleDateString()}</p>
          <p className="text-gray-500">{daysUntilDue < 0 ? `${Math.abs(daysUntilDue)} days overdue` : `in ${daysUntilDue} days`}</p>
        </div>
        <div className="bg-white border border-brand-border rounded-xl p-4">
          <p className="text-[10px] uppercase text-gray-400 mb-2">Schedule Next Visit</p>
          <form onSubmit={scheduleVisit} className="space-y-2">
            <input required type="date" value={scheduleDate} onChange={(e) => setScheduleDate(e.target.value)} className="w-full border border-brand-border rounded-lg px-2 py-1.5 text-xs" />
            <div className="flex flex-wrap gap-2">
              {employees.map((e) => (
                <label key={e.id} className="flex items-center gap-1 text-[11px]">
                  <input type="checkbox" checked={scheduleTechnicians.includes(e.id)}
                    onChange={(ev) => setScheduleTechnicians((prev) => ev.target.checked ? [...prev, e.id] : prev.filter((x) => x !== e.id))} />
                  {e.name}
                </label>
              ))}
            </div>
            <input placeholder="Notes (optional)" value={scheduleNotes} onChange={(e) => setScheduleNotes(e.target.value)} className="w-full border border-brand-border rounded-lg px-2 py-1.5 text-xs" />
            <button disabled={scheduling} className="w-full bg-brand-charcoal text-white text-xs py-1.5 rounded-lg disabled:opacity-60">{scheduling ? 'Scheduling…' : 'Schedule Visit'}</button>
          </form>
        </div>
      </div>

      <div className="bg-white border border-brand-border rounded-xl overflow-hidden">
        <p className="text-[10px] uppercase text-gray-400 p-4 pb-0">Visit History</p>
        <table className="w-full text-xs mt-2">
          <thead className="bg-brand-bg"><tr>
            <th className="p-3 text-left">Scheduled</th><th className="p-3 text-left">Completed</th>
            <th className="p-3 text-left">Notes</th><th className="p-3 text-left">Status</th><th className="p-3 text-left">Actions</th>
          </tr></thead>
          <tbody>
            {contract.visits.map((v) => (
              <tr key={v.id} className="border-t border-brand-border">
                <td className="p-3">{new Date(v.scheduledDate).toLocaleDateString()}</td>
                <td className="p-3">{v.completedDate ? new Date(v.completedDate).toLocaleDateString() : '—'}</td>
                <td className="p-3 text-gray-500">{v.notes || '—'}</td>
                <td className="p-3"><span className={`px-2 py-0.5 rounded-full text-[10px] ${VISIT_BADGE[v.status]}`}>{VISIT_LABEL[v.status]}</span></td>
                <td className="p-3 space-x-2">
                  {v.status === 'SCHEDULED' && (
                    <>
                      <button onClick={() => completeVisit(v.id)} className="text-emerald-600 font-semibold">Mark Completed</button>
                      <button onClick={() => markVisit(v.id, 'MISSED')} className="text-brand-red">Missed</button>
                    </>
                  )}
                </td>
              </tr>
            ))}
            {contract.visits.length === 0 && <tr><td colSpan={5} className="p-6 text-center text-gray-400">No visits logged yet.</td></tr>}
          </tbody>
        </table>
      </div>
    </div>
  );
}
