"use client";

import { useMemo, useState } from "react";
import { getCSRFToken } from "@/lib/csrf-client";
import type { JobListing } from "@/lib/careers";
import type { careersEn } from "@/lib/config/translations/modules/pages/careers.en";

type CareersTranslations = typeof careersEn;
type Lang = "ar" | "en";

interface CareersClientProps {
  lang: Lang;
  copy: CareersTranslations;
  jobs: JobListing[];
}

const MAX_FILE_SIZE_BYTES = 10 * 1024 * 1024; // 10MB
const ACCEPTED_MIME_TYPES = ["application/pdf"];

export function CareersClient({ lang, copy, jobs }: CareersClientProps) {
  const [selectedJob, setSelectedJob] = useState<JobListing | null>(null);
  const [formData, setFormData] = useState({
    fullName: "",
    email: "",
    phone: "",
    coverLetter: "",
    linkedIn: "",
    portfolio: "",
  });
  const [resumeFile, setResumeFile] = useState<File | null>(null);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [submitStatus, setSubmitStatus] = useState<
    "idle" | "success" | "error"
  >("idle");

  const isRtl = lang === "ar";
  const hasJobs = jobs.length > 0;

  const sortedJobs = useMemo(
    () =>
      [...jobs].sort(
        (a, b) =>
          new Date(b.openingAt).getTime() - new Date(a.openingAt).getTime(),
      ),
    [jobs],
  );

  const normaliseArray = (
    record: Record<Lang, string[]>,
    language: Lang,
  ): string[] => {
    const primary = record?.[language];
    if (Array.isArray(primary) && primary.length > 0) {
      return primary;
    }
    const fallbackLang: Lang = language === "en" ? "ar" : "en";
    const fallback = record?.[fallbackLang];
    return Array.isArray(fallback) ? fallback : [];
  };

  const normaliseString = (
    record: Record<Lang, string>,
    language: Lang,
  ): string => {
    const value = record?.[language];
    if (typeof value === "string" && value.trim().length > 0) {
      return value;
    }
    const fallbackLang: Lang = language === "en" ? "ar" : "en";
    const fallbackValue = record?.[fallbackLang];
    return typeof fallbackValue === "string" ? fallbackValue : "";
  };

  const handleApplyClick = (job: JobListing) => {
    setSelectedJob(job);
    setSubmitStatus("idle");
  };

  const handleCloseModal = () => {
    setSelectedJob(null);
    setFormData({
      fullName: "",
      email: "",
      phone: "",
      coverLetter: "",
      linkedIn: "",
      portfolio: "",
    });
    setResumeFile(null);
    setSubmitStatus("idle");
  };

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) {
      return;
    }

    if (!ACCEPTED_MIME_TYPES.includes(file.type)) {
      const message =
        copy.applicationFormResumeTypeError ??
        (lang === "ar" ? "يجب رفع ملف PDF فقط" : "Please upload a PDF file");
      alert(message);
      return;
    }

    if (file.size > MAX_FILE_SIZE_BYTES) {
      const message =
        copy.applicationFormResumeSizeError ??
        (lang === "ar"
          ? "يجب ألا يتجاوز حجم الملف 10 ميجابايت"
          : "File size must be less than 10MB");
      alert(message);
      return;
    }

    setResumeFile(file);
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!selectedJob) return;

    setIsSubmitting(true);
    setSubmitStatus("idle");

    try {
      const formDataToSend = new FormData();
      formDataToSend.append("jobId", selectedJob.id);
      formDataToSend.append("jobTitle", selectedJob.title[lang]);
      formDataToSend.append("fullName", formData.fullName);
      formDataToSend.append("email", formData.email);
      formDataToSend.append("phone", formData.phone);
      formDataToSend.append("coverLetter", formData.coverLetter);
      formDataToSend.append("linkedIn", formData.linkedIn);
      formDataToSend.append("portfolio", formData.portfolio);
      formDataToSend.append("lang", lang);

      if (resumeFile) {
        formDataToSend.append("resume", resumeFile);
      }

      const csrfToken = getCSRFToken() ?? "";
      const response = await fetch("/api/apply-job", {
        method: "POST",
        headers: { "x-csrf-token": csrfToken },
        body: formDataToSend,
        credentials: "include",
      });

      if (!response.ok) {
        throw new Error("Submission failed");
      }

      setSubmitStatus("success");
      setTimeout(() => {
        handleCloseModal();
      }, 3000);
    } catch (error) {
      console.error("Application submission error:", error);
      setSubmitStatus("error");
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <>
      {/* Job Listings */}
      <div className="grid gap-6 md:gap-8">
        {!hasJobs && (
          <div className="bg-gradient-to-br from-slate-50 to-white dark:from-slate-800 dark:to-slate-900 rounded-2xl p-8 text-center border border-slate-200 dark:border-slate-700">
            <h3 className="text-2xl font-bold text-slate-900 dark:text-white mb-4">
              {copy.openPositionsNone}
            </h3>
            <p className="text-neutral-600 dark:text-neutral-400">
              {copy.openPositionsEmptyCta ?? copy.openPositionsSubtitle}
            </p>
          </div>
        )}

        {sortedJobs.map((job) => {
          const jobTitle = job.title[lang];
          const responsibilities = normaliseArray(job.responsibilities, lang);
          const requirements = normaliseArray(job.requirements, lang);
          const niceToHave = normaliseArray(job.niceToHave, lang);
          const benefits = normaliseArray(job.benefits, lang);
          const skills = normaliseArray(job.skills, lang);
          const workday = normaliseArray(job.workdayExpectations, lang);
          const applicationInstructions = normaliseString(
            job.applicationInstructions,
            lang,
          );

          return (
            <div
              key={job.id}
              className="group bg-gradient-to-br from-slate-50 to-white dark:from-slate-800 dark:to-slate-900 rounded-2xl p-6 md:p-8 border border-slate-200 dark:border-slate-700 hover:border-brand-green dark:hover:border-brand-green transition-all duration-300 hover:shadow-xl hover:shadow-brand-green/10 transform hover:-translate-y-1"
            >
              {/* Job Header */}
              <div className="flex flex-col md:flex-row md:items-start md:justify-between gap-4 mb-6">
                <div className="flex-1">
                  <h3 className="text-2xl md:text-3xl font-bold text-slate-900 dark:text-white mb-2">
                    {jobTitle}
                  </h3>
                  <div className="flex flex-wrap gap-3 text-sm">
                    <span className="inline-flex items-center px-3 py-1 rounded-full bg-brand-green/10 text-brand-green font-medium">
                      {job.departmentLabel[lang]}
                    </span>
                    <span className="inline-flex items-center px-3 py-1 rounded-full bg-slate-200 dark:bg-slate-700 text-slate-700 dark:text-slate-300">
                      📍 {job.location[lang]}
                    </span>
                    <span className="inline-flex items-center px-3 py-1 rounded-full bg-slate-200 dark:bg-slate-700 text-slate-700 dark:text-slate-300">
                      {job.contractTypeLabel[lang]}
                    </span>
                    <span className="inline-flex items-center px-3 py-1 rounded-full bg-slate-200 dark:bg-slate-700 text-slate-700 dark:text-slate-300">
                      {job.levelLabel[lang]}
                    </span>
                  </div>
                </div>

                <div className="flex flex-col items-start md:items-end gap-2">
                  <div className="text-lg md:text-xl font-bold text-brand-green">
                    {job.salaryRange[lang]}
                  </div>
                  <button
                    onClick={() => handleApplyClick(job)}
                    className="inline-flex items-center justify-center px-6 py-3 bg-brand-green text-white font-semibold rounded-lg hover:bg-green-600 transition-all duration-200 transform hover:scale-105 shadow-md hover:shadow-brand-green/50"
                  >
                    {copy.jobApplyButton}
                  </button>
                </div>
              </div>

              {/* Job Details */}
              <div className="space-y-6">
                {responsibilities.length > 0 && (
                  <div>
                    <h4 className="text-lg font-bold text-slate-900 dark:text-white mb-3">
                      {copy.jobResponsibilities}
                    </h4>
                    <ul className="space-y-2">
                      {responsibilities.map((resp, idx) => (
                        <li
                          key={idx}
                          className="flex items-start gap-3 text-neutral-600 dark:text-neutral-400"
                        >
                          <span className="text-brand-green mt-1 flex-shrink-0">
                            ▪
                          </span>
                          <span>{resp}</span>
                        </li>
                      ))}
                    </ul>
                  </div>
                )}

                {requirements.length > 0 && (
                  <div>
                    <h4 className="text-lg font-bold text-slate-900 dark:text-white mb-3">
                      {copy.jobRequirements}
                    </h4>
                    <ul className="space-y-2">
                      {requirements.map((req, idx) => (
                        <li
                          key={idx}
                          className="flex items-start gap-3 text-neutral-600 dark:text-neutral-400"
                        >
                          <span className="text-brand-green mt-1 flex-shrink-0">
                            ✓
                          </span>
                          <span>{req}</span>
                        </li>
                      ))}
                    </ul>
                  </div>
                )}

                {skills.length > 0 && (
                  <div>
                    <h4 className="text-lg font-bold text-slate-900 dark:text-white mb-3">
                      {copy.jobSkills}
                    </h4>
                    <ul className="space-y-2">
                      {skills.map((skill, idx) => (
                        <li
                          key={idx}
                          className="flex items-start gap-3 text-neutral-600 dark:text-neutral-400"
                        >
                          <span className="text-slate-400 mt-1 flex-shrink-0">
                            •
                          </span>
                          <span>{skill}</span>
                        </li>
                      ))}
                    </ul>
                  </div>
                )}

                {niceToHave.length > 0 && (
                  <div>
                    <h4 className="text-lg font-bold text-slate-900 dark:text-white mb-3">
                      {copy.jobNiceToHave}
                    </h4>
                    <ul className="space-y-2">
                      {niceToHave.map((nice, idx) => (
                        <li
                          key={idx}
                          className="flex items-start gap-3 text-neutral-600 dark:text-neutral-400"
                        >
                          <span className="text-slate-400 mt-1 flex-shrink-0">
                            +
                          </span>
                          <span>{nice}</span>
                        </li>
                      ))}
                    </ul>
                  </div>
                )}

                {benefits.length > 0 && (
                  <div>
                    <h4 className="text-lg font-bold text-slate-900 dark:text-white mb-3">
                      {copy.jobBenefits}
                    </h4>
                    <ul className="space-y-2">
                      {benefits.map((benefit, idx) => (
                        <li
                          key={idx}
                          className="flex items-start gap-3 text-neutral-600 dark:text-neutral-400"
                        >
                          <span className="text-brand-green mt-1 flex-shrink-0">
                            ★
                          </span>
                          <span>{benefit}</span>
                        </li>
                      ))}
                    </ul>
                  </div>
                )}

                {workday.length > 0 && (
                  <div>
                    <h4 className="text-lg font-bold text-slate-900 dark:text-white mb-3">
                      {copy.jobWorkday}
                    </h4>
                    <ul className="space-y-2">
                      {workday.map((item, idx) => (
                        <li
                          key={idx}
                          className="flex items-start gap-3 text-neutral-600 dark:text-neutral-400"
                        >
                          <span className="text-slate-400 mt-1 flex-shrink-0">
                            •
                          </span>
                          <span>{item}</span>
                        </li>
                      ))}
                    </ul>
                  </div>
                )}

                {applicationInstructions && (
                  <div className="bg-slate-100 dark:bg-slate-800/60 rounded-xl p-4 border border-slate-200 dark:border-slate-700">
                    <h4 className="text-lg font-bold text-slate-900 dark:text-white mb-2">
                      {copy.jobApplicationInstructions}
                    </h4>
                    <p className="text-neutral-600 dark:text-neutral-400 leading-relaxed">
                      {applicationInstructions}
                    </p>
                  </div>
                )}

                <div className="pt-4 border-t border-slate-200 dark:border-slate-700">
                  <p className="text-sm text-neutral-500">
                    {copy.jobPosted}:{" "}
                    {new Date(job.openingAt).toLocaleDateString(
                      lang === "ar" ? "ar-SA" : "en-US",
                      { year: "numeric", month: "long", day: "numeric" },
                    )}
                  </p>
                </div>
              </div>
            </div>
          );
        })}
      </div>

      {/* Application Modal */}
      {selectedJob && (
        <div
          className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm p-4"
          onClick={handleCloseModal}
          dir={isRtl ? "rtl" : "ltr"}
        >
          <div
            className="bg-white dark:bg-slate-900 rounded-2xl shadow-2xl w-full max-w-2xl max-h-[90vh] overflow-y-auto"
            onClick={(e) => e.stopPropagation()}
          >
            {/* Success State */}
            {submitStatus === "success" && (
              <div className="p-8 text-center">
                <div className="text-6xl mb-4">✅</div>
                <h3 className="text-2xl font-bold text-slate-900 dark:text-white mb-2">
                  {copy.applicationFormSuccessTitle}
                </h3>
                <p className="text-neutral-600 dark:text-neutral-400">
                  {copy.applicationFormSuccessMessage}
                </p>
              </div>
            )}

            {/* Error State */}
            {submitStatus === "error" && (
              <div className="p-8 text-center">
                <div className="text-6xl mb-4">❌</div>
                <h3 className="text-2xl font-bold text-slate-900 dark:text-white mb-2">
                  {copy.applicationFormErrorTitle}
                </h3>
                <p className="text-neutral-600 dark:text-neutral-400 mb-6">
                  {copy.applicationFormErrorMessage}
                </p>
                <button
                  onClick={() => setSubmitStatus("idle")}
                  className="px-6 py-2 bg-brand-green text-white font-semibold rounded-lg hover:bg-green-600 transition-all"
                >
                  {lang === "ar" ? "حاول مرة أخرى" : "Try Again"}
                </button>
              </div>
            )}

            {/* Form State */}
            {submitStatus === "idle" && (
              <>
                {/* Modal Header */}
                <div className="sticky top-0 bg-gradient-to-br from-slate-900 to-slate-800 text-white p-6 rounded-t-2xl">
                  <div className="flex items-start justify-between">
                    <div>
                      <h2 className="text-2xl font-bold mb-1">
                        {copy.applicationFormTitle}
                      </h2>
                      <p className="text-xl font-semibold text-brand-green">
                        {selectedJob.title[lang]}
                      </p>
                      <p className="text-sm text-neutral-300 mt-2">
                        {copy.applicationFormSubtitle}
                      </p>
                    </div>
                    <button
                      onClick={handleCloseModal}
                      className="text-white hover:text-brand-green transition-colors text-2xl"
                      aria-label="Close"
                    >
                      ×
                    </button>
                  </div>
                </div>

                {/* Form */}
                <form onSubmit={handleSubmit} className="p-6 space-y-6">
                  {/* Full Name */}
                  <div>
                    <label className="block text-sm font-semibold text-slate-900 dark:text-white mb-2">
                      {copy.applicationFormNameLabel}{" "}
                      <span className="text-red-500">*</span>
                    </label>
                    <input
                      type="text"
                      required
                      value={formData.fullName}
                      onChange={(e) =>
                        setFormData({ ...formData, fullName: e.target.value })
                      }
                      placeholder={copy.applicationFormNamePlaceholder}
                      className="w-full px-4 py-3 rounded-lg border border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-800 text-slate-900 dark:text-white focus:ring-2 focus:ring-brand-green focus:border-transparent"
                    />
                  </div>

                  {/* Email */}
                  <div>
                    <label className="block text-sm font-semibold text-slate-900 dark:text-white mb-2">
                      {copy.applicationFormEmailLabel}{" "}
                      <span className="text-red-500">*</span>
                    </label>
                    <input
                      type="email"
                      required
                      value={formData.email}
                      onChange={(e) =>
                        setFormData({ ...formData, email: e.target.value })
                      }
                      placeholder={copy.applicationFormEmailPlaceholder}
                      className="w-full px-4 py-3 rounded-lg border border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-800 text-slate-900 dark:text-white focus:ring-2 focus:ring-brand-green focus:border-transparent"
                    />
                  </div>

                  {/* Phone */}
                  <div>
                    <label className="block text-sm font-semibold text-slate-900 dark:text-white mb-2">
                      {copy.applicationFormPhoneLabel}{" "}
                      <span className="text-red-500">*</span>
                    </label>
                    <input
                      type="tel"
                      required
                      value={formData.phone}
                      onChange={(e) =>
                        setFormData({ ...formData, phone: e.target.value })
                      }
                      placeholder={copy.applicationFormPhonePlaceholder}
                      className="w-full px-4 py-3 rounded-lg border border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-800 text-slate-900 dark:text-white focus:ring-2 focus:ring-brand-green focus:border-transparent"
                    />
                  </div>

                  {/* Resume Upload */}
                  <div>
                    <label className="block text-sm font-semibold text-slate-900 dark:text-white mb-2">
                      {copy.applicationFormResumeLabel}{" "}
                      <span className="text-red-500">*</span>
                    </label>
                    <input
                      type="file"
                      accept=".pdf"
                      required
                      onChange={handleFileChange}
                      className="w-full px-4 py-3 rounded-lg border-2 border-dashed border-slate-300 dark:border-slate-600 bg-slate-50 dark:bg-slate-800 file:mr-4 file:py-2 file:px-4 file:rounded-lg file:border-0 file:text-sm file:font-semibold file:bg-brand-green file:text-white hover:file:bg-green-600"
                    />
                    <p className="text-xs text-neutral-500 mt-1">
                      {copy.applicationFormResumeHelp}
                    </p>
                  </div>

                  {/* Cover Letter */}
                  <div>
                    <label className="block text-sm font-semibold text-slate-900 dark:text-white mb-2">
                      {copy.applicationFormCoverLetterLabel}
                    </label>
                    <textarea
                      value={formData.coverLetter}
                      onChange={(e) =>
                        setFormData({
                          ...formData,
                          coverLetter: e.target.value,
                        })
                      }
                      placeholder={copy.applicationFormCoverLetterPlaceholder}
                      rows={4}
                      className="w-full px-4 py-3 rounded-lg border border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-800 text-slate-900 dark:text-white focus:ring-2 focus:ring-brand-green focus:border-transparent resize-none"
                    />
                  </div>

                  {/* Form Actions */}
                  <div className="flex flex-col-reverse sm:flex-row gap-3 pt-4">
                    <button
                      type="button"
                      onClick={handleCloseModal}
                      disabled={isSubmitting}
                      className="flex-1 px-6 py-3 border-2 border-slate-300 dark:border-slate-600 text-slate-700 dark:text-slate-300 font-semibold rounded-lg hover:bg-slate-100 dark:hover:bg-slate-800 transition-all disabled:opacity-50 disabled:cursor-not-allowed"
                    >
                      {copy.applicationFormCancelButton}
                    </button>
                    <button
                      type="submit"
                      disabled={isSubmitting || !resumeFile}
                      className="flex-1 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 transform hover:scale-105 shadow-md hover:shadow-brand-green/50"
                    >
                      {isSubmitting ? (
                        <span className="flex items-center justify-center gap-2">
                          <span className="animate-spin">⏳</span>
                          <span>
                            {lang === "ar"
                              ? "جاري الإرسال..."
                              : "Submitting..."}
                          </span>
                        </span>
                      ) : (
                        copy.applicationFormSubmitButton
                      )}
                    </button>
                  </div>
                </form>
              </>
            )}
          </div>
        </div>
      )}
    </>
  );
}
