/**
 * ApplicationDetailModal Component
 * View full application details and update status
 */

"use client";

import { useState, useEffect } from "react";
import {
  X,
  Download,
  Mail,
  Phone,
  ExternalLink,
  Calendar,
  Save,
  AlertCircle,
  Send,
} from "lucide-react";

interface Application {
  id: string;
  job_id: string;
  applicant_name: string;
  applicant_email: string;
  applicant_phone: string;
  applicant_linkedin: string | null;
  applicant_portfolio: string | null;
  cover_note: string | null;
  status: string;
  reviewed_at: string | null;
  reviewed_by: string | null;
  interview_link: string | null;
  interview_scheduled_at: string | null;
  rejection_reason: string | null;
  hired_at: string | null;
  internal_notes: string | null;
  submitted_at: string;
  job?: {
    title_translations: { ar: string; en: string };
    department_label: { ar: string; en: string };
  };
}

interface ApplicationDetailModalProps {
  isOpen: boolean;
  application: Application;
  canEdit?: boolean;
  onClose: () => void;
  onUpdated: () => void;
}

export default function ApplicationDetailModal({
  isOpen,
  application,
  canEdit,
  onClose,
  onUpdated,
}: ApplicationDetailModalProps) {
  const [isUpdating, setIsUpdating] = useState(false);
  const [isSendingInvite, setIsSendingInvite] = useState(false);
  const [newStatus, setNewStatus] = useState(application.status);
  const [interviewLink, setInterviewLink] = useState(
    application.interview_link || "",
  );
  const [interviewDate, setInterviewDate] = useState(
    application.interview_scheduled_at
      ? application.interview_scheduled_at.split("T")[0]
      : "",
  );
  const [rejectionReason, setRejectionReason] = useState(
    application.rejection_reason || "",
  );
  const [internalNotes, setInternalNotes] = useState(
    application.internal_notes || "",
  );

  useEffect(() => {
    setNewStatus(application.status);
    setInterviewLink(application.interview_link || "");
    setInterviewDate(
      application.interview_scheduled_at
        ? application.interview_scheduled_at.split("T")[0]
        : "",
    );
    setRejectionReason(application.rejection_reason || "");
    setInternalNotes(application.internal_notes || "");
  }, [application]);

  if (!isOpen) return null;

  const handleDownloadCV = async () => {
    try {
      const response = await fetch(
        `/api/staff/applications/${application.id}/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 = `${application.applicant_name.replace(/\s+/g, "_")}_CV.pdf`;
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a);
    } catch (error) {
      console.error("Error downloading CV:", error);
      alert("Failed to download CV");
    }
  };

  const handleUpdateStatus = async () => {
    if (!canEdit) return;

    // Validation
    if (newStatus === "interview_scheduled" && !interviewLink) {
      alert("Please provide an interview link");
      return;
    }

    if (newStatus === "rejected" && !rejectionReason) {
      alert("Please provide a rejection reason (internal use only)");
      return;
    }

    setIsUpdating(true);

    try {
      const updateData: any = {
        status: newStatus,
        internalNotes,
      };

      if (newStatus === "interview_scheduled") {
        updateData.interviewLink = interviewLink;
        if (interviewDate) {
          updateData.interviewScheduledAt = new Date(
            interviewDate,
          ).toISOString();
        }
      }

      if (newStatus === "rejected") {
        updateData.rejectionReason = rejectionReason;
      }

      const response = await fetch(
        `/api/staff/applications/${application.id}`,
        {
          method: "PATCH",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(updateData),
        },
      );

      const result = await response.json();

      if (!response.ok) {
        throw new Error(result.error || "Failed to update status");
      }

      alert(
        "Application status updated successfully! Email notification sent to applicant.",
      );
      onUpdated();
    } catch (error: any) {
      console.error("Error updating application:", error);
      alert(error.message || "Failed to update application");
    } finally {
      setIsUpdating(false);
    }
  };

  const getStatusBadge = (status: string) => {
    const badges = {
      new: "bg-blue-100 text-blue-700 border-blue-300",
      shortlisted: "bg-yellow-100 text-yellow-700 border-yellow-300",
      interview_scheduled: "bg-purple-100 text-purple-700 border-purple-300",
      hired: "bg-green-100 text-green-700 border-green-300",
      rejected: "bg-red-100 text-red-700 border-red-300",
    };

    return (
      <span
        className={`px-3 py-1 rounded-full text-xs font-semibold border ${badges[status as keyof typeof badges] || badges.new}`}
      >
        {status.replace("_", " ").toUpperCase()}
      </span>
    );
  };

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4 overflow-y-auto">
      <div className="bg-white rounded-2xl shadow-2xl max-w-4xl w-full max-h-[90vh] overflow-y-auto">
        {/* Header */}
        <div className="sticky top-0 bg-white border-b border-gray-200 px-6 py-4 flex items-center justify-between z-10">
          <div>
            <h2 className="text-2xl font-bold text-brand-ink">
              {application.applicant_name}
            </h2>
            <p className="text-sm text-gray-600 mt-1">
              Applied for: {application.job?.title_translations?.en || "N/A"}
            </p>
          </div>
          <button
            type="button"
            aria-label="Close"
            onClick={onClose}
            className="p-2 text-gray-500 hover:text-gray-700 hover:bg-gray-100 rounded-lg transition-all"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        <div className="p-6 space-y-6">
          {/* Current Status */}
          <div className="bg-gray-50 rounded-lg p-4 border border-gray-200">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-gray-600">
                  Current Status
                </p>
                <div className="mt-2">{getStatusBadge(application.status)}</div>
              </div>
              {application.reviewed_at && (
                <div className="text-right">
                  <p className="text-xs text-gray-500">Last updated</p>
                  <p className="text-sm font-medium text-gray-700">
                    {new Date(application.reviewed_at).toLocaleDateString(
                      "en-US",
                      {
                        month: "short",
                        day: "numeric",
                        year: "numeric",
                        hour: "2-digit",
                        minute: "2-digit",
                      },
                    )}
                  </p>
                </div>
              )}
            </div>
          </div>

          {/* Contact Information */}
          <div>
            <h3 className="text-lg font-bold text-brand-ink mb-3">
              Contact Information
            </h3>
            <div className="space-y-3">
              <div className="flex items-center gap-3">
                <Mail className="w-5 h-5 text-gray-400" />
                <a
                  href={`mailto:${application.applicant_email}`}
                  className="text-brand-green hover:underline"
                >
                  {application.applicant_email}
                </a>
              </div>
              <div className="flex items-center gap-3">
                <Phone className="w-5 h-5 text-gray-400" />
                <a
                  href={`tel:${application.applicant_phone}`}
                  className="text-brand-green hover:underline"
                >
                  {application.applicant_phone}
                </a>
              </div>
              {application.applicant_linkedin && (
                <div className="flex items-center gap-3">
                  <ExternalLink className="w-5 h-5 text-gray-400" />
                  <a
                    href={application.applicant_linkedin}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="text-brand-green hover:underline"
                  >
                    LinkedIn Profile
                  </a>
                </div>
              )}
              {application.applicant_portfolio && (
                <div className="flex items-center gap-3">
                  <ExternalLink className="w-5 h-5 text-gray-400" />
                  <a
                    href={application.applicant_portfolio}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="text-brand-green hover:underline"
                  >
                    Portfolio
                  </a>
                </div>
              )}
            </div>
          </div>

          {/* Cover Letter */}
          {application.cover_note && (
            <div>
              <h3 className="text-lg font-bold text-brand-ink mb-3">
                Cover Letter
              </h3>
              <div className="bg-gray-50 rounded-lg p-4 border border-gray-200">
                <p className="text-sm text-gray-700 whitespace-pre-wrap">
                  {application.cover_note}
                </p>
              </div>
            </div>
          )}

          {/* Resume Download */}
          <div>
            <h3 className="text-lg font-bold text-brand-ink mb-3">Resume</h3>
            <button
              onClick={handleDownloadCV}
              className="inline-flex items-center gap-2 px-6 py-3 bg-blue-600 text-white font-semibold rounded-lg hover:bg-blue-700 transition-all"
            >
              <Download className="w-5 h-5" />
              Download CV
            </button>
          </div>

          {/* Status Update Section (ADMIN only) */}
          {canEdit && (
            <div className="border-t border-gray-200 pt-6">
              <h3 className="text-lg font-bold text-brand-ink mb-4">
                Update Application Status
              </h3>

              <div className="space-y-4">
                {/* Status Selector */}
                <div>
                  <label className="block text-sm font-semibold text-gray-700 mb-2">
                    New Status
                  </label>
                  <select
                    value={newStatus}
                    onChange={(e) => setNewStatus(e.target.value)}
                    className="w-full px-4 py-3 border-2 border-gray-200 rounded-lg focus:ring-2 focus:ring-brand-green focus:border-brand-green"
                  >
                    <option value="new">New</option>
                    <option value="shortlisted">Shortlisted</option>
                    <option value="interview_scheduled">
                      Interview Scheduled
                    </option>
                    <option value="hired">Hired</option>
                    <option value="rejected">Rejected</option>
                  </select>
                </div>

                {/* Conditional fields based on status */}
                {newStatus === "interview_scheduled" && (
                  <>
                    <div>
                      <label className="block text-sm font-semibold text-gray-700 mb-2">
                        Interview Link (Zoom/Google Meet){" "}
                        <span className="text-red-500">*</span>
                      </label>
                      <input
                        type="url"
                        value={interviewLink}
                        onChange={(e) => setInterviewLink(e.target.value)}
                        placeholder="https://zoom.us/j/..."
                        className="w-full px-4 py-3 border-2 border-gray-200 rounded-lg focus:ring-2 focus:ring-brand-green focus:border-brand-green"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-semibold text-gray-700 mb-2">
                        Interview Date/Time
                      </label>
                      <input
                        type="datetime-local"
                        value={interviewDate}
                        onChange={(e) => setInterviewDate(e.target.value)}
                        className="w-full px-4 py-3 border-2 border-gray-200 rounded-lg focus:ring-2 focus:ring-brand-green focus:border-brand-green"
                      />
                    </div>
                  </>
                )}

                {newStatus === "rejected" && (
                  <div>
                    <label className="block text-sm font-semibold text-gray-700 mb-2">
                      Rejection Reason (Internal){" "}
                      <span className="text-red-500">*</span>
                    </label>
                    <textarea
                      value={rejectionReason}
                      onChange={(e) => setRejectionReason(e.target.value)}
                      placeholder="Not enough experience, wrong skill set, etc."
                      rows={3}
                      className="w-full px-4 py-3 border-2 border-gray-200 rounded-lg focus:ring-2 focus:ring-brand-green focus:border-brand-green"
                    />
                    <p className="mt-1 text-xs text-gray-500">
                      For internal records only (not sent to applicant)
                    </p>
                  </div>
                )}

                {/* Internal Notes */}
                <div>
                  <label className="block text-sm font-semibold text-gray-700 mb-2">
                    Internal Notes
                  </label>
                  <textarea
                    value={internalNotes}
                    onChange={(e) => setInternalNotes(e.target.value)}
                    placeholder="Add notes for team collaboration..."
                    rows={4}
                    className="w-full px-4 py-3 border-2 border-gray-200 rounded-lg focus:ring-2 focus:ring-brand-green focus:border-brand-green"
                  />
                </div>

                {/* Email Notification Warning */}
                {newStatus !== application.status && (
                  <div className="bg-amber-50 border border-amber-200 rounded-lg p-4 flex items-start gap-3">
                    <AlertCircle className="w-5 h-5 text-amber-600 flex-shrink-0 mt-0.5" />
                    <div className="text-sm text-amber-800">
                      <p className="font-semibold">
                        Email notification will be sent
                      </p>
                      <p className="mt-1">
                        Changing status to{" "}
                        <strong>{newStatus.replace("_", " ")}</strong> will
                        automatically send an email to{" "}
                        <strong>{application.applicant_email}</strong>
                      </p>
                    </div>
                  </div>
                )}

                {/* Update Button */}
                <button
                  onClick={handleUpdateStatus}
                  disabled={isUpdating || newStatus === application.status}
                  className="w-full px-6 py-3 bg-brand-green text-white font-semibold rounded-lg hover:bg-green-600 transition-all disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2"
                >
                  <Save className="w-5 h-5" />
                  {isUpdating ? "Updating..." : "Update Status & Send Email"}
                </button>
              </div>
            </div>
          )}

          {/* Send Interview Invite (ADMIN only) */}
          {canEdit &&
            (application.status === "shortlisted" ||
              application.status === "new") && (
              <div className="border-t border-gray-200 pt-6">
                <div className="bg-blue-50 border border-blue-200 rounded-lg p-6">
                  <h3 className="text-lg font-bold text-blue-900 mb-2 flex items-center gap-2">
                    <Send className="w-5 h-5" />
                    Send Interview Invitation
                  </h3>
                  <p className="text-sm text-blue-700 mb-4">
                    Send a secure interview booking link to the applicant. They
                    will have 3 days to schedule their preferred interview time.
                  </p>
                  <button
                    onClick={async () => {
                      const confirmed = confirm(
                        `Send interview invitation to ${application.applicant_email}?\n\n` +
                          `This will:\n` +
                          `• Generate a secure 3-day booking link\n` +
                          `• Send invitation email to applicant\n` +
                          `• Update application status to "interview_scheduled"`,
                      );

                      if (!confirmed) return;

                      setIsSendingInvite(true);

                      try {
                        const response = await fetch(
                          `/api/staff/dashboard/careers/applications/${application.id}/send-invite`,
                          {
                            method: "POST",
                            headers: { "Content-Type": "application/json" },
                          },
                        );

                        const result = await response.json();

                        if (!response.ok) {
                          throw new Error(
                            result.error || "Failed to send invite",
                          );
                        }

                        alert(
                          "Interview invitation sent successfully!\n\nThe applicant will receive an email with a booking link.",
                        );
                        onUpdated();
                      } catch (error: any) {
                        alert(
                          error.message ||
                            "Failed to send interview invitation",
                        );
                      } finally {
                        setIsSendingInvite(false);
                      }
                    }}
                    disabled={isSendingInvite}
                    className="w-full px-6 py-3 bg-blue-600 text-white font-semibold rounded-lg hover:bg-blue-700 transition-all disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2"
                  >
                    <Send className="w-5 h-5" />
                    {isSendingInvite
                      ? "Sending Invitation..."
                      : "Send Interview Invitation"}
                  </button>
                </div>
              </div>
            )}

          {/* Application Timeline */}
          <div className="border-t border-gray-200 pt-6">
            <h3 className="text-lg font-bold text-brand-ink mb-4">Timeline</h3>
            <div className="space-y-3">
              <div className="flex items-start gap-3">
                <Calendar className="w-5 h-5 text-gray-400 mt-0.5" />
                <div>
                  <p className="text-sm font-medium text-gray-900">Applied</p>
                  <p className="text-xs text-gray-500">
                    {new Date(application.submitted_at).toLocaleString(
                      "en-US",
                      {
                        month: "long",
                        day: "numeric",
                        year: "numeric",
                        hour: "2-digit",
                        minute: "2-digit",
                      },
                    )}
                  </p>
                </div>
              </div>

              {application.reviewed_at && (
                <div className="flex items-start gap-3">
                  <Calendar className="w-5 h-5 text-gray-400 mt-0.5" />
                  <div>
                    <p className="text-sm font-medium text-gray-900">
                      Last Reviewed
                    </p>
                    <p className="text-xs text-gray-500">
                      {new Date(application.reviewed_at).toLocaleString(
                        "en-US",
                        {
                          month: "long",
                          day: "numeric",
                          year: "numeric",
                          hour: "2-digit",
                          minute: "2-digit",
                        },
                      )}
                    </p>
                  </div>
                </div>
              )}

              {application.hired_at && (
                <div className="flex items-start gap-3">
                  <Calendar className="w-5 h-5 text-green-600 mt-0.5" />
                  <div>
                    <p className="text-sm font-medium text-green-700">Hired</p>
                    <p className="text-xs text-gray-500">
                      {new Date(application.hired_at).toLocaleString("en-US", {
                        month: "long",
                        day: "numeric",
                        year: "numeric",
                      })}
                    </p>
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>

        {/* Footer */}
        <div className="sticky bottom-0 bg-gray-50 border-t border-gray-200 px-6 py-4">
          <button
            onClick={onClose}
            className="w-full px-6 py-3 border-2 border-gray-300 text-gray-700 font-semibold rounded-lg hover:bg-gray-100 transition-all"
          >
            Close
          </button>
        </div>
      </div>
    </div>
  );
}
