/**
 * Interview Detail Page
 * Detailed view and management of a single interview booking
 */

"use client";

import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import {
  ArrowLeft,
  User,
  Mail,
  Phone,
  Briefcase,
  MapPin,
  Calendar,
  Clock,
  Globe,
  Download,
  ExternalLink,
  AlertCircle,
  CheckCircle,
} from "lucide-react";
import InterviewStatusBadge from "@/components/staff/interviews/InterviewStatusBadge";
import InterviewActionButtons from "@/components/staff/interviews/InterviewActionButtons";
import StaffNotesEditor from "@/components/staff/interviews/StaffNotesEditor";
import MeetingLinkForm from "@/components/staff/interviews/MeetingLinkForm";
import {
  InterviewBookingListItem,
  InterviewStatus,
  MeetingPlatform,
} from "@/lib/types/interview.types";

interface InterviewDetailPageProps {
  params: {
    id: string;
  };
}

export default function InterviewDetailPage({
  params,
}: InterviewDetailPageProps) {
  const router = useRouter();
  const [booking, setBooking] = useState<InterviewBookingListItem | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [showMeetingLinkForm, setShowMeetingLinkForm] = useState(false);
  const [isUpdating, setIsUpdating] = useState(false);

  useEffect(() => {
    fetchBookingDetails();
  }, [params.id]);

  const fetchBookingDetails = async () => {
    setIsLoading(true);
    setError(null);

    try {
      const response = await fetch(
        `/api/staff/dashboard/careers/interviews/${params.id}`,
      );
      if (!response.ok) {
        throw new Error("Failed to fetch booking details");
      }

      const data = await response.json();
      setBooking(data.booking);
    } catch (err: any) {
      setError(err.message || "Failed to load interview booking");
    } finally {
      setIsLoading(false);
    }
  };

  const handleUpdateBooking = async (updates: any) => {
    setIsUpdating(true);

    try {
      const response = await fetch(
        `/api/staff/dashboard/careers/interviews/${params.id}`,
        {
          method: "PATCH",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(updates),
        },
      );

      if (!response.ok) {
        const result = await response.json();
        throw new Error(result.error || "Failed to update booking");
      }

      await fetchBookingDetails();
      return true;
    } catch (err: any) {
      alert(err.message || "Failed to update booking");
      return false;
    } finally {
      setIsUpdating(false);
    }
  };

  const handleConfirm = async () => {
    if (!booking?.meetingLink) {
      alert("Please add a meeting link before confirming");
      setShowMeetingLinkForm(true);
      return;
    }

    const confirmed = confirm(
      `Confirm this interview?\n\nThis will send a confirmation email to ${booking.applicantEmail} with the meeting details.`,
    );

    if (!confirmed) return;

    const success = await handleUpdateBooking({
      status: InterviewStatus.CONFIRMED,
      confirmedDate: booking.preferredDate,
      confirmedTime: booking.preferredTime,
    });

    if (success) {
      alert("Interview confirmed! Confirmation email sent to applicant.");
    }
  };

  const handleCancel = async () => {
    const reason = prompt(
      "Please provide a cancellation reason (will be sent to applicant):",
    );
    if (!reason) return;

    const success = await handleUpdateBooking({
      status: InterviewStatus.CANCELLED,
      cancellationReason: reason,
    });

    if (success) {
      alert("Interview cancelled. Notification email sent to applicant.");
    }
  };

  const handleComplete = async () => {
    const confirmed = confirm("Mark this interview as completed?");
    if (!confirmed) return;

    const success = await handleUpdateBooking({
      status: InterviewStatus.COMPLETED,
    });

    if (success) {
      alert("Interview marked as completed!");
    }
  };

  const handleSaveMeetingLink = async (data: {
    meetingLink: string;
    meetingPlatform: MeetingPlatform;
    meetingId?: string;
    meetingPassword?: string;
  }) => {
    await handleUpdateBooking(data);
    setShowMeetingLinkForm(false);
  };

  const handleSaveNotes = async (notes: string) => {
    await handleUpdateBooking({ staffNotes: notes });
  };

  const handleDownloadCV = async () => {
    if (!booking?.applicantCvPath) {
      alert("CV not available");
      return;
    }

    try {
      const response = await fetch(
        `/api/staff/dashboard/careers/applications/${booking.applicationId}/download-cv`,
      );
      if (!response.ok) throw new Error("Failed to download CV");

      const blob = await response.blob();
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = `${booking.applicantName.replace(/\s+/g, "_")}_CV.pdf`;
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a);
    } catch (error) {
      alert("Failed to download CV");
    }
  };

  if (isLoading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="text-center">
          <div className="inline-block w-12 h-12 border-4 border-brand-green border-t-transparent rounded-full animate-spin" />
          <p className="mt-4 text-gray-600 font-semibold">
            Loading interview details...
          </p>
        </div>
      </div>
    );
  }

  if (error || !booking) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="text-center">
          <AlertCircle className="w-16 h-16 text-red-500 mx-auto mb-4" />
          <h2 className="text-2xl font-bold text-gray-900 mb-2">Error</h2>
          <p className="text-gray-600 mb-6">{error || "Booking not found"}</p>
          <button
            onClick={() => router.push("/staff/dashboard/careers/interviews")}
            className="px-6 py-3 bg-brand-green text-white font-semibold rounded-lg hover:bg-green-600"
          >
            Back to Bookings
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-6 max-w-6xl mx-auto">
      {/* Header */}
      <div className="flex items-center gap-4">
        <button
          onClick={() => router.push("/staff/dashboard/careers/interviews")}
          className="p-2 hover:bg-gray-100 rounded-lg transition-all"
          aria-label="Back to interview list"
        >
          <ArrowLeft className="w-6 h-6 text-gray-600" />
        </button>
        <div className="flex-1">
          <h1 className="text-3xl font-bold text-brand-ink">
            {booking.applicantName}
          </h1>
          <p className="text-sm text-gray-600 mt-1">
            Interview for {booking.jobTitle || "N/A"}
          </p>
        </div>
        <InterviewStatusBadge status={booking.status} />
      </div>

      {/* Main Content Grid */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Left Column - Main Info */}
        <div className="lg:col-span-2 space-y-6">
          {/* Applicant Information */}
          <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
            <h2 className="text-xl font-bold text-brand-ink mb-4 flex items-center gap-2">
              <User className="w-5 h-5 text-brand-green" />
              Applicant Information
            </h2>

            <div className="space-y-3">
              <div className="flex items-center gap-3">
                <Mail className="w-5 h-5 text-gray-400" />
                <a
                  href={`mailto:${booking.applicantEmail}`}
                  className="text-brand-green hover:underline"
                >
                  {booking.applicantEmail}
                </a>
              </div>

              {booking.applicantPhone && (
                <div className="flex items-center gap-3">
                  <Phone className="w-5 h-5 text-gray-400" />
                  <a
                    href={`tel:${booking.applicantPhone}`}
                    className="text-brand-green hover:underline"
                  >
                    {booking.applicantPhone}
                  </a>
                </div>
              )}

              {booking.applicantCvPath && (
                <div className="pt-3 border-t border-gray-200">
                  <button
                    onClick={handleDownloadCV}
                    className="inline-flex items-center gap-2 px-4 py-2 bg-blue-600 text-white font-semibold rounded-lg hover:bg-blue-700 transition-all"
                  >
                    <Download className="w-4 h-4" />
                    Download CV
                  </button>
                </div>
              )}
            </div>
          </div>

          {/* Job Details */}
          <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
            <h2 className="text-xl font-bold text-brand-ink mb-4 flex items-center gap-2">
              <Briefcase className="w-5 h-5 text-brand-green" />
              Job Details
            </h2>

            <div className="space-y-2">
              <div>
                <p className="text-sm font-medium text-gray-600">Position</p>
                <p className="text-lg font-semibold text-gray-900">
                  {booking.jobTitle || "N/A"}
                </p>
              </div>

              {booking.jobTitleAr && (
                <div>
                  <p className="text-sm font-medium text-gray-600">
                    Position (Arabic)
                  </p>
                  <p className="text-lg font-semibold text-gray-900">
                    {booking.jobTitleAr}
                  </p>
                </div>
              )}
            </div>
          </div>

          {/* Interview Booking Details */}
          <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
            <h2 className="text-xl font-bold text-brand-ink mb-4 flex items-center gap-2">
              <Calendar className="w-5 h-5 text-brand-green" />
              Interview Booking Details
            </h2>

            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <div>
                <p className="text-sm font-medium text-gray-600 mb-1">
                  Preferred Date
                </p>
                <div className="flex items-center gap-2 text-gray-900 font-semibold">
                  <Calendar className="w-4 h-4 text-gray-400" />
                  {new Date(booking.preferredDate).toLocaleDateString("en-US", {
                    weekday: "long",
                    month: "long",
                    day: "numeric",
                    year: "numeric",
                  })}
                </div>
              </div>

              <div>
                <p className="text-sm font-medium text-gray-600 mb-1">
                  Preferred Time
                </p>
                <div className="flex items-center gap-2 text-gray-900 font-semibold">
                  <Clock className="w-4 h-4 text-gray-400" />
                  {booking.preferredTime}
                </div>
              </div>

              <div>
                <p className="text-sm font-medium text-gray-600 mb-1">
                  Timezone
                </p>
                <div className="flex items-center gap-2 text-gray-900 font-semibold">
                  <Globe className="w-4 h-4 text-gray-400" />
                  {booking.timezone}
                </div>
              </div>

              <div>
                <p className="text-sm font-medium text-gray-600 mb-1">
                  Duration
                </p>
                <div className="flex items-center gap-2 text-gray-900 font-semibold">
                  <Clock className="w-4 h-4 text-gray-400" />
                  {booking.durationMinutes} minutes
                </div>
              </div>
            </div>

            {booking.applicantNotes && (
              <div className="mt-4 pt-4 border-t border-gray-200">
                <p className="text-sm font-medium text-gray-600 mb-2">
                  Applicant Notes
                </p>
                <div className="bg-gray-50 rounded-lg p-3 text-sm text-gray-700">
                  {booking.applicantNotes}
                </div>
              </div>
            )}
          </div>

          {/* Meeting Details */}
          {!showMeetingLinkForm && booking.meetingLink && (
            <div className="bg-green-50 rounded-xl shadow-sm border border-green-200 p-6">
              <div className="flex items-center justify-between mb-4">
                <h2 className="text-xl font-bold text-green-900 flex items-center gap-2">
                  <CheckCircle className="w-5 h-5 text-green-600" />
                  Meeting Details
                </h2>
                <button
                  onClick={() => setShowMeetingLinkForm(true)}
                  className="text-sm text-green-700 hover:text-green-800 font-semibold"
                >
                  Edit
                </button>
              </div>

              <div className="space-y-3">
                <div>
                  <p className="text-sm font-medium text-green-700 mb-1">
                    Platform
                  </p>
                  <p className="text-green-900 font-semibold capitalize">
                    {booking.meetingPlatform || "Not specified"}
                  </p>
                </div>

                <div>
                  <p className="text-sm font-medium text-green-700 mb-1">
                    Meeting Link
                  </p>
                  <a
                    href={booking.meetingLink}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="inline-flex items-center gap-2 text-green-700 hover:text-green-800 font-semibold hover:underline"
                  >
                    {booking.meetingLink}
                    <ExternalLink className="w-4 h-4" />
                  </a>
                </div>

                {booking.meetingId && (
                  <div>
                    <p className="text-sm font-medium text-green-700 mb-1">
                      Meeting ID
                    </p>
                    <p className="text-green-900 font-mono">
                      {booking.meetingId}
                    </p>
                  </div>
                )}

                {booking.meetingPassword && (
                  <div>
                    <p className="text-sm font-medium text-green-700 mb-1">
                      Password
                    </p>
                    <p className="text-green-900 font-mono">
                      {booking.meetingPassword}
                    </p>
                  </div>
                )}
              </div>
            </div>
          )}

          {/* Meeting Link Form */}
          {showMeetingLinkForm && (
            <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
              <h2 className="text-xl font-bold text-brand-ink mb-4">
                {booking.meetingLink ? "Edit Meeting Link" : "Add Meeting Link"}
              </h2>
              <MeetingLinkForm
                initialLink={booking.meetingLink || undefined}
                initialPlatform={booking.meetingPlatform || undefined}
                initialMeetingId={booking.meetingId || undefined}
                initialPassword={booking.meetingPassword || undefined}
                onSave={handleSaveMeetingLink}
              />
              <button
                onClick={() => setShowMeetingLinkForm(false)}
                className="mt-4 text-sm text-gray-600 hover:text-gray-900"
              >
                Cancel
              </button>
            </div>
          )}

          {/* Staff Notes */}
          <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
            <h2 className="text-xl font-bold text-brand-ink mb-4">
              Staff Notes
            </h2>
            <StaffNotesEditor
              initialValue={booking.staffNotes || ""}
              onSave={handleSaveNotes}
              placeholder="Add internal notes about this interview..."
            />
          </div>
        </div>

        {/* Right Column - Timeline & Actions */}
        <div className="space-y-6">
          {/* Actions */}
          <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
            <h2 className="text-lg font-bold text-brand-ink mb-4">Actions</h2>
            <InterviewActionButtons
              status={booking.status}
              hasMeetingLink={!!booking.meetingLink}
              isLoading={isUpdating}
              onConfirm={handleConfirm}
              onAddMeetingLink={() => setShowMeetingLinkForm(true)}
              onCancel={handleCancel}
              onComplete={handleComplete}
            />
          </div>

          {/* Application Timeline */}
          <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
            <h2 className="text-lg font-bold text-brand-ink mb-4">Timeline</h2>
            <div className="space-y-4">
              {booking.submittedAt && (
                <div className="flex gap-3">
                  <div className="flex-shrink-0 w-2 h-2 bg-blue-500 rounded-full mt-2" />
                  <div>
                    <p className="text-sm font-semibold text-gray-900">
                      Application Submitted
                    </p>
                    <p className="text-xs text-gray-500">
                      {new Date(booking.submittedAt).toLocaleString()}
                    </p>
                  </div>
                </div>
              )}

              <div className="flex gap-3">
                <div className="flex-shrink-0 w-2 h-2 bg-yellow-500 rounded-full mt-2" />
                <div>
                  <p className="text-sm font-semibold text-gray-900">
                    Interview Requested
                  </p>
                  <p className="text-xs text-gray-500">
                    {new Date(booking.createdAt).toLocaleString()}
                  </p>
                </div>
              </div>

              {booking.confirmedAt && (
                <div className="flex gap-3">
                  <div className="flex-shrink-0 w-2 h-2 bg-green-500 rounded-full mt-2" />
                  <div>
                    <p className="text-sm font-semibold text-gray-900">
                      Interview Confirmed
                    </p>
                    <p className="text-xs text-gray-500">
                      {new Date(booking.confirmedAt).toLocaleString()}
                    </p>
                    {booking.confirmedBy && (
                      <p className="text-xs text-gray-500">
                        by {booking.confirmedBy}
                      </p>
                    )}
                  </div>
                </div>
              )}

              {booking.cancelledAt && (
                <div className="flex gap-3">
                  <div className="flex-shrink-0 w-2 h-2 bg-red-500 rounded-full mt-2" />
                  <div>
                    <p className="text-sm font-semibold text-gray-900">
                      Interview Cancelled
                    </p>
                    <p className="text-xs text-gray-500">
                      {new Date(booking.cancelledAt).toLocaleString()}
                    </p>
                    {booking.cancellationReason && (
                      <p className="text-xs text-gray-600 mt-1 italic">
                        {booking.cancellationReason}
                      </p>
                    )}
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
