"use client";

import { useEffect, useMemo, useState } from "react";
import Link from "next/link";
import { useParams } from "next/navigation";
import {
  AlertCircle,
  ArrowLeft,
  BookOpen,
  Briefcase,
  Calendar,
  CalendarDays,
  Check,
  CheckCircle2,
  Circle,
  ClipboardList,
  Download,
  ExternalLink,
  FileCheck2,
  FileText,
  Plus,
  RefreshCw,
  ShieldCheck,
  Star,
  Trash2,
  Upload,
  User,
  UserCheck,
  Users,
  X,
  XCircle,
} from "lucide-react";
import { ResumeViewer } from "@/components/ResumeViewer";

interface Task {
  id: number;
  title: string;
  description: string;
  category: string;
  assigneeType: "candidate" | "internal";
  assignedUserId: number | null;
  assignedUser: { id: number; name: string } | null;
  requiresUpload: boolean;
  uploadLabel: string;
  required: boolean;
  status: string;
  dueDate: string | null;
}

interface Document {
  id: number;
  taskId: number | null;
  label: string;
  fileName: string;
  mimeType: string;
  fileSize: number;
  status: string;
  reviewNotes: string;
  createdAt: string;
}

interface Workspace {
  id: number;
  status: string;
  startDate: string | null;
  targetStartDate: string | null;
  welcomeMessage: string;
  assignedRecruiterId: number | null;
  candidate: {
    id: number;
    firstName: string;
    lastName: string;
    email: string;
    phone: string;
    summary?: string;
    coverLetter?: string;
    source?: string;
    rating?: number;
    resumeUrl?: string | null;
    resumeData?: any | null;
    createdAt?: string;
  };
  job: { id: number; title: string; location: string } | null;
  assignedRecruiter: { id: number; name: string } | null;
  tasks: Task[];
  documents: Document[];
  progress: number;
  completedTasks: number;
  totalTasks: number;
  applicationSubmission: {
    id: number;
    submittedAt: string;
    responses: Record<string, any>;
    applicantName: string;
    applicantEmail: string;
    applicantPhone: string;
    status: string;
  } | null;
  applicationForm: {
    id: number;
    title: string;
    description: string;
    fields: Array<{
      id: string;
      type: string;
      label: string;
      placeholder?: string;
      required?: boolean;
      options?: string[];
      helpText?: string;
    }>;
  } | null;
  evaluations?: Array<{
    id: number;
    rating: number;
    feedback: string;
    recommendation: string;
    createdAt: string;
    evaluator: { name: string } | null;
  }>;
  interviews?: Array<{
    id: number;
    title: string;
    type: string;
    scheduledAt: string;
    duration: number;
    status: string;
    feedback: string;
  }>;
  employee?: {
    id: number;
    employeeNumber: string;
    jobTitle: string;
    hireDate: string;
    status: string;
    salary?: number;
    ptoBalanceDays?: string;
  } | null;
}

const taskStatusStyles: Record<string, string> = {
  pending: "bg-gray-100 text-gray-700",
  in_progress: "bg-blue-100 text-blue-700",
  pending_review: "bg-amber-100 text-amber-700",
  needs_attention: "bg-red-100 text-red-700",
  completed: "bg-emerald-100 text-emerald-700",
};

export default function OnboardingWorkspacePage() {
  const params = useParams();
  const onboardingId = String(params.id);
  const [workspace, setWorkspace] = useState<Workspace | null>(null);
  const [users, setUsers] = useState<any[]>([]);
  const [templates, setTemplates] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [view, setView] = useState<"staff" | "candidate">("staff");
  const [tab, setTab] = useState<"tasks" | "documents" | "application">("tasks");
  const [showTaskModal, setShowTaskModal] = useState(false);
  const [showTemplateModal, setShowTemplateModal] = useState(false);
  const [saving, setSaving] = useState(false);
  const [notice, setNotice] = useState("");
  const [error, setError] = useState("");
  const [viewDocument, setViewDocument] = useState<Document | null>(null);
  const [newTask, setNewTask] = useState({
    title: "",
    description: "",
    category: "General",
    assigneeType: "candidate",
    assignedUserId: "1",
    dueDate: "",
    required: true,
    requiresUpload: false,
    uploadLabel: "",
  });

  async function loadWorkspace() {
    setLoading(true);
    try {
      const [workspaceRes, usersRes, templatesRes] = await Promise.all([
        fetch(`/api/onboarding/${onboardingId}`),
        fetch("/api/users"),
        fetch("/api/library?type=task"),
      ]);
      const [workspaceData, usersData, templateData] = await Promise.all([
        workspaceRes.json(), usersRes.json(), templatesRes.json(),
      ]);
      if (!workspaceRes.ok) throw new Error(workspaceData.error);
      setWorkspace(workspaceData);
      setUsers(Array.isArray(usersData) ? usersData : []);
      setTemplates(Array.isArray(templateData) ? templateData : []);
    } catch (loadError: any) {
      setError(loadError.message || "Unable to load onboarding workspace.");
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => { loadWorkspace(); }, [onboardingId]);

  const candidateTasks = useMemo(
    () => workspace?.tasks.filter((task) => task.assigneeType === "candidate") || [],
    [workspace]
  );
  const internalTasks = useMemo(
    () => workspace?.tasks.filter((task) => task.assigneeType === "internal") || [],
    [workspace]
  );

  async function addTask() {
    if (!newTask.title.trim()) return;
    setSaving(true); setError("");
    try {
      const response = await fetch(`/api/onboarding/${onboardingId}/tasks`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          ...newTask,
          assignedUserId: newTask.assigneeType === "internal" ? Number(newTask.assignedUserId) : null,
          dueDate: newTask.dueDate || null,
        }),
      });
      const data = await response.json();
      if (!response.ok) throw new Error(data.error);
      setShowTaskModal(false);
      setNewTask({ title: "", description: "", category: "General", assigneeType: "candidate", assignedUserId: "1", dueDate: "", required: true, requiresUpload: false, uploadLabel: "" });
      setNotice("Task assigned successfully.");
      await loadWorkspace();
    } catch (addError: any) {
      setError(addError.message || "Unable to add task.");
    } finally { setSaving(false); }
  }

  async function applyTemplate(template: any) {
    setSaving(true); setError("");
    const tasks = (template.content?.tasks || []).map((task: any) => ({
      title: task.title,
      description: task.description || "",
      category: template.category || "Onboarding",
      assigneeType: "internal",
      assignedUserId: workspace?.assignedRecruiterId || 1,
      required: task.required !== false,
      requiresUpload: false,
      dueDate: workspace?.targetStartDate,
    }));
    try {
      const response = await fetch(`/api/onboarding/${onboardingId}/tasks`, {
        method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ tasks }),
      });
      const data = await response.json();
      if (!response.ok) throw new Error(data.error);
      setShowTemplateModal(false);
      setNotice(`${template.name} tasks were assigned.`);
      await loadWorkspace();
    } catch (templateError: any) { setError(templateError.message || "Unable to apply template."); }
    finally { setSaving(false); }
  }

  function previewDocumentUrl(documentId: number): string {
    return `/api/onboarding/${onboardingId}/documents/${documentId}?inline=true`;
  }

  function isInlineViewable(document: Document): boolean {
    const inlineTypes = ["image/", "application/pdf", "text/"];
    return inlineTypes.some((prefix) => document.mimeType.startsWith(prefix));
  }

  async function updateTask(taskId: number, updates: Record<string, any>) {
    const response = await fetch(`/api/onboarding/${onboardingId}/tasks/${taskId}`, {
      method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(updates),
    });
    if (response.ok) await loadWorkspace();
  }

  async function deleteTask(taskId: number) {
    if (!confirm("Delete this onboarding task?")) return;
    await fetch(`/api/onboarding/${onboardingId}/tasks/${taskId}`, { method: "DELETE" });
    await loadWorkspace();
  }

  async function uploadDocument(task: Task, file: File) {
    setNotice(""); setError("");
    const body = new FormData();
    body.append("file", file);
    body.append("taskId", String(task.id));
    body.append("label", task.uploadLabel || task.title);
    body.append("uploadedByType", view === "candidate" ? "candidate" : "staff");
    const response = await fetch(`/api/onboarding/${onboardingId}/documents`, { method: "POST", body });
    const data = await response.json();
    if (!response.ok) { setError(data.error || "Upload failed."); return; }
    setNotice(`${file.name} uploaded for review.`);
    await loadWorkspace();
  }

  async function reviewDocument(documentId: number, status: "approved" | "rejected") {
    const reviewNotes = status === "rejected" ? prompt("Reason for rejection / instructions to candidate:") || "Please upload a replacement." : "Approved";
    await fetch(`/api/onboarding/${onboardingId}/documents/${documentId}`, {
      method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ status, reviewNotes }),
    });
    setNotice(status === "approved" ? "Document approved." : "Document returned to the candidate.");
    await loadWorkspace();
  }

  async function updateWorkspaceStatus(status: string) {
    const res = await fetch(`/api/onboarding/${onboardingId}`, {
      method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ status }),
    });
    const data = await res.json();
    if (res.ok) {
      if (status === "completed") {
        if (data.employee) {
          setNotice(`🎉 Onboarding Completed! Candidate information pushed to HRIS as ${data.employee.employeeNumber}.`);
        } else {
          setNotice("🎉 Onboarding Completed! Candidate record synced with HRIS.");
        }
      } else {
        setNotice(`Onboarding status updated to ${status.replaceAll("_", " ")}.`);
      }
      await loadWorkspace();
    }
  }

  if (loading) return <div className="h-full flex items-center justify-center"><div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600" /></div>;
  if (!workspace) return <div className="p-6 text-center text-red-600">{error || "Workspace not found"}</div>;

  const renderTask = (task: Task, portalMode: boolean) => {
    const taskDocument = workspace.documents.find((document) => document.taskId === task.id);
    const isComplete = task.status === "completed";
    return (
      <div key={task.id} className={`bg-white border rounded-xl p-4 shadow-sm ${task.status === "needs_attention" ? "border-red-300" : isComplete ? "border-emerald-200" : "border-gray-200"}`}>
        <div className="flex items-start gap-3">
          <button
            onClick={() => !task.requiresUpload && updateTask(task.id, { status: isComplete ? "pending" : "completed" })}
            disabled={task.requiresUpload && !isComplete}
            className={`mt-0.5 shrink-0 ${isComplete ? "text-emerald-600" : "text-gray-300"}`}
          >
            {isComplete ? <CheckCircle2 className="w-5 h-5" /> : <Circle className="w-5 h-5" />}
          </button>
          <div className="flex-1 min-w-0">
            <div className="flex flex-wrap items-center gap-2">
              <h3 className={`font-medium ${isComplete ? "text-gray-500 line-through" : "text-gray-900"}`}>{task.title}</h3>
              {task.required && <span className="text-[10px] uppercase px-1.5 py-0.5 bg-red-50 text-red-600 rounded font-bold">Required</span>}
              <span className={`text-xs px-2 py-0.5 rounded-full font-medium capitalize ${taskStatusStyles[task.status] || taskStatusStyles.pending}`}>{task.status.replaceAll("_", " ")}</span>
            </div>
            {task.description && <p className="text-sm text-gray-500 mt-1">{task.description}</p>}
            <div className="flex flex-wrap gap-3 mt-2 text-xs text-gray-400">
              <span>{task.category}</span>
              {task.dueDate && <span>Due {new Date(`${task.dueDate}T00:00:00`).toLocaleDateString()}</span>}
              {!portalMode && <span>{task.assigneeType === "candidate" ? "Candidate task" : `Internal · ${task.assignedUser?.name || "Unassigned"}`}</span>}
            </div>

            {task.requiresUpload && (
              <div className="mt-3 p-3 bg-blue-50 border border-blue-100 rounded-lg">
                <div className="flex items-center justify-between gap-3">
                  <div>
                    <p className="text-sm font-medium text-blue-900">{task.uploadLabel || "Supporting document"}</p>
                    <p className="text-xs text-blue-700 mt-0.5">PDF, image, or office document · maximum 5 MB</p>
                  </div>
                  {taskDocument ? (
                    <button
                      type="button"
                      onClick={() => setViewDocument(taskDocument)}
                      className="text-xs font-semibold text-blue-700 flex items-center gap-1 hover:text-blue-900 hover:underline"
                      title="View document inline"
                    >
                      <FileText className="w-3 h-3" /> {taskDocument.fileName} — tap to view
                    </button>
                  ) : (
                    <label className="cursor-pointer px-3 py-2 bg-blue-600 hover:bg-blue-700 text-white text-xs font-semibold rounded-lg flex items-center gap-1.5">
                      <Upload className="w-3.5 h-3.5" /> Upload
                      <input type="file" className="hidden" accept=".pdf,.png,.jpg,.jpeg,.doc,.docx" onChange={(event) => { const file = event.target.files?.[0]; if (file) uploadDocument(task, file); event.target.value = ""; }} />
                    </label>
                  )}
                </div>
                {taskDocument?.status === "rejected" && <p className="text-xs text-red-700 mt-2"><strong>Action required:</strong> {taskDocument.reviewNotes}</p>}
              </div>
            )}
          </div>
          {!portalMode && (
            <button onClick={() => deleteTask(task.id)} className="p-1.5 text-gray-300 hover:text-red-600 hover:bg-red-50 rounded-lg"><Trash2 className="w-4 h-4" /></button>
          )}
        </div>
      </div>
    );
  };

  return (
    <div className="min-h-full bg-gray-50">
      <div className="bg-white border-b border-gray-200 px-6 py-4">
        <div className="flex items-center justify-between gap-4">
          <div className="flex items-center gap-3">
            <Link href="/onboarding" className="p-2 hover:bg-gray-100 rounded-lg"><ArrowLeft className="w-5 h-5 text-gray-500" /></Link>
            <div className="w-11 h-11 bg-emerald-100 text-emerald-700 rounded-full flex items-center justify-center font-semibold">{workspace.candidate.firstName[0]}{workspace.candidate.lastName[0]}</div>
            <div><h1 className="font-semibold text-gray-900 text-lg">{workspace.candidate.firstName} {workspace.candidate.lastName}</h1><p className="text-sm text-gray-500">{workspace.job?.title || "New hire"} · Onboarding workspace</p></div>
          </div>
          <div className="flex items-center gap-3">
            <div className="flex bg-gray-100 p-1 rounded-lg">
              <button onClick={() => setView("staff")} className={`px-3 py-1.5 rounded-md text-xs font-medium flex items-center gap-1.5 ${view === "staff" ? "bg-white text-blue-700 shadow-sm" : "text-gray-500"}`}><ShieldCheck className="w-3.5 h-3.5" /> Staff view</button>
              <button onClick={() => setView("candidate")} className={`px-3 py-1.5 rounded-md text-xs font-medium flex items-center gap-1.5 ${view === "candidate" ? "bg-white text-emerald-700 shadow-sm" : "text-gray-500"}`}><User className="w-3.5 h-3.5" /> Candidate portal</button>
            </div>
            {view === "staff" && (
              <div className="flex items-center gap-2">
                {workspace.employee ? (
                  <Link
                    href="/hris"
                    className="flex items-center gap-1.5 px-3.5 py-2 bg-indigo-50 border border-indigo-200 text-indigo-700 font-bold text-xs rounded-lg hover:bg-indigo-100 transition-colors shadow-sm"
                  >
                    <UserCheck className="w-4 h-4 text-indigo-600" />
                    <span>HRIS Pushed: {workspace.employee.employeeNumber}</span>
                  </Link>
                ) : (
                  <button
                    onClick={() => updateWorkspaceStatus("completed")}
                    className="flex items-center gap-1.5 px-3.5 py-2 bg-emerald-600 hover:bg-emerald-700 text-white font-bold text-xs rounded-lg transition-colors shadow-sm"
                  >
                    <CheckCircle2 className="w-4 h-4" />
                    <span>Complete & Push to HRIS</span>
                  </button>
                )}
                <select value={workspace.status} onChange={(event) => updateWorkspaceStatus(event.target.value)} className="px-3 py-2 border border-gray-300 rounded-lg text-sm capitalize"><option value="in_progress">In progress</option><option value="waiting_on_candidate">Waiting on candidate</option><option value="completed">Completed</option><option value="cancelled">Cancelled</option></select>
              </div>
            )}
          </div>
        </div>
      </div>

      <div className="p-6 max-w-7xl mx-auto">
        {notice && <div className="mb-4 p-3 bg-emerald-50 border border-emerald-200 rounded-lg text-sm text-emerald-700 flex justify-between"><span>{notice}</span><button onClick={() => setNotice("")}><X className="w-4 h-4" /></button></div>}
        {error && <div className="mb-4 p-3 bg-red-50 border border-red-200 rounded-lg text-sm text-red-700 flex justify-between"><span>{error}</span><button onClick={() => setError("")}><X className="w-4 h-4" /></button></div>}

        <div className="grid grid-cols-1 lg:grid-cols-4 gap-6">
          <aside className="lg:col-span-1 space-y-4">
            <div className="bg-white border border-gray-200 rounded-xl p-5 shadow-sm">
              <div className="flex justify-between text-sm mb-2"><span className="text-gray-500">Overall progress</span><strong>{workspace.progress}%</strong></div>
              <div className="h-2.5 bg-gray-100 rounded-full overflow-hidden"><div className="h-full bg-emerald-500 rounded-full" style={{ width: `${workspace.progress}%` }} /></div>
              <p className="text-xs text-gray-500 mt-2">{workspace.completedTasks} of {workspace.totalTasks} tasks completed</p>
            </div>
            <div className="bg-white border border-gray-200 rounded-xl p-5 shadow-sm space-y-3 text-sm">
              <div><p className="text-xs text-gray-400">Recruiter / administrator</p><p className="font-medium text-gray-800">{workspace.assignedRecruiter?.name || "Not assigned"}</p></div>
              <div><p className="text-xs text-gray-400">Target start date</p><p className="font-medium text-gray-800">{workspace.targetStartDate ? new Date(`${workspace.targetStartDate}T00:00:00`).toLocaleDateString() : "Not set"}</p></div>
              <div><p className="text-xs text-gray-400">Candidate contact</p><p className="font-medium text-gray-800 truncate">{workspace.candidate.email}</p></div>
            </div>

            {/* HRIS Sync Status Box */}
            {workspace.employee ? (
              <div className="bg-gradient-to-br from-indigo-50 to-blue-50 border border-indigo-200 rounded-xl p-4 shadow-sm space-y-2">
                <div className="flex items-center justify-between">
                  <span className="text-[10px] uppercase font-extrabold px-2 py-0.5 bg-indigo-600 text-white rounded-md">
                    HRIS Pushed
                  </span>
                  <span className="font-mono text-xs font-bold text-indigo-900">{workspace.employee.employeeNumber}</span>
                </div>
                <p className="text-sm font-bold text-gray-900 leading-tight">{workspace.employee.jobTitle}</p>
                <p className="text-xs text-gray-500">
                  Hire Date: <span className="font-medium text-gray-800">{workspace.employee.hireDate}</span>
                </p>
                <Link
                  href="/hris"
                  className="mt-2 flex items-center justify-center gap-1.5 w-full py-2 bg-indigo-600 hover:bg-indigo-700 text-white text-xs font-bold rounded-lg transition-colors shadow-sm"
                >
                  <span>Open HRIS Directory</span>
                  <ExternalLink className="w-3.5 h-3.5" />
                </Link>
              </div>
            ) : (
              <div className="bg-emerald-50/70 border border-emerald-200 rounded-xl p-4 shadow-sm space-y-2">
                <div className="flex items-center gap-2 text-emerald-800 font-bold text-xs">
                  <UserCheck className="w-4 h-4 text-emerald-600" />
                  <span>HRIS Auto-Push Ready</span>
                </div>
                <p className="text-xs text-emerald-700 leading-relaxed">
                  Completing this onboarding case automatically creates an employee record and populates details into HRIS.
                </p>
                <button
                  onClick={() => updateWorkspaceStatus("completed")}
                  className="w-full mt-1 py-2 bg-emerald-600 hover:bg-emerald-700 text-white text-xs font-bold rounded-lg transition-colors shadow-sm flex items-center justify-center gap-1.5"
                >
                  <CheckCircle2 className="w-3.5 h-3.5" />
                  <span>Complete & Push to HRIS Now</span>
                </button>
              </div>
            )}
            {view === "staff" && (
              <div className="bg-white border border-gray-200 rounded-xl p-4 shadow-sm space-y-2">
                <button onClick={() => setTab("application")} className="w-full flex items-center justify-center gap-2 px-3 py-2.5 bg-emerald-50 text-emerald-800 border border-emerald-200 rounded-lg text-sm font-semibold hover:bg-emerald-100 transition-colors"><ClipboardList className="w-4 h-4 text-emerald-600" /> Recall Application</button>
                <button onClick={() => setShowTaskModal(true)} className="w-full flex items-center justify-center gap-2 px-3 py-2.5 bg-blue-600 text-white rounded-lg text-sm font-medium hover:bg-blue-700"><Plus className="w-4 h-4" /> Assign task / document</button>
                <button onClick={() => setShowTemplateModal(true)} className="w-full flex items-center justify-center gap-2 px-3 py-2.5 bg-gray-100 text-gray-700 rounded-lg text-sm font-medium hover:bg-gray-200"><BookOpen className="w-4 h-4" /> Apply task template</button>
              </div>
            )}
          </aside>

          <main className="lg:col-span-3">
            {view === "candidate" && (
              <div className="mb-5 bg-gradient-to-r from-emerald-600 to-teal-600 text-white rounded-xl p-6 shadow-sm">
                <p className="text-sm text-emerald-100">Welcome to the team</p>
                <h2 className="text-xl font-bold mt-1">Hi {workspace.candidate.firstName}! 👋</h2>
                <p className="text-sm text-emerald-50 mt-2 max-w-2xl">{workspace.welcomeMessage || "Complete the tasks below before your first day. Your onboarding contact is available if you need help."}</p>
              </div>
            )}

            {view === "staff" && (
              <div className="flex items-center gap-1 bg-white border border-gray-200 p-1 rounded-lg w-fit mb-4 shadow-sm flex-wrap">
                <button onClick={() => setTab("tasks")} className={`px-4 py-2 rounded-md text-sm font-medium ${tab === "tasks" ? "bg-blue-600 text-white" : "text-gray-600 hover:bg-gray-50"}`}>Tasks ({workspace.tasks.length})</button>
                <button onClick={() => setTab("documents")} className={`px-4 py-2 rounded-md text-sm font-medium ${tab === "documents" ? "bg-blue-600 text-white" : "text-gray-600 hover:bg-gray-50"}`}>Documents ({workspace.documents.length})</button>
                <button onClick={() => setTab("application")} className={`px-4 py-2 rounded-md text-sm font-medium flex items-center gap-1.5 ${tab === "application" ? "bg-blue-600 text-white" : "text-gray-600 hover:bg-gray-50"}`}><ClipboardList className="w-4 h-4" /> Recall Application</button>
              </div>
            )}

            {view === "staff" && tab === "application" && (
              <div className="space-y-6">
                {/* Summary Banner */}
                <div className="bg-white border border-gray-200 rounded-2xl p-6 shadow-sm">
                  <div className="flex flex-col md:flex-row md:items-center justify-between gap-4 border-b border-gray-100 pb-5 mb-5">
                    <div>
                      <span className="text-xs font-bold uppercase px-2.5 py-1 bg-emerald-100 text-emerald-800 rounded-full">
                        Recruitment ATS Profile Recalled
                      </span>
                      <h2 className="text-xl font-bold text-gray-900 mt-2">
                        {workspace.candidate.firstName} {workspace.candidate.lastName} — Application Record
                      </h2>
                      <p className="text-sm text-gray-500 mt-0.5">
                        Applied for <strong className="text-gray-800">{workspace.job?.title || "Assigned Role"}</strong> • Source: <span className="capitalize">{workspace.candidate.source?.replace("_", " ") || "Direct"}</span>
                      </p>
                    </div>
                    <Link
                      href={`/candidates/${workspace.candidate.id}`}
                      className="flex items-center gap-2 px-4 py-2 bg-slate-900 text-white hover:bg-slate-800 rounded-xl text-sm font-semibold transition-colors shrink-0 shadow-sm"
                    >
                      <span>Open Candidate ATS Profile</span>
                      <ExternalLink className="w-4 h-4" />
                    </Link>
                  </div>

                  <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-4 gap-4 text-sm">
                    <div className="p-3.5 bg-gray-50 rounded-xl border border-gray-100">
                      <p className="text-xs text-gray-400 uppercase font-bold">Email Address</p>
                      <p className="font-medium text-gray-900 truncate mt-0.5">{workspace.candidate.email}</p>
                    </div>
                    <div className="p-3.5 bg-gray-50 rounded-xl border border-gray-100">
                      <p className="text-xs text-gray-400 uppercase font-bold">Phone Number</p>
                      <p className="font-medium text-gray-900 mt-0.5">{workspace.candidate.phone || "No phone recorded"}</p>
                    </div>
                    <div className="p-3.5 bg-gray-50 rounded-xl border border-gray-200/60">
                      <p className="text-xs text-gray-400 uppercase font-bold">Recruiter Rating</p>
                      <div className="flex items-center gap-1 mt-1">
                        {[1, 2, 3, 4, 5].map((star) => (
                          <Star
                            key={star}
                            className={`w-4 h-4 ${
                              star <= (workspace.candidate.rating || 0)
                                ? "fill-amber-400 text-amber-400"
                                : "text-gray-200"
                            }`}
                          />
                        ))}
                        <span className="text-xs text-gray-600 font-bold ml-1">({workspace.candidate.rating || 0}/5)</span>
                      </div>
                    </div>
                    <div className="p-3.5 bg-gray-50 rounded-xl border border-gray-100">
                      <p className="text-xs text-gray-400 uppercase font-bold">Application Date</p>
                      <p className="font-medium text-gray-900 mt-0.5">
                        {workspace.applicationSubmission
                          ? new Date(workspace.applicationSubmission.submittedAt).toLocaleDateString()
                          : workspace.candidate.createdAt
                          ? new Date(workspace.candidate.createdAt).toLocaleDateString()
                          : "N/A"}
                      </p>
                    </div>
                  </div>
                </div>

                {/* Questionnaire Q&A */}
                <div className="bg-white border border-gray-200 rounded-2xl p-6 shadow-sm space-y-4">
                  <div className="flex items-center justify-between border-b border-gray-100 pb-3">
                    <div className="flex items-center gap-2">
                      <ClipboardList className="w-5 h-5 text-blue-600" />
                      <h3 className="font-bold text-gray-900 text-base">Submitted Job Application Questionnaire</h3>
                    </div>
                    {workspace.applicationSubmission && (
                      <span className="text-xs bg-blue-50 text-blue-700 font-semibold px-2.5 py-1 rounded-full border border-blue-100">
                        Submission #{workspace.applicationSubmission.id}
                      </span>
                    )}
                  </div>

                  {workspace.applicationSubmission ? (
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                      {workspace.applicationForm?.fields?.length ? (
                        workspace.applicationForm.fields.map((field) => {
                          const val = workspace.applicationSubmission?.responses?.[field.id];
                          return (
                            <div key={field.id} className="p-4 bg-gray-50 rounded-xl border border-gray-200/80 space-y-1">
                              <p className="text-xs font-bold text-gray-500 uppercase">{field.label}</p>
                              <p className="text-sm font-medium text-gray-900 whitespace-pre-line">
                                {val !== undefined && val !== null && val !== "" ? String(val) : "No response provided"}
                              </p>
                            </div>
                          );
                        })
                      ) : (
                        Object.entries(workspace.applicationSubmission.responses || {}).map(([key, val]) => (
                          <div key={key} className="p-4 bg-gray-50 rounded-xl border border-gray-200/80 space-y-1">
                            <p className="text-xs font-bold text-gray-500 uppercase">{key.replace(/([A-Z])/g, " $1")}</p>
                            <p className="text-sm font-medium text-gray-900 whitespace-pre-line">
                              {val !== undefined && val !== null && val !== "" ? String(val) : "No response provided"}
                            </p>
                          </div>
                        ))
                      )}
                    </div>
                  ) : (
                    <div className="p-5 bg-gray-50 rounded-xl border border-gray-200/80 space-y-3">
                      <p className="text-sm text-gray-700 font-medium">Candidate Application Notes & Cover Letter:</p>
                      <p className="text-sm text-gray-600 leading-relaxed bg-white p-4 rounded-lg border border-gray-200">
                        {workspace.candidate.summary || workspace.candidate.coverLetter || "No structured questionnaire submission found for this application record."}
                      </p>
                    </div>
                  )}
                </div>

                {/* Side-by-Side Resume View */}
                {(workspace.candidate.resumeData || workspace.candidate.resumeUrl) && (
                  <div className="bg-white border border-gray-200 rounded-2xl p-6 shadow-sm space-y-4">
                    <div className="flex items-center gap-2 border-b border-gray-100 pb-3">
                      <FileText className="w-5 h-5 text-blue-600" />
                      <h3 className="font-bold text-gray-900 text-base">Candidate Resume & Credentials Record</h3>
                    </div>
                    <div className="h-[650px] overflow-hidden rounded-xl border border-gray-200">
                      <ResumeViewer
                        resumeData={workspace.candidate.resumeData}
                        resumeUrl={workspace.candidate.resumeUrl}
                        firstName={workspace.candidate.firstName}
                        lastName={workspace.candidate.lastName}
                        email={workspace.candidate.email}
                        phone={workspace.candidate.phone}
                        expanded
                      />
                    </div>
                  </div>
                )}

                {/* Recruitment Feedback Summary */}
                {((workspace.evaluations && workspace.evaluations.length > 0) || (workspace.interviews && workspace.interviews.length > 0)) && (
                  <div className="bg-white border border-gray-200 rounded-2xl p-6 shadow-sm space-y-4">
                    <div className="flex items-center gap-2 border-b border-gray-100 pb-3">
                      <Briefcase className="w-5 h-5 text-purple-600" />
                      <h3 className="font-bold text-gray-900 text-base">Hiring Evaluations & Interview Digest</h3>
                    </div>
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                      {workspace.evaluations && workspace.evaluations.length > 0 && (
                        <div className="space-y-3">
                          <h4 className="text-xs font-bold text-gray-400 uppercase tracking-wider">Evaluations ({workspace.evaluations.length})</h4>
                          {workspace.evaluations.map((eval_) => (
                            <div key={eval_.id} className="p-3.5 bg-gray-50 rounded-xl border border-gray-200/80 space-y-1">
                              <div className="flex items-center justify-between">
                                <span className="text-xs font-semibold text-gray-800">{eval_.evaluator?.name || "Team Member"}</span>
                                <span className="text-xs font-bold px-2 py-0.5 bg-blue-100 text-blue-800 rounded-full capitalize">{eval_.recommendation.replace("_", " ")}</span>
                              </div>
                              <p className="text-xs text-gray-600 leading-relaxed">&quot;{eval_.feedback}&quot;</p>
                            </div>
                          ))}
                        </div>
                      )}
                      {workspace.interviews && workspace.interviews.length > 0 && (
                        <div className="space-y-3">
                          <h4 className="text-xs font-bold text-gray-400 uppercase tracking-wider">Interviews ({workspace.interviews.length})</h4>
                          {workspace.interviews.map((intv) => (
                            <div key={intv.id} className="p-3.5 bg-gray-50 rounded-xl border border-gray-200/80 space-y-1">
                              <div className="flex items-center justify-between">
                                <span className="text-xs font-semibold text-gray-800">{intv.title}</span>
                                <span className="text-xs font-bold px-2 py-0.5 bg-emerald-100 text-emerald-800 rounded-full capitalize">{intv.status}</span>
                              </div>
                              {intv.feedback && <p className="text-xs text-gray-600 leading-relaxed">&quot;{intv.feedback}&quot;</p>}
                            </div>
                          ))}
                        </div>
                      )}
                    </div>
                  </div>
                )}
              </div>
            )}

            {(view === "candidate" || tab === "tasks") && (
              <div className="space-y-6">
                {(view === "candidate" ? [{ label: "Your tasks", tasks: candidateTasks }] : [{ label: "Candidate tasks", tasks: candidateTasks }, { label: "Internal team tasks", tasks: internalTasks }]).map((section) => (
                  <section key={section.label}>
                    <div className="flex items-center justify-between mb-3"><h2 className="font-semibold text-gray-900 flex items-center gap-2">{section.label === "Candidate tasks" || section.label === "Your tasks" ? <UserCheck className="w-4 h-4 text-emerald-600" /> : <Users className="w-4 h-4 text-blue-600" />}{section.label}<span className="text-xs bg-gray-200 text-gray-600 px-2 py-0.5 rounded-full">{section.tasks.length}</span></h2></div>
                    <div className="space-y-3">{section.tasks.length ? section.tasks.map((task) => renderTask(task, view === "candidate")) : <div className="bg-white border border-dashed border-gray-300 rounded-xl p-8 text-center text-sm text-gray-400">No tasks assigned.</div>}</div>
                  </section>
                ))}
              </div>
            )}

            {view === "staff" && tab === "documents" && (
              <div className="space-y-3">
                {!workspace.documents.length ? <div className="bg-white border border-dashed border-gray-300 rounded-xl p-10 text-center"><FileText className="w-10 h-10 text-gray-300 mx-auto mb-2" /><p className="text-sm text-gray-500">No documents uploaded yet.</p></div> : workspace.documents.map((document) => (
                  <div key={document.id} className="bg-white border border-gray-200 rounded-xl p-4 shadow-sm flex items-center gap-4">
                    <button
                      type="button"
                      onClick={() => setViewDocument(document)}
                      className="p-2.5 bg-blue-50 rounded-lg hover:bg-blue-100 transition-colors shrink-0"
                      title="View document inline"
                    >
                      <FileText className="w-5 h-5 text-blue-600" />
                    </button>
                    <div className="flex-1 min-w-0">
                      <p className="font-medium text-gray-900 truncate">{document.label}</p>
                      <p className="text-xs text-gray-500 truncate">{document.fileName} · {(document.fileSize / 1024).toFixed(1)} KB · uploaded {new Date(document.createdAt).toLocaleDateString()}</p>
                      {document.reviewNotes && <p className="text-xs text-gray-500 mt-1">Review: {document.reviewNotes}</p>}
                    </div>
                    <span className={`text-xs px-2 py-1 rounded-full font-medium capitalize ${document.status === "approved" ? "bg-emerald-100 text-emerald-700" : document.status === "rejected" ? "bg-red-100 text-red-700" : "bg-amber-100 text-amber-700"}`}>{document.status.replaceAll("_", " ")}</span>
                    <button
                      type="button"
                      onClick={() => setViewDocument(document)}
                      className="px-2.5 py-1.5 bg-blue-600 text-white text-xs font-bold rounded-lg hover:bg-blue-700 transition-colors flex items-center gap-1"
                    >
                      <FileText className="w-3.5 h-3.5" /> View Inline
                    </button>
                    <a href={`/api/onboarding/${onboardingId}/documents/${document.id}`} className="p-2 text-gray-500 hover:text-blue-600 hover:bg-blue-50 rounded-lg" title="Download"><Download className="w-4 h-4" /></a>
                    {document.status !== "approved" && <button onClick={() => reviewDocument(document.id, "approved")} className="p-2 text-emerald-600 hover:bg-emerald-50 rounded-lg" title="Approve"><Check className="w-4 h-4" /></button>}
                    {document.status !== "rejected" && <button onClick={() => reviewDocument(document.id, "rejected")} className="p-2 text-red-600 hover:bg-red-50 rounded-lg" title="Reject"><XCircle className="w-4 h-4" /></button>}
                  </div>
                ))}
              </div>
            )}
          </main>
        </div>
      </div>

      {showTaskModal && (
        <div className="fixed inset-0 bg-black/55 z-50 flex items-center justify-center p-4"><div className="bg-white rounded-2xl shadow-2xl w-full max-w-lg max-h-[90vh] overflow-y-auto">
          <div className="p-5 border-b border-gray-200 flex justify-between"><div><h2 className="font-semibold text-gray-900">Assign onboarding task</h2><p className="text-sm text-gray-500">Identify candidate details, uploads, or internal actions.</p></div><button onClick={() => setShowTaskModal(false)} className="p-2 hover:bg-gray-100 rounded-lg"><X className="w-5 h-5 text-gray-400" /></button></div>
          <div className="p-5 space-y-4">
            <div><label className="block text-sm font-medium text-gray-700 mb-1">Task title *</label><input value={newTask.title} onChange={(event) => setNewTask({ ...newTask, title: event.target.value })} className="w-full px-3 py-2.5 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:outline-none" placeholder="e.g. Upload signed employee handbook" /></div>
            <div><label className="block text-sm font-medium text-gray-700 mb-1">Instructions</label><textarea value={newTask.description} onChange={(event) => setNewTask({ ...newTask, description: event.target.value })} rows={3} className="w-full px-3 py-2.5 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:outline-none resize-none" placeholder="Tell the candidate or team member exactly what is needed..." /></div>
            <div className="grid grid-cols-2 gap-3"><div><label className="block text-sm font-medium text-gray-700 mb-1">Category</label><input value={newTask.category} onChange={(event) => setNewTask({ ...newTask, category: event.target.value })} className="w-full px-3 py-2.5 border border-gray-300 rounded-lg text-sm" /></div><div><label className="block text-sm font-medium text-gray-700 mb-1">Due date</label><input type="date" value={newTask.dueDate} onChange={(event) => setNewTask({ ...newTask, dueDate: event.target.value })} className="w-full px-3 py-2.5 border border-gray-300 rounded-lg text-sm" /></div></div>
            <div><label className="block text-sm font-medium text-gray-700 mb-1">Assign to</label><select value={newTask.assigneeType} onChange={(event) => setNewTask({ ...newTask, assigneeType: event.target.value })} className="w-full px-3 py-2.5 border border-gray-300 rounded-lg text-sm"><option value="candidate">Candidate / new hire</option><option value="internal">Internal staff member</option></select></div>
            {newTask.assigneeType === "internal" && <div><label className="block text-sm font-medium text-gray-700 mb-1">Staff member</label><select value={newTask.assignedUserId} onChange={(event) => setNewTask({ ...newTask, assignedUserId: event.target.value })} className="w-full px-3 py-2.5 border border-gray-300 rounded-lg text-sm">{users.map((user) => <option key={user.id} value={user.id}>{user.name} ({user.role.replaceAll("_", " ")})</option>)}</select></div>}
            {newTask.assigneeType === "candidate" && <div className="p-4 bg-blue-50 border border-blue-100 rounded-lg"><label className="flex items-center gap-2 text-sm font-medium text-blue-900"><input type="checkbox" checked={newTask.requiresUpload} onChange={(event) => setNewTask({ ...newTask, requiresUpload: event.target.checked })} className="rounded border-blue-300" /> Require the candidate to upload a document</label>{newTask.requiresUpload && <div className="mt-3"><label className="block text-xs font-medium text-blue-800 mb-1">Requested document / detail label</label><input value={newTask.uploadLabel} onChange={(event) => setNewTask({ ...newTask, uploadLabel: event.target.value })} className="w-full px-3 py-2 border border-blue-200 rounded-lg text-sm bg-white" placeholder="e.g. Direct deposit authorization form" /></div>}</div>}
            <label className="flex items-center gap-2 text-sm text-gray-700"><input type="checkbox" checked={newTask.required} onChange={(event) => setNewTask({ ...newTask, required: event.target.checked })} className="rounded border-gray-300" /> Required before onboarding can be completed</label>
          </div>
          <div className="p-5 border-t border-gray-200 flex justify-end gap-3"><button onClick={() => setShowTaskModal(false)} className="px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 rounded-lg">Cancel</button><button onClick={addTask} disabled={saving || !newTask.title} className="px-5 py-2 text-sm font-semibold text-white bg-blue-600 hover:bg-blue-700 rounded-lg disabled:opacity-50">{saving ? "Assigning..." : "Assign Task"}</button></div>
        </div></div>
      )}

      {/* Inline Document Viewer Modal */}
      {viewDocument && (
        <div className="fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-2xl shadow-2xl w-full max-w-5xl max-h-[92vh] overflow-hidden flex flex-col border border-gray-100">
            <div className="px-6 py-4 bg-slate-900 text-white flex items-center justify-between shrink-0">
              <div className="flex items-center gap-3 min-w-0">
                <div className="p-2 bg-blue-500/20 rounded-xl">
                  <FileText className="w-5 h-5 text-blue-400" />
                </div>
                <div className="min-w-0">
                  <h2 className="font-bold text-lg truncate">{viewDocument.label}</h2>
                  <p className="text-xs text-slate-400 truncate">
                    {viewDocument.fileName} · {(viewDocument.fileSize / 1024).toFixed(1)} KB ·{" "}
                    {viewDocument.status === "approved"
                      ? "Approved"
                      : viewDocument.status === "rejected"
                      ? "Rejected — Re-upload Needed"
                      : "Pending Review"}
                  </p>
                </div>
              </div>
              <div className="flex items-center gap-2 shrink-0">
                <a
                  href={`/api/onboarding/${onboardingId}/documents/${viewDocument.id}`}
                  className="px-3 py-2 bg-blue-600 hover:bg-blue-700 text-white text-xs font-bold rounded-lg flex items-center gap-1.5 transition-colors"
                  title="Download original file"
                >
                  <Download className="w-4 h-4" />
                  Download
                </a>
                <button
                  onClick={() => setViewDocument(null)}
                  className="p-2 text-slate-400 hover:text-white hover:bg-slate-800 rounded-xl transition-colors"
                >
                  <X className="w-5 h-5" />
                </button>
              </div>
            </div>

            <div className="flex-1 bg-slate-100 flex items-center justify-center overflow-auto">
              {isInlineViewable(viewDocument) ? (
                <iframe
                  src={previewDocumentUrl(viewDocument.id)}
                  className="w-full h-full min-h-[600px] border-0"
                  title={viewDocument.fileName}
                />
              ) : (
                <div className="text-center p-12 space-y-4 max-w-md">
                  <FileText className="w-16 h-16 text-gray-300 mx-auto" />
                  <h3 className="font-bold text-xl text-gray-900">Preview not available</h3>
                  <p className="text-sm text-gray-500">
                    This file type (<span className="font-mono text-gray-700">{viewDocument.mimeType}</span>) cannot be previewed inline.
                  </p>
                  <p className="text-sm text-gray-500">
                    Please download it to view the contents on your device.
                  </p>
                  <div className="flex justify-center gap-3 pt-2">
                    <a
                      href={`/api/onboarding/${onboardingId}/documents/${viewDocument.id}`}
                      className="px-6 py-3 bg-blue-600 hover:bg-blue-700 text-white font-bold rounded-xl shadow-sm flex items-center gap-2 transition-colors"
                    >
                      <Download className="w-4 h-4" />
                      Download {viewDocument.fileName}
                    </a>
                    <button
                      onClick={() => setViewDocument(null)}
                      className="px-5 py-3 bg-gray-100 hover:bg-gray-200 text-gray-700 font-medium rounded-xl"
                    >
                      Close
                    </button>
                  </div>
                </div>
              )}
            </div>

            <div className="px-5 py-3 bg-white border-t border-gray-200 flex items-center justify-between shrink-0">
              <span className="text-xs text-gray-400">
                Uploaded {new Date(viewDocument.createdAt).toLocaleString()}
                {viewDocument.reviewNotes && (
                  <span className="ml-3 text-amber-600 font-medium">
                    Review note: {viewDocument.reviewNotes}
                  </span>
                )}
              </span>
              <button
                onClick={() => setViewDocument(null)}
                className="px-5 py-2.5 bg-slate-900 text-white font-bold text-sm rounded-xl hover:bg-slate-800 shadow-sm"
              >
                Close Preview
              </button>
            </div>
          </div>
        </div>
      )}

      {showTemplateModal && (
        <div className="fixed inset-0 bg-black/55 z-50 flex items-center justify-center p-4"><div className="bg-white rounded-2xl shadow-2xl w-full max-w-lg max-h-[85vh] overflow-hidden flex flex-col">
          <div className="p-5 border-b border-gray-200 flex justify-between"><div><h2 className="font-semibold text-gray-900">Apply task template</h2><p className="text-sm text-gray-500">Add a standard checklist from the template library.</p></div><button onClick={() => setShowTemplateModal(false)} className="p-2 hover:bg-gray-100 rounded-lg"><X className="w-5 h-5 text-gray-400" /></button></div>
          <div className="p-5 overflow-y-auto space-y-3">{templates.map((template) => <button key={template.id} onClick={() => applyTemplate(template)} className="w-full text-left p-4 border border-gray-200 rounded-xl hover:border-blue-400 hover:bg-blue-50 transition-colors"><h3 className="font-medium text-gray-900">{template.name}</h3><p className="text-xs text-gray-500 mt-1">{template.description}</p><p className="text-xs font-medium text-blue-600 mt-2">{template.content?.tasks?.length || 0} tasks</p></button>)}</div>
          <div className="p-4 border-t border-gray-200 text-right"><button onClick={() => setShowTemplateModal(false)} className="px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 rounded-lg">Cancel</button></div>
        </div></div>
      )}
    </div>
  );
}
