'use client';

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

type Employee = { id: number; name: string; employeeNo: string; roleTitle?: string };
type Photo = { id: number; url: string; type: string; caption: string | null; createdAt: string };
type Visit = { id: number; visitDate: string; technicianIds: number[] | null; summary: string | null };
type ProjectDetail = {
  id: number; projectNo: string; title: string; status: string; projectType: string | null;
  siteAddress: string | null; description: string | null; notes: string | null;
  startDate: string | null; targetCompletionDate: string | null; actualCompletionDate: string | null;
  client: { id: number; name: string; company: string | null; phone: string };
  quote: { id: number; quoteNo: string; totalTzs: string } | null;
  order: { id: number; orderNo: string; totalTzs: string } | null;
  invoice: { id: number; invoiceNo: string; status: string; totalTzs: string } | null;
  assignments: { employee: Employee; roleOnJob: string | null }[];
  visits: Visit[];
  photos: Photo[];
  signOff: { signedByName: string; signedByTitle: string | null; signatureUrl: string; notes: string | null; signedAt: 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 PHOTO_TYPES = ['BEFORE', 'AFTER', 'PROGRESS'] as const;

export default function ProjectDetailPage() {
  const params = useParams();
  const router = useRouter();
  const id = Number(params.id);
  const { accessToken, appSecretProof } = useAuth();
  const { show } = useToast();
  const fileRef = useRef<HTMLInputElement>(null);

  const [project, setProject] = useState<ProjectDetail | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [employees, setEmployees] = useState<Employee[]>([]);

  const [assignEmployeeId, setAssignEmployeeId] = useState('');
  const [assignRole, setAssignRole] = useState('');
  const [visitSummary, setVisitSummary] = useState('');
  const [visitTechnicians, setVisitTechnicians] = useState<number[]>([]);
  const [photoType, setPhotoType] = useState<typeof PHOTO_TYPES[number]>('PROGRESS');
  const [photoCaption, setPhotoCaption] = useState('');
  const [uploading, setUploading] = useState(false);

  const [signName, setSignName] = useState('');
  const [signTitle, setSignTitle] = useState('');
  const [signature, setSignature] = useState<SignatureValue>(null);
  const [signNotes, setSignNotes] = useState('');
  const [signing, setSigning] = useState(false);

  async function load() {
    if (!accessToken || !appSecretProof || !id) return;
    setLoading(true);
    try {
      const d = await adminApiFetch(`/admin/projects/${id}`, accessToken, appSecretProof);
      setProject(d.project);
    } catch { setError('Could not load this project — 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/projects/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/projects/${id}/status`, accessToken, appSecretProof, { method: 'PATCH', body: JSON.stringify({ status }) });
      show('success', `Moved to ${LABEL[status]}.`);
      load();
    } catch { show('error', 'Could not update status.'); }
  }

  async function assignTechnician(e: React.FormEvent) {
    e.preventDefault();
    if (!accessToken || !appSecretProof || !assignEmployeeId) return;
    try {
      await adminApiFetch(`/admin/projects/${id}/assign`, accessToken, appSecretProof, {
        method: 'POST', body: JSON.stringify({ employeeId: Number(assignEmployeeId), roleOnJob: assignRole || undefined }),
      });
      setAssignEmployeeId(''); setAssignRole('');
      show('success', 'Technician assigned.');
      load();
    } catch { show('error', 'Could not assign technician.'); }
  }

  async function unassign(employeeId: number) {
    if (!accessToken || !appSecretProof) return;
    try {
      await adminApiFetch(`/admin/projects/${id}/assign/${employeeId}`, accessToken, appSecretProof, { method: 'DELETE' });
      show('success', 'Technician removed from job.');
      load();
    } catch { show('error', 'Could not remove technician.'); }
  }

  async function logVisit(e: React.FormEvent) {
    e.preventDefault();
    if (!accessToken || !appSecretProof) return;
    try {
      await adminApiFetch(`/admin/projects/${id}/visits`, accessToken, appSecretProof, {
        method: 'POST', body: JSON.stringify({ technicianIds: visitTechnicians, summary: visitSummary || undefined }),
      });
      setVisitSummary(''); setVisitTechnicians([]);
      show('success', 'Site visit logged.');
      load();
    } catch { show('error', 'Could not log that visit.'); }
  }

  async function uploadPhoto(file: File) {
    if (!accessToken || !appSecretProof) return;
    setUploading(true);
    try {
      const fd = new FormData();
      fd.append('photo', file);
      const res = await fetch(`${process.env.NEXT_PUBLIC_API_BASE_URL}/admin/projects/upload-photo`, {
        method: 'POST',
        headers: { Authorization: `Bearer ${accessToken}`, 'X-App-Secret-Proof': appSecretProof },
        body: fd,
      });
      const uploaded = await res.json();
      if (!res.ok) throw new Error(uploaded.error || 'UPLOAD_FAILED');
      await adminApiFetch(`/admin/projects/${id}/photos`, accessToken, appSecretProof, {
        method: 'POST', body: JSON.stringify({ url: uploaded.url, type: photoType, caption: photoCaption || undefined }),
      });
      setPhotoCaption('');
      show('success', 'Photo added.');
      load();
    } catch { show('error', 'Could not upload that photo.'); }
    finally { setUploading(false); if (fileRef.current) fileRef.current.value = ''; }
  }

  async function deletePhoto(photoId: number) {
    if (!accessToken || !appSecretProof) return;
    try {
      await adminApiFetch(`/admin/projects/photos/${photoId}`, accessToken, appSecretProof, { method: 'DELETE' });
      load();
    } catch { show('error', 'Could not delete that photo.'); }
  }

  async function submitSignOff(e: React.FormEvent) {
    e.preventDefault();
    if (!accessToken || !appSecretProof || !signName || !signature?.image) {
      show('error', 'Name and signature are both required.');
      return;
    }
    setSigning(true);
    try {
      await adminApiFetch(`/admin/projects/${id}/signoff`, accessToken, appSecretProof, {
        method: 'POST',
        body: JSON.stringify({ signedByName: signName, signedByTitle: signTitle || undefined, signatureUrl: signature.image, notes: signNotes || undefined }),
      });
      show('success', 'Job signed off by the client.');
      load();
    } catch { show('error', 'Could not record the sign-off.'); }
    finally { setSigning(false); }
  }

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

  const assignedIds = new Set(project.assignments.map((a) => a.employee.id));

  return (
    <div className="space-y-5">
      <div className="flex items-center justify-between">
        <div>
          <button onClick={() => router.push('/projects')} className="text-[10px] text-gray-400 hover:text-brand-charcoal mb-1">&larr; All Projects</button>
          <h1 className="text-xl font-bold">{project.projectNo} &bull; {project.title}</h1>
          <p className="text-xs text-gray-500">{project.client.name}{project.client.company && ` • ${project.client.company}`} • {project.client.phone}</p>
        </div>
        <select value={project.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}>{LABEL[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">Job Details</p>
          <p><span className="text-gray-400">Type:</span> {project.projectType || '—'}</p>
          <p><span className="text-gray-400">Site:</span> {project.siteAddress || '—'}</p>
          <p><span className="text-gray-400">Target completion:</span> {project.targetCompletionDate ? new Date(project.targetCompletionDate).toLocaleDateString() : '—'}</p>
          {project.description && <p className="text-gray-500 pt-1">{project.description}</p>}
        </div>
        <div className="bg-white border border-brand-border rounded-xl p-4 space-y-1">
          <p className="text-[10px] uppercase text-gray-400">Linked Records</p>
          <p>{project.quote ? <>Quote: <span className="font-semibold">{project.quote.quoteNo}</span> (TZS {Number(project.quote.totalTzs).toLocaleString()})</> : <span className="text-gray-400">No quote linked</span>}</p>
          <p>{project.order ? <>Order: <span className="font-semibold">{project.order.orderNo}</span></> : <span className="text-gray-400">No order linked</span>}</p>
          <p>{project.invoice ? <>Invoice: <span className="font-semibold">{project.invoice.invoiceNo}</span> ({project.invoice.status})</> : <span className="text-gray-400">Not yet invoiced</span>}</p>
        </div>
        <div className="bg-white border border-brand-border rounded-xl p-4 space-y-1">
          <p className="text-[10px] uppercase text-gray-400">Crew</p>
          {project.assignments.length === 0 && <p className="text-gray-400">Unassigned</p>}
          {project.assignments.map((a) => (
            <div key={a.employee.id} className="flex justify-between items-center">
              <span>{a.employee.name}{a.roleOnJob && ` — ${a.roleOnJob}`}</span>
              <button onClick={() => unassign(a.employee.id)} className="text-brand-red text-[10px]">Remove</button>
            </div>
          ))}
          <form onSubmit={assignTechnician} className="flex gap-1 pt-2">
            <select value={assignEmployeeId} onChange={(e) => setAssignEmployeeId(e.target.value)} className="flex-1 border border-brand-border rounded px-1.5 py-1 text-[11px]">
              <option value="">Assign technician…</option>
              {employees.filter((e) => !assignedIds.has(e.id)).map((e) => <option key={e.id} value={e.id}>{e.name}</option>)}
            </select>
            <input placeholder="Role" value={assignRole} onChange={(e) => setAssignRole(e.target.value)} className="w-20 border border-brand-border rounded px-1.5 py-1 text-[11px]" />
            <button className="bg-brand-charcoal text-white px-2 rounded text-[11px]">Add</button>
          </form>
        </div>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        <div className="bg-white border border-brand-border rounded-xl p-4">
          <p className="text-[10px] uppercase text-gray-400 mb-2">Site Visits</p>
          <form onSubmit={logVisit} className="space-y-2 mb-3">
            <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={visitTechnicians.includes(e.id)}
                    onChange={(ev) => setVisitTechnicians((prev) => ev.target.checked ? [...prev, e.id] : prev.filter((x) => x !== e.id))} />
                  {e.name}
                </label>
              ))}
            </div>
            <textarea placeholder="What was found / done on site…" value={visitSummary} onChange={(e) => setVisitSummary(e.target.value)} className="w-full border border-brand-border rounded-lg px-2 py-1.5 text-xs" rows={2} />
            <button className="bg-brand-charcoal text-white text-xs px-3 py-1.5 rounded-lg">Log Visit</button>
          </form>
          <div className="space-y-2 max-h-64 overflow-y-auto">
            {project.visits.map((v) => (
              <div key={v.id} className="border-t border-brand-border pt-2 text-xs">
                <p className="text-gray-400">{new Date(v.visitDate).toLocaleString()}</p>
                <p>{v.summary || <span className="text-gray-400">No notes recorded.</span>}</p>
              </div>
            ))}
            {project.visits.length === 0 && <p className="text-gray-400 text-xs">No site visits logged yet.</p>}
          </div>
        </div>

        <div className="bg-white border border-brand-border rounded-xl p-4">
          <p className="text-[10px] uppercase text-gray-400 mb-2">Before / After Photos</p>
          <div className="flex gap-2 mb-2">
            <select value={photoType} onChange={(e) => setPhotoType(e.target.value as typeof PHOTO_TYPES[number])} className="border border-brand-border rounded px-1.5 py-1 text-[11px]">
              {PHOTO_TYPES.map((t) => <option key={t} value={t}>{t}</option>)}
            </select>
            <input placeholder="Caption" value={photoCaption} onChange={(e) => setPhotoCaption(e.target.value)} className="flex-1 border border-brand-border rounded px-1.5 py-1 text-[11px]" />
          </div>
          <input ref={fileRef} type="file" accept="image/*" disabled={uploading}
            onChange={(e) => e.target.files?.[0] && uploadPhoto(e.target.files[0])}
            className="text-[11px] mb-3" />
          <div className="grid grid-cols-3 gap-2 max-h-64 overflow-y-auto">
            {project.photos.map((p) => (
              <div key={p.id} className="relative group">
                <img src={p.url} alt={p.caption || p.type} className="w-full h-20 object-cover rounded-lg border border-brand-border" />
                <span className="absolute top-1 left-1 bg-black/60 text-white text-[9px] px-1.5 py-0.5 rounded">{p.type}</span>
                <button onClick={() => deletePhoto(p.id)} className="absolute top-1 right-1 bg-black/60 text-white text-[9px] px-1.5 rounded opacity-0 group-hover:opacity-100">✕</button>
              </div>
            ))}
            {project.photos.length === 0 && <p className="text-gray-400 text-xs col-span-3">No photos yet.</p>}
          </div>
        </div>
      </div>

      <div className="bg-white border border-brand-border rounded-xl p-4">
        <p className="text-[10px] uppercase text-gray-400 mb-2">Client Completion Sign-Off</p>
        {project.signOff ? (
          <div className="text-xs space-y-2">
            <p>Signed by <span className="font-semibold">{project.signOff.signedByName}</span>{project.signOff.signedByTitle && ` — ${project.signOff.signedByTitle}`} on {new Date(project.signOff.signedAt).toLocaleString()}</p>
            {project.signOff.notes && <p className="text-gray-500">{project.signOff.notes}</p>}
            <img src={project.signOff.signatureUrl} alt="Signature" className="h-20 border border-brand-border rounded-lg bg-white p-1" />
          </div>
        ) : (
          <form onSubmit={submitSignOff} className="space-y-2 max-w-md">
            <div className="grid grid-cols-2 gap-2">
              <input required placeholder="Signed by (client name)" value={signName} onChange={(e) => setSignName(e.target.value)} className="border border-brand-border rounded-lg px-2 py-1.5 text-xs" />
              <input placeholder="Title (optional)" value={signTitle} onChange={(e) => setSignTitle(e.target.value)} className="border border-brand-border rounded-lg px-2 py-1.5 text-xs" />
            </div>
            <SignaturePad value={signature} onChange={setSignature} />
            <textarea placeholder="Completion notes (optional)" value={signNotes} onChange={(e) => setSignNotes(e.target.value)} className="w-full border border-brand-border rounded-lg px-2 py-1.5 text-xs" rows={2} />
            <button disabled={signing} className="bg-brand-red text-white text-xs px-4 py-2 rounded-lg disabled:opacity-60">{signing ? 'Recording…' : 'Record Sign-Off & Close Job'}</button>
          </form>
        )}
      </div>
    </div>
  );
}
