"use client";

import { useEffect, useRef, useState, type FormEvent } from "react";
import {
  X,
  FileUp,
  CheckCircle2,
  FileCheck2,
  Loader2,
  ArrowRight,
} from "lucide-react";

const MAX_RESUME_SIZE_MB = 5;
const ACCEPTED_RESUME_TYPES = [".pdf", ".doc", ".docx"];

const FOCUSABLE =
  'a[href], button:not([disabled]), input:not([disabled]):not([type="hidden"]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';

type ApplyModalProps = {
  jobTitle: string;
  onClose: () => void;
};

type FieldErrors = Partial<
  Record<"fullName" | "email" | "phone" | "resume", string>
>;

const inputClass =
  "mt-2 min-h-12 w-full rounded-xl border border-slate-200 bg-white px-4 text-base text-slate-900 outline-none transition-[border-color,box-shadow] duration-200 ease-out placeholder:text-ink-400 hover:border-slate-300 focus:border-accent focus:ring-4 focus:ring-accent/10 focus-visible:ring-offset-0 aria-[invalid=true]:border-red-300";

export default function ApplyModal({ jobTitle, onClose }: ApplyModalProps) {
  const [submitting, setSubmitting] = useState(false);
  const [submitted, setSubmitted] = useState(false);
  const [formError, setFormError] = useState<string | null>(null);
  const [fieldErrors, setFieldErrors] = useState<FieldErrors>({});
  const [resumeName, setResumeName] = useState<string>("");
  const dialogRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const previouslyFocused = document.activeElement as HTMLElement | null;
    const dialog = dialogRef.current;

    // Move focus into the dialog (first field), then keep Tab inside it.
    (
      dialog?.querySelector<HTMLElement>("input:not([type='hidden'])") ?? dialog
    )?.focus();

    const onKeyDown = (e: KeyboardEvent) => {
      if (e.key === "Escape") {
        onClose();
        return;
      }
      if (e.key !== "Tab" || !dialog) return;
      const items = Array.from(dialog.querySelectorAll<HTMLElement>(FOCUSABLE));
      if (items.length === 0) return;
      const first = items[0];
      const last = items[items.length - 1];
      if (e.shiftKey && document.activeElement === first) {
        e.preventDefault();
        last.focus();
      } else if (!e.shiftKey && document.activeElement === last) {
        e.preventDefault();
        first.focus();
      }
    };
    document.addEventListener("keydown", onKeyDown);
    document.body.style.overflow = "hidden";
    return () => {
      document.removeEventListener("keydown", onKeyDown);
      document.body.style.overflow = "";
      previouslyFocused?.focus?.();
    };
  }, [onClose]);

  function validateResume(file: File | undefined): string | undefined {
    if (!file) return undefined;
    const ext = file.name.slice(file.name.lastIndexOf(".")).toLowerCase();
    if (!ACCEPTED_RESUME_TYPES.includes(ext)) {
      return "Resume must be a PDF or Word document (.pdf, .doc, .docx).";
    }
    if (file.size > MAX_RESUME_SIZE_MB * 1024 * 1024) {
      return `Resume must be smaller than ${MAX_RESUME_SIZE_MB}MB.`;
    }
    return undefined;
  }

  async function handleSubmit(e: FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setFormError(null);

    const form = e.currentTarget;
    const data = new FormData(form);
    const fullName = String(data.get("fullName") || "").trim();
    const email = String(data.get("email") || "").trim();
    const phone = String(data.get("phone") || "").trim();
    const resume = data.get("resume") as File | null;

    const errors: FieldErrors = {};
    if (!fullName) errors.fullName = "Full name is required.";
    if (!email) {
      errors.email = "Email is required.";
    } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
      errors.email = "Enter a valid email address.";
    }
    if (!phone) errors.phone = "Phone number is required.";
    const resumeError = validateResume(resume ?? undefined);
    if (resumeError) errors.resume = resumeError;

    setFieldErrors(errors);
    if (Object.keys(errors).length > 0) return;

    // Integration point: wire this up to an ATS or backend endpoint (e.g. via
    // process.env.NEXT_PUBLIC_CAREERS_FORM_ENDPOINT), following the same
    // pattern as Contact.tsx's Formspree submission.
    const endpoint = process.env.NEXT_PUBLIC_CAREERS_FORM_ENDPOINT;
    if (!endpoint) {
      setFormError(
        "Applications aren't wired up to a backend yet. Please email your resume to hr@vasundharainfotechllp.com.",
      );
      return;
    }

    setSubmitting(true);
    try {
      const response = await fetch(endpoint, {
        method: "POST",
        headers: { Accept: "application/json" },
        body: data,
      });
      if (response.ok) {
        setSubmitted(true);
      } else {
        setFormError(
          "Something went wrong submitting your application. Please try again.",
        );
      }
    } catch {
      setFormError(
        "Something went wrong submitting your application. Please try again.",
      );
    } finally {
      setSubmitting(false);
    }
  }

  const resumeOk = Boolean(resumeName) && !fieldErrors.resume;

  return (
    <div
      className="fixed inset-0 z-100 flex items-end justify-center bg-slate-900/50 backdrop-blur-sm sm:items-center sm:p-6"
      onMouseDown={(e) => {
        if (e.target === e.currentTarget) onClose();
      }}
    >
      <div className="relative w-full max-w-xl">
        <div
          ref={dialogRef}
          role="dialog"
          aria-modal="true"
          aria-labelledby="apply-modal-title"
          tabIndex={-1}
          className="relative max-h-[92vh] w-full overflow-y-auto rounded-t-3xl border border-slate-200 bg-white p-6 shadow-[0_30px_70px_-30px_rgba(15,23,42,0.5)] outline-none sm:rounded-3xl sm:p-8"
          style={{ animation: "reveal-up 0.3s ease-out both" }}
        >
          <div className="flex items-start justify-between gap-4">
            <div className="min-w-0">
              <p className="inline-flex items-center gap-2 text-[11px] font-semibold uppercase tracking-[0.2em] text-accent">
                <span className="h-1.5 w-1.5 rounded-full bg-accent" />
                Apply for this role
              </p>
              <h3
                id="apply-modal-title"
                className="mt-2 font-display text-2xl font-semibold tracking-tight text-[#0F172A] sm:text-[1.7rem]"
              >
                {jobTitle}
              </h3>
            </div>
            <button
              type="button"
              onClick={onClose}
              aria-label="Close application form"
              className="grid h-10 w-10 shrink-0 cursor-pointer place-items-center rounded-full border border-slate-200 text-ink-400 transition-all duration-200 hover:border-accent/40 hover:bg-accent-50 hover:text-accent"
            >
              <X className="h-4.5 w-4.5" />
            </button>
          </div>

          {submitted ? (
            <div className="flex flex-col items-center py-10 text-center">
              <span className="grid h-16 w-16 place-items-center rounded-full bg-accent/10 text-accent">
                <CheckCircle2 className="h-8 w-8" strokeWidth={1.75} />
              </span>
              <h4 className="mt-5 font-display text-xl font-semibold text-[#0F172A]">
                Application received!
              </h4>
              <p className="mt-2 max-w-sm text-sm leading-relaxed text-ink-300">
                Thanks for applying to {jobTitle}. Our talent team will review
                your application and get back to you soon.
              </p>
              <button
                type="button"
                onClick={onClose}
                className="btn-primary mt-7 cursor-pointer"
              >
                Close
              </button>
            </div>
          ) : (
            <form onSubmit={handleSubmit} className="mt-7 space-y-5" noValidate>
              <input type="hidden" name="position" value={jobTitle} />

              <div>
                <label
                  htmlFor="fullName"
                  className="text-sm font-semibold text-[#0F172A]"
                >
                  Full Name <span className="text-red-600">*</span>
                </label>
                <input
                  id="fullName"
                  name="fullName"
                  type="text"
                  required
                  placeholder="Your full name"
                  aria-invalid={Boolean(fieldErrors.fullName)}
                  className={inputClass}
                />
                {fieldErrors.fullName && (
                  <p className="mt-1.5 text-xs text-red-600">
                    {fieldErrors.fullName}
                  </p>
                )}
              </div>

              <div className="grid gap-5 sm:grid-cols-2">
                <div>
                  <label
                    htmlFor="email"
                    className="text-sm font-semibold text-[#0F172A]"
                  >
                    Email <span className="text-red-600">*</span>
                  </label>
                  <input
                    id="email"
                    name="email"
                    type="email"
                    required
                    placeholder="you@email.com"
                    aria-invalid={Boolean(fieldErrors.email)}
                    className={inputClass}
                  />
                  {fieldErrors.email && (
                    <p className="mt-1.5 text-xs text-red-600">
                      {fieldErrors.email}
                    </p>
                  )}
                </div>
                <div>
                  <label
                    htmlFor="phone"
                    className="text-sm font-semibold text-[#0F172A]"
                  >
                    Phone Number <span className="text-red-600">*</span>
                  </label>
                  <input
                    id="phone"
                    name="phone"
                    type="tel"
                    required
                    placeholder="+1 (555) 000-0000"
                    aria-invalid={Boolean(fieldErrors.phone)}
                    className={inputClass}
                  />
                  {fieldErrors.phone && (
                    <p className="mt-1.5 text-xs text-red-600">
                      {fieldErrors.phone}
                    </p>
                  )}
                </div>
              </div>

              <div>
                <label
                  htmlFor="resume"
                  className="text-sm font-semibold text-[#0F172A]"
                >
                  Resume <span className="text-red-600">*</span>
                </label>
                <label
                  htmlFor="resume"
                  className={`mt-2 flex min-h-32 w-full cursor-pointer flex-col items-center justify-center gap-2 rounded-2xl border-2 border-dashed px-4 py-5 text-center transition-all duration-200 ease-out focus-within:border-accent focus-within:ring-4 focus-within:ring-accent/10 ${
                    resumeOk
                      ? "border-accent/50 bg-accent-50/70"
                      : fieldErrors.resume
                        ? "border-red-300 bg-red-50/40"
                        : "border-slate-200 bg-slate-50/60 hover:border-accent/50 hover:bg-accent-50/50"
                  }`}
                >
                  <span
                    className={`grid h-11 w-11 place-items-center rounded-xl ${
                      resumeOk
                        ? "bg-accent text-white"
                        : "bg-accent/10 text-accent"
                    }`}
                  >
                    {resumeOk ? (
                      <FileCheck2 className="h-5 w-5" aria-hidden />
                    ) : (
                      <FileUp className="h-5 w-5" aria-hidden />
                    )}
                  </span>
                  <span className="max-w-full break-all text-sm font-semibold text-[#0F172A]">
                    {resumeName || "Click to upload your resume"}
                  </span>
                  <span className="text-xs text-ink-400">
                    PDF, DOC, DOCX · Maximum file size: {MAX_RESUME_SIZE_MB} MB
                  </span>
                  <input
                    id="resume"
                    name="resume"
                    type="file"
                    required
                    accept=".pdf,.doc,.docx"
                    className="sr-only"
                    onChange={(e) => {
                      const file = e.target.files?.[0];
                      setResumeName(file?.name || "");
                      const err = validateResume(file);
                      setFieldErrors((prev) => ({ ...prev, resume: err }));
                    }}
                  />
                </label>
                {fieldErrors.resume && (
                  <p className="mt-1.5 text-xs text-red-600">
                    {fieldErrors.resume}
                  </p>
                )}
              </div>

              <div className="grid gap-5 sm:grid-cols-2">
                <div>
                  <label
                    htmlFor="linkedin"
                    className="text-sm font-semibold text-[#0F172A]"
                  >
                    LinkedIn URL
                  </label>
                  <input
                    id="linkedin"
                    name="linkedin"
                    type="url"
                    placeholder="linkedin.com/in/you"
                    className={inputClass}
                  />
                </div>
                <div>
                  <label
                    htmlFor="portfolio"
                    className="text-sm font-semibold text-[#0F172A]"
                  >
                    Portfolio URL
                  </label>
                  <input
                    id="portfolio"
                    name="portfolio"
                    type="url"
                    placeholder="yourportfolio.com"
                    className={inputClass}
                  />
                </div>
              </div>

              <div>
                <label
                  htmlFor="message"
                  className="text-sm font-semibold text-[#0F172A]"
                >
                  Cover Letter / Message
                </label>
                <textarea
                  id="message"
                  name="message"
                  rows={4}
                  placeholder="Tell us why you're a great fit for this role."
                  className={`${inputClass} min-h-28 resize-y py-3 leading-relaxed`}
                />
              </div>

              {formError && (
                <p
                  role="alert"
                  className="rounded-xl border border-red-200 bg-red-50 px-4 py-2.5 text-center text-sm text-red-600"
                >
                  {formError}
                </p>
              )}

              <button
                type="submit"
                disabled={submitting}
                aria-busy={submitting}
                className="group inline-flex h-13 w-full cursor-pointer items-center justify-center gap-2 rounded-[14px] bg-accent-600 px-6 text-[0.95rem] font-semibold text-white shadow-glow-sm transition-all duration-200 ease-out hover:-translate-y-0.5 hover:bg-accent-700 hover:shadow-[0_0_0_1px_rgba(0,148,238,0.2),0_14px_34px_-8px_rgba(0,148,238,0.5)] active:translate-y-0 disabled:translate-y-0 disabled:cursor-not-allowed disabled:opacity-70 disabled:hover:bg-accent"
              >
                {submitting ? (
                  <>
                    <Loader2 className="h-4 w-4 animate-spin" />
                    Submitting...
                  </>
                ) : (
                  <>
                    Submit Application
                    <ArrowRight className="h-4 w-4 transition-transform duration-200 group-hover:translate-x-1" />
                  </>
                )}
              </button>
              <p className="text-center text-sm text-ink-400">
                Required fields are marked with{" "}
                <span className="text-red-600">*</span>.
              </p>
            </form>
          )}
        </div>
      </div>
    </div>
  );
}
