"use client";

import { useEffect, useState } from "react";
import { useParams, useRouter } from "next/navigation";
import Link from "next/link";
import {
  ArrowLeft,
  Mail,
  Phone,
  MapPin,
  Building2,
  Star,
  Calendar,
  FileText,
  MessageSquare,
  Plus,
  ChevronRight,
  User,
  ExternalLink,
  LinkIcon,
  Globe,
  X,
  Send,
  Smartphone,
  AlertCircle,
  ClipboardList,
  PanelRightOpen,
  PanelRightClose,
  UserCheck,
} from "lucide-react";
import { ResumeViewer } from "@/components/ResumeViewer";
import type { ResumeData } from "@/lib/resume";

interface Evaluation {
  id: number;
  rating: number;
  feedback: string;
  recommendation: string;
  category: string;
  createdAt: string;
  evaluator: { name: string } | null;
}

interface Interview {
  id: number;
  title: string;
  type: string;
  scheduledAt: string;
  duration: number;
  location: string;
  meetingLink: string;
  status: string;
  feedback: string;
}

interface TextMessage {
  id: number;
  phone: string;
  body: string;
  status: string;
  providerMessageId: string;
  error: string;
  createdAt: string;
  sentAt: string | null;
}



interface TextMessagingSetting {
  enabled: boolean;
  provider: "mock" | "external";
  fromNumber: string;
  consentRequired: boolean;
  canManage: boolean;
}

interface CandidateDetail {
  id: number;
  firstName: string;
  lastName: string;
  email: string;
  phone: string;
  linkedin: string;
  website: string;
  summary: string;
  coverLetter: string;
  source: string;
  rating: number;
  status: string;
  resumeUrl: string | null;
  resumeFileType: string | null;
  resumeData: ResumeData | null;
  createdAt: string;
  job: { id: number; title: string } | null;
  currentStage: { id: number; name: string; type: string } | null;
  currentPipeline: any;
  evaluations: Evaluation[];
  interviews: Interview[];
  textMessages: TextMessage[];
  onboardingCase: { id: number; status: string } | null;
  employee?: { id: number; employeeNumber: string; jobTitle: string; status: string } | null;
  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;
}

export default function CandidateDetailPage() {
  const params = useParams();
  const router = useRouter();
  const candidateId = params.id as string;
  const [candidate, setCandidate] = useState<CandidateDetail | null>(null);
  const [loading, setLoading] = useState(true);
  const [activeTab, setActiveTab] = useState<"overview" | "application" | "evaluations" | "interviews" | "texts">("overview");
  const [showEvalModal, setShowEvalModal] = useState(false);
  const [showInterviewModal, setShowInterviewModal] = useState(false);
  const [showTextModal, setShowTextModal] = useState(false);
  const [showResume, setShowResume] = useState(false);
  const [textingSetting, setTextingSetting] = useState<TextMessagingSetting | null>(null);
  const [textMessage, setTextMessage] = useState("");
  const [textStatus, setTextStatus] = useState("");
  const [sendingText, setSendingText] = useState(false);
  const [startingOnboarding, setStartingOnboarding] = useState(false);
  const [newEval, setNewEval] = useState({
    rating: 3,
    feedback: "",
    recommendation: "pending",
  });
  const [newInterview, setNewInterview] = useState({
    title: "",
    type: "video",
    scheduledAt: "",
    duration: 30,
    location: "",
    meetingLink: "",
    notes: "",
  });

  useEffect(() => {
    fetch(`/api/candidates/${candidateId}`)
      .then((res) => res.json())
      .then((data) => {
        setCandidate(data);
        setLoading(false);
      });

    fetch("/api/settings/text-messaging")
      .then((res) => res.json())
      .then((data) => setTextingSetting(data))
      .catch(() => setTextingSetting(null));
  }, [candidateId]);

  async function submitEvaluation() {
    await fetch("/api/evaluations", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        candidateId: parseInt(candidateId),
        jobId: candidate?.job?.id,
        rating: newEval.rating,
        feedback: newEval.feedback,
        recommendation: newEval.recommendation,
      }),
    });
    setShowEvalModal(false);
    setNewEval({ rating: 3, feedback: "", recommendation: "pending" });
    fetch(`/api/candidates/${candidateId}`)
      .then((res) => res.json())
      .then(setCandidate);
  }

  async function scheduleInterview() {
    await fetch("/api/interviews", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        candidateId: parseInt(candidateId),
        jobId: candidate?.job?.id,
        ...newInterview,
      }),
    });
    setShowInterviewModal(false);
    setNewInterview({
      title: "",
      type: "video",
      scheduledAt: "",
      duration: 30,
      location: "",
      meetingLink: "",
      notes: "",
    });
    fetch(`/api/candidates/${candidateId}`)
      .then((res) => res.json())
      .then(setCandidate);
  }

  async function sendTextMessage() {
    setSendingText(true);
    setTextStatus("");

    const response = await fetch("/api/text-messages", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        candidateId: parseInt(candidateId),
        body: textMessage,
        senderId: 1,
      }),
    });

    const data = await response.json();
    setSendingText(false);

    if (!response.ok) {
      setTextStatus(data.error || "Unable to send text message.");
      return;
    }

    setTextStatus("Text message sent and logged.");
    setTextMessage("");
    setShowTextModal(false);
    setActiveTab("texts");
    fetch(`/api/candidates/${candidateId}`)
      .then((res) => res.json())
      .then(setCandidate);
  }

  async function startCandidateOnboarding() {
    if (!candidate) return;
    setStartingOnboarding(true);
    const response = await fetch("/api/onboarding", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ candidateId: candidate.id, assignedRecruiterId: 1 }),
    });
    const data = await response.json();
    setStartingOnboarding(false);

    if (response.ok || (response.status === 409 && data.onboardingId)) {
      router.push(`/onboarding/${data.id || data.onboardingId}`);
    }
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center h-full">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600" />
      </div>
    );
  }

  if (!candidate) {
    return <div className="p-6 text-center text-gray-500">Candidate not found</div>;
  }

  const recommendationColors: Record<string, string> = {
    strong_yes: "bg-green-100 text-green-700",
    yes: "bg-blue-100 text-blue-700",
    neutral: "bg-gray-100 text-gray-700",
    no: "bg-red-100 text-red-700",
  };

  return (
    <div className="p-6">
      {/* Breadcrumb */}
      <div className="flex items-center justify-between gap-4 mb-4">
        <div className="flex items-center gap-2 text-sm text-gray-500">
          <Link href="/candidates" className="hover:text-blue-600 transition-colors">
            Candidates
          </Link>
          <ChevronRight className="w-4 h-4" />
          <span className="text-gray-900 font-medium">
            {candidate.firstName} {candidate.lastName}
          </span>
        </div>
        {(candidate.resumeData || candidate.resumeUrl) && (
          <button
            onClick={() => setShowResume((prev) => !prev)}
            className={`flex items-center gap-2 px-3 py-2 rounded-lg transition-colors text-sm font-medium ${
              showResume
                ? "bg-blue-600 text-white hover:bg-blue-700"
                : "bg-white text-gray-700 border border-gray-300 hover:bg-gray-50"
            }`}
          >
            {showResume ? <PanelRightClose className="w-4 h-4" /> : <PanelRightOpen className="w-4 h-4" />}
            {showResume ? "Hide Resume" : "View Resume"}
          </button>
        )}
      </div>

      <div className={showResume ? "flex flex-col xl:flex-row gap-6 items-start" : ""}>
        {/* Resume Panel - Side by side */}
        {showResume && (
          <div className="w-full xl:w-[460px] xl:shrink-0 xl:sticky xl:top-6 h-[calc(100vh-7rem)] min-h-[600px]">
            <ResumeViewer
              resumeData={candidate.resumeData}
              resumeUrl={candidate.resumeUrl}
              firstName={candidate.firstName}
              lastName={candidate.lastName}
              email={candidate.email}
              phone={candidate.phone}
              expanded
            />
          </div>
        )}

        {/* Details: profile + tabs */}
        <div className={showResume ? "flex-1 w-full grid grid-cols-1 gap-6" : "grid grid-cols-1 lg:grid-cols-3 gap-6"}>
        {/* Left Column - Candidate Info */}
        <div className={`space-y-6 ${showResume ? "" : "lg:col-span-1"}`}>
          {/* Profile Card */}
          <div className="bg-white rounded-xl border border-gray-200 shadow-sm p-5">
            <div className="flex items-center gap-4 mb-4">
              <div className="w-16 h-16 bg-blue-100 rounded-full flex items-center justify-center text-xl font-bold text-blue-700">
                {candidate.firstName[0]}
                {candidate.lastName[0]}
              </div>
              <div>
                <h1 className="text-xl font-bold text-gray-900">
                  {candidate.firstName} {candidate.lastName}
                </h1>
                <div className="flex items-center gap-2 mt-1">
                  <div className="flex items-center gap-0.5">
                    {[1, 2, 3, 4, 5].map((star) => (
                      <Star
                        key={star}
                        className={`w-4 h-4 ${
                          star <= (candidate.rating || 0)
                            ? "fill-amber-400 text-amber-400"
                            : "text-gray-200"
                        }`}
                      />
                    ))}
                  </div>
                  <span className="text-sm text-gray-500 capitalize">
                    {candidate.source.replace("_", " ")}
                  </span>
                </div>
              </div>
            </div>

            {candidate.currentStage && (
              <div className="mb-4 p-3 bg-blue-50 rounded-lg">
                <p className="text-xs text-gray-500 mb-1">Current Stage</p>
                <p className="text-sm font-medium text-blue-700">{candidate.currentStage.name}</p>
              </div>
            )}

            {candidate.job && (
              <div className="mb-4">
                <Link
                  href={`/jobs/${candidate.job.id}`}
                  className="text-sm font-medium text-blue-600 hover:text-blue-700"
                >
                  {candidate.job.title}
                </Link>
              </div>
            )}

            <div className="space-y-3 pt-4 border-t border-gray-100">
              <a
                href={`mailto:${candidate.email}`}
                className="flex items-center gap-3 text-sm text-gray-600 hover:text-blue-600 transition-colors"
              >
                <Mail className="w-4 h-4 text-gray-400" />
                {candidate.email}
              </a>
              {candidate.phone && (
                <a
                  href={`tel:${candidate.phone}`}
                  className="flex items-center gap-3 text-sm text-gray-600 hover:text-blue-600 transition-colors"
                >
                  <Phone className="w-4 h-4 text-gray-400" />
                  {candidate.phone}
                </a>
              )}
              {candidate.linkedin && (
                <a
                  href={candidate.linkedin}
                  target="_blank"
                  className="flex items-center gap-3 text-sm text-gray-600 hover:text-blue-600 transition-colors"
                >
                  <LinkIcon className="w-4 h-4 text-gray-400" />
                  LinkedIn Profile
                </a>
              )}
              {candidate.website && (
                <a
                  href={candidate.website}
                  target="_blank"
                  className="flex items-center gap-3 text-sm text-gray-600 hover:text-blue-600 transition-colors"
                >
                  <Globe className="w-4 h-4 text-gray-400" />
                  Portfolio
                </a>
              )}
              <div className="flex items-center gap-3 text-sm text-gray-600">
                <Calendar className="w-4 h-4 text-gray-400" />
                Applied {new Date(candidate.createdAt).toLocaleDateString("en-US", { month: "long", day: "numeric", year: "numeric" })}
              </div>
            </div>
          </div>

          {/* Quick Actions */}
          <div className="bg-white rounded-xl border border-gray-200 shadow-sm p-5">
            <h3 className="font-semibold text-gray-900 mb-3">Quick Actions</h3>
            <div className="space-y-2">
              {candidate.employee && (
                <Link
                  href="/hris"
                  className="w-full flex items-center gap-3 p-3 text-sm font-bold text-indigo-800 bg-indigo-50 hover:bg-indigo-100 rounded-lg transition-colors border border-indigo-200"
                >
                  <UserCheck className="w-4 h-4 text-indigo-600" />
                  Pushed to HRIS ({candidate.employee.employeeNumber})
                </Link>
              )}
              {candidate.onboardingCase ? (
                <Link
                  href={`/onboarding/${candidate.onboardingCase.id}`}
                  className="w-full flex items-center gap-3 p-3 text-sm font-medium text-emerald-700 bg-emerald-50 hover:bg-emerald-100 rounded-lg transition-colors"
                >
                  <UserCheck className="w-4 h-4" />
                  Open Onboarding Workspace
                </Link>
              ) : (
                <button
                  onClick={startCandidateOnboarding}
                  disabled={startingOnboarding}
                  className="w-full flex items-center gap-3 p-3 text-sm font-medium text-emerald-700 bg-emerald-50 hover:bg-emerald-100 rounded-lg transition-colors disabled:opacity-50"
                >
                  <UserCheck className="w-4 h-4" />
                  {startingOnboarding ? "Starting Onboarding..." : "Select & Start Onboarding"}
                </button>
              )}
              <button
                onClick={() => setActiveTab("application")}
                className="w-full flex items-center gap-3 p-3 text-sm font-medium text-blue-700 bg-blue-50 hover:bg-blue-100 rounded-lg transition-colors"
              >
                <ClipboardList className="w-4 h-4 text-blue-600" />
                Recall Submitted Application
              </button>
              <button
                onClick={() => setShowEvalModal(true)}
                className="w-full flex items-center gap-3 p-3 text-sm text-gray-700 hover:bg-gray-50 rounded-lg transition-colors"
              >
                <Star className="w-4 h-4 text-amber-500" />
                Add Evaluation
              </button>
              <button
                onClick={() => setShowInterviewModal(true)}
                className="w-full flex items-center gap-3 p-3 text-sm text-gray-700 hover:bg-gray-50 rounded-lg transition-colors"
              >
                <Calendar className="w-4 h-4 text-blue-500" />
                Schedule Interview
              </button>
              <button className="w-full flex items-center gap-3 p-3 text-sm text-gray-700 hover:bg-gray-50 rounded-lg transition-colors">
                <MessageSquare className="w-4 h-4 text-green-500" />
                Send Email
              </button>
              <button
                onClick={() => {
                  setTextStatus("");
                  setShowTextModal(true);
                }}
                disabled={!textingSetting?.enabled || !candidate.phone}
                className="w-full flex items-center gap-3 p-3 text-sm text-gray-700 hover:bg-gray-50 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                title={
                  !textingSetting?.enabled
                    ? "Text messaging must be enabled by a super user in Settings"
                    : !candidate.phone
                    ? "Candidate does not have a phone number"
                    : "Send a text message"
                }
              >
                <Smartphone className="w-4 h-4 text-blue-500" />
                Send Text Message
              </button>
              {!textingSetting?.enabled && (
                <p className="px-3 text-xs text-amber-600">
                  Texting is off. A super user can enable it in Settings.
                </p>
              )}
            </div>
          </div>
        </div>

        {/* Right Column - Tabs */}
        <div className="lg:col-span-2 space-y-6">
          {/* Tabs */}
          <div className="bg-white rounded-xl border border-gray-200 shadow-sm">
            <div className="flex border-b border-gray-200">
              {(["overview", "evaluations", "interviews", "texts"] as const).map((tab) => (
                <button
                  key={tab}
                  onClick={() => setActiveTab(tab)}
                  className={`px-5 py-3 text-sm font-medium capitalize transition-colors ${
                    activeTab === tab
                      ? "text-blue-600 border-b-2 border-blue-600"
                      : "text-gray-500 hover:text-gray-700"
                  }`}
                >
                  {tab}
                </button>
              ))}
            </div>

            <div className="p-5">
              {activeTab === "overview" && (
                <div className="space-y-6">
                  {candidate.summary && (
                    <div>
                      <h3 className="font-semibold text-gray-900 mb-2">Summary</h3>
                      <p className="text-sm text-gray-600">{candidate.summary}</p>
                    </div>
                  )}
                  {candidate.coverLetter && (
                    <div>
                      <h3 className="font-semibold text-gray-900 mb-2">Cover Letter</h3>
                      <div className="text-sm text-gray-600 whitespace-pre-line bg-gray-50 p-4 rounded-lg">
                        {candidate.coverLetter}
                      </div>
                    </div>
                  )}
                </div>
              )}

              {activeTab === "evaluations" && (
                <div>
                  <div className="flex items-center justify-between mb-4">
                    <h3 className="font-semibold text-gray-900">
                      Evaluations ({candidate.evaluations.length})
                    </h3>
                    <button
                      onClick={() => setShowEvalModal(true)}
                      className="flex items-center gap-2 text-sm text-blue-600 hover:text-blue-700"
                    >
                      <Plus className="w-4 h-4" />
                      Add Evaluation
                    </button>
                  </div>
                  {candidate.evaluations.length === 0 ? (
                    <p className="text-sm text-gray-400 text-center py-8">No evaluations yet</p>
                  ) : (
                    <div className="space-y-3">
                      {candidate.evaluations.map((eval_) => (
                        <div
                          key={eval_.id}
                          className="p-4 bg-gray-50 rounded-lg border border-gray-100"
                        >
                          <div className="flex items-center justify-between mb-2">
                            <div className="flex items-center gap-2">
                              <div className="w-7 h-7 bg-purple-100 rounded-full flex items-center justify-center text-xs font-medium text-purple-700">
                                {eval_.evaluator?.name?.[0] || "U"}
                              </div>
                              <span className="text-sm font-medium text-gray-900">
                                {eval_.evaluator?.name || "Unknown"}
                              </span>
                            </div>
                            <div className="flex items-center gap-2">
                              <div className="flex items-center gap-0.5">
                                {[1, 2, 3, 4, 5].map((star) => (
                                  <Star
                                    key={star}
                                    className={`w-3.5 h-3.5 ${
                                      star <= eval_.rating
                                        ? "fill-amber-400 text-amber-400"
                                        : "text-gray-200"
                                    }`}
                                  />
                                ))}
                              </div>
                              <span
                                className={`text-xs px-2 py-0.5 rounded-full font-medium capitalize ${
                                  recommendationColors[eval_.recommendation] || "bg-gray-100 text-gray-600"
                                }`}
                              >
                                {eval_.recommendation.replace("_", " ")}
                              </span>
                            </div>
                          </div>
                          <p className="text-sm text-gray-600">{eval_.feedback}</p>
                          <p className="text-xs text-gray-400 mt-2">
                            {new Date(eval_.createdAt).toLocaleDateString("en-US", {
                              month: "short",
                              day: "numeric",
                              year: "numeric",
                            })}
                          </p>
                        </div>
                      ))}
                    </div>
                  )}
                </div>
              )}

              {activeTab === "interviews" && (
                <div>
                  <div className="flex items-center justify-between mb-4">
                    <h3 className="font-semibold text-gray-900">
                      Interviews ({candidate.interviews.length})
                    </h3>
                    <button
                      onClick={() => setShowInterviewModal(true)}
                      className="flex items-center gap-2 text-sm text-blue-600 hover:text-blue-700"
                    >
                      <Plus className="w-4 h-4" />
                      Schedule Interview
                    </button>
                  </div>
                  {candidate.interviews.length === 0 ? (
                    <p className="text-sm text-gray-400 text-center py-8">No interviews scheduled</p>
                  ) : (
                    <div className="space-y-3">
                      {candidate.interviews.map((interview) => (
                        <div
                          key={interview.id}
                          className="p-4 bg-gray-50 rounded-lg border border-gray-100"
                        >
                          <div className="flex items-center justify-between mb-2">
                            <div>
                              <p className="text-sm font-medium text-gray-900">{interview.title}</p>
                              <p className="text-xs text-gray-500 capitalize">{interview.type} interview</p>
                            </div>
                            <span
                              className={`text-xs px-2 py-0.5 rounded-full font-medium ${
                                interview.status === "scheduled"
                                  ? "bg-blue-100 text-blue-700"
                                  : interview.status === "completed"
                                  ? "bg-green-100 text-green-700"
                                  : "bg-gray-100 text-gray-700"
                              }`}
                            >
                              {interview.status}
                            </span>
                          </div>
                          <div className="flex items-center gap-4 text-xs text-gray-500 mt-2">
                            <span className="flex items-center gap-1">
                              <Calendar className="w-3 h-3" />
                              {new Date(interview.scheduledAt).toLocaleDateString("en-US", {
                                month: "short",
                                day: "numeric",
                                year: "numeric",
                              })}
                            </span>
                            <span>{interview.duration} min</span>
                            {interview.meetingLink && (
                              <a
                                href={interview.meetingLink}
                                target="_blank"
                                className="text-blue-600 hover:underline flex items-center gap-1"
                              >
                                <ExternalLink className="w-3 h-3" />
                                Join Meeting
                              </a>
                            )}
                          </div>
                          {interview.feedback && (
                            <p className="text-sm text-gray-600 mt-2 bg-white p-3 rounded">
                              {interview.feedback}
                            </p>
                          )}
                        </div>
                      ))}
                    </div>
                  )}
                </div>
              )}

              {activeTab === "texts" && (
                <div>
                  <div className="flex items-center justify-between mb-4">
                    <h3 className="font-semibold text-gray-900">
                      Text Messages ({candidate.textMessages?.length || 0})
                    </h3>
                    <button
                      onClick={() => {
                        setTextStatus("");
                        setShowTextModal(true);
                      }}
                      disabled={!textingSetting?.enabled || !candidate.phone}
                      className="flex items-center gap-2 text-sm text-blue-600 hover:text-blue-700 disabled:opacity-50 disabled:cursor-not-allowed"
                    >
                      <Plus className="w-4 h-4" />
                      Send Text
                    </button>
                  </div>

                  {!textingSetting?.enabled && (
                    <div className="p-4 bg-amber-50 border border-amber-200 rounded-lg flex items-start gap-3 mb-4">
                      <AlertCircle className="w-5 h-5 text-amber-600 mt-0.5" />
                      <div>
                        <p className="text-sm font-medium text-amber-800">Text messaging is disabled</p>
                        <p className="text-sm text-amber-700 mt-1">
                          A super user can turn this feature on from Settings → Text Messaging.
                        </p>
                      </div>
                    </div>
                  )}

                  {!candidate.textMessages || candidate.textMessages.length === 0 ? (
                    <p className="text-sm text-gray-400 text-center py-8">No text messages sent yet</p>
                  ) : (
                    <div className="space-y-3">
                      {candidate.textMessages.map((message) => (
                        <div key={message.id} className="p-4 bg-gray-50 rounded-lg border border-gray-100">
                          <div className="flex items-center justify-between mb-2">
                            <div className="flex items-center gap-2 text-sm font-medium text-gray-900">
                              <Smartphone className="w-4 h-4 text-blue-500" />
                              {message.phone}
                            </div>
                            <span
                              className={`text-xs px-2 py-0.5 rounded-full font-medium capitalize ${
                                message.status === "sent"
                                  ? "bg-green-100 text-green-700"
                                  : message.status === "failed"
                                  ? "bg-red-100 text-red-700"
                                  : "bg-gray-100 text-gray-700"
                              }`}
                            >
                              {message.status}
                            </span>
                          </div>
                          <p className="text-sm text-gray-600 whitespace-pre-line">{message.body}</p>
                          <div className="flex items-center justify-between text-xs text-gray-400 mt-3">
                            <span>
                              {new Date(message.createdAt).toLocaleString("en-US", {
                                month: "short",
                                day: "numeric",
                                year: "numeric",
                                hour: "2-digit",
                                minute: "2-digit",
                              })}
                            </span>
                            {message.providerMessageId && <span>{message.providerMessageId}</span>}
                          </div>
                        </div>
                      ))}
                    </div>
                  )}
                </div>
              )}
            </div>
          </div>
        </div>
      </div>
      </div>

      {/* Evaluation Modal */}
      {showEvalModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-xl shadow-xl w-full max-w-md">
            <div className="flex items-center justify-between p-5 border-b border-gray-200">
              <h2 className="text-lg font-semibold text-gray-900">Add Evaluation</h2>
              <button
                onClick={() => setShowEvalModal(false)}
                className="p-2 hover:bg-gray-100 rounded-lg transition-colors"
              >
                <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">Rating</label>
                <div className="flex items-center gap-2">
                  {[1, 2, 3, 4, 5].map((star) => (
                    <button
                      key={star}
                      onClick={() => setNewEval({ ...newEval, rating: star })}
                    >
                      <Star
                        className={`w-6 h-6 ${
                          star <= newEval.rating
                            ? "fill-amber-400 text-amber-400"
                            : "text-gray-200"
                        }`}
                      />
                    </button>
                  ))}
                </div>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Recommendation</label>
                <select
                  value={newEval.recommendation}
                  onChange={(e) => setNewEval({ ...newEval, recommendation: e.target.value })}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm"
                >
                  <option value="strong_yes">Strong Yes</option>
                  <option value="yes">Yes</option>
                  <option value="neutral">Neutral</option>
                  <option value="no">No</option>
                </select>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Feedback</label>
                <textarea
                  value={newEval.feedback}
                  onChange={(e) => setNewEval({ ...newEval, feedback: e.target.value })}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm h-24 resize-none"
                  placeholder="Share your feedback..."
                />
              </div>
            </div>
            <div className="flex items-center justify-end gap-3 p-5 border-t border-gray-200">
              <button
                onClick={() => setShowEvalModal(false)}
                className="px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-100 rounded-lg transition-colors"
              >
                Cancel
              </button>
              <button
                onClick={submitEvaluation}
                className="px-4 py-2 text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 rounded-lg transition-colors"
              >
                Submit Evaluation
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Text Message Modal */}
      {showTextModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-xl shadow-xl w-full max-w-md">
            <div className="flex items-center justify-between p-5 border-b border-gray-200">
              <h2 className="text-lg font-semibold text-gray-900">Send Text Message</h2>
              <button
                onClick={() => setShowTextModal(false)}
                className="p-2 hover:bg-gray-100 rounded-lg transition-colors"
              >
                <X className="w-5 h-5 text-gray-400" />
              </button>
            </div>
            <div className="p-5 space-y-4">
              <div className="p-3 bg-blue-50 rounded-lg border border-blue-100">
                <p className="text-sm font-medium text-blue-900">
                  To: {candidate.firstName} {candidate.lastName}
                </p>
                <p className="text-sm text-blue-700">{candidate.phone || "No phone number on file"}</p>
                <p className="text-xs text-blue-600 mt-1">
                  From: {textingSetting?.fromNumber || "Configured sender number"}
                </p>
              </div>

              {textingSetting?.consentRequired && (
                <div className="p-3 bg-amber-50 rounded-lg border border-amber-200 flex items-start gap-2">
                  <AlertCircle className="w-4 h-4 text-amber-600 mt-0.5" />
                  <p className="text-xs text-amber-700">
                    Confirm the candidate has consented to receive recruiting text messages before sending.
                  </p>
                </div>
              )}

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Message</label>
                <textarea
                  value={textMessage}
                  onChange={(event) => setTextMessage(event.target.value.slice(0, 320))}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm h-28 resize-none"
                  placeholder={`Hi ${candidate.firstName}, this is Sarah from Acme Corp about your application...`}
                />
                <div className="flex items-center justify-between mt-1">
                  <p className="text-xs text-gray-500">Messages are logged to the candidate timeline.</p>
                  <p className="text-xs text-gray-400">{textMessage.length}/320</p>
                </div>
              </div>

              {textStatus && (
                <p className={`text-sm ${textStatus.includes("sent") ? "text-green-600" : "text-red-600"}`}>
                  {textStatus}
                </p>
              )}
            </div>
            <div className="flex items-center justify-end gap-3 p-5 border-t border-gray-200">
              <button
                onClick={() => setShowTextModal(false)}
                className="px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-100 rounded-lg transition-colors"
              >
                Cancel
              </button>
              <button
                onClick={sendTextMessage}
                disabled={!textMessage.trim() || sendingText || !candidate.phone || !textingSetting?.enabled}
                className="flex items-center gap-2 px-4 py-2 text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
              >
                <Send className="w-4 h-4" />
                {sendingText ? "Sending..." : "Send Text"}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Interview Modal */}
      {showInterviewModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-xl shadow-xl w-full max-w-md">
            <div className="flex items-center justify-between p-5 border-b border-gray-200">
              <h2 className="text-lg font-semibold text-gray-900">Schedule Interview</h2>
              <button
                onClick={() => setShowInterviewModal(false)}
                className="p-2 hover:bg-gray-100 rounded-lg transition-colors"
              >
                <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">Title</label>
                <input
                  type="text"
                  value={newInterview.title}
                  onChange={(e) => setNewInterview({ ...newInterview, title: e.target.value })}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm"
                  placeholder="e.g., Technical Interview"
                />
              </div>
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Type</label>
                  <select
                    value={newInterview.type}
                    onChange={(e) => setNewInterview({ ...newInterview, type: e.target.value })}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm"
                  >
                    <option value="phone">Phone</option>
                    <option value="video">Video</option>
                    <option value="onsite">On-site</option>
                    <option value="technical">Technical</option>
                  </select>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Duration (min)</label>
                  <select
                    value={newInterview.duration}
                    onChange={(e) => setNewInterview({ ...newInterview, duration: parseInt(e.target.value) })}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm"
                  >
                    <option value={15}>15 min</option>
                    <option value={30}>30 min</option>
                    <option value={45}>45 min</option>
                    <option value={60}>60 min</option>
                    <option value={90}>90 min</option>
                  </select>
                </div>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Date & Time</label>
                <input
                  type="datetime-local"
                  value={newInterview.scheduledAt}
                  onChange={(e) => setNewInterview({ ...newInterview, scheduledAt: e.target.value })}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Meeting Link</label>
                <input
                  type="text"
                  value={newInterview.meetingLink}
                  onChange={(e) => setNewInterview({ ...newInterview, meetingLink: e.target.value })}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm"
                  placeholder="Zoom/Google Meet link"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Notes</label>
                <textarea
                  value={newInterview.notes}
                  onChange={(e) => setNewInterview({ ...newInterview, notes: e.target.value })}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm h-20 resize-none"
                  placeholder="Interview notes..."
                />
              </div>
            </div>
            <div className="flex items-center justify-end gap-3 p-5 border-t border-gray-200">
              <button
                onClick={() => setShowInterviewModal(false)}
                className="px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-100 rounded-lg transition-colors"
              >
                Cancel
              </button>
              <button
                onClick={scheduleInterview}
                className="px-4 py-2 text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 rounded-lg transition-colors"
              >
                Schedule
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
