import { useEffect, useRef, useState } from "react";
import { CheckCircle2, ChevronDown, Loader2, MapPin, Upload } from "lucide-react";
import SEO from "../lib/seo";
import PageHero from "../components/PageHero";
import Reveal from "../components/Reveal";
import SectionHead from "../components/SectionHead";
import { fetchJobs, submitApplication } from "../lib/api";
import type { Job } from "../types";

const inputCls =
  "w-full bg-transparent border-b border-white/25 text-white placeholder:text-white/30 text-sm px-0 py-3 outline-none focus:border-cy transition-colors rounded-none";
const labelCls = "block text-[11px] font-tech tracking-[0.22em] text-cy mb-2 uppercase";

export default function Careers() {
  const [jobs, setJobs] = useState<Job[]>([]);
  const [openJob, setOpenJob] = useState<string | undefined | null>(null);
  const [form, setForm] = useState({ name: "", email: "", phone: "", position: "", positionDetails: "", currentCompany: "", experience: "", linkedin: "", message: "", website: "" });
  const [resume, setResume] = useState({ name: "", data: "" });
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [status, setStatus] = useState("idle");
  const [ref, setRef] = useState<string | null>(null);
  const formRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    fetchJobs().then((d) => setJobs(d.jobs || [])).catch(() => {});
  }, []);

  const set = (k) => (e) => setForm((f) => ({ ...f, [k]: e.target.value }));

  const onFile = (e) => {
    const file = e.target.files?.[0];
    if (!file) return;
    if (file.size > 3 * 1024 * 1024) {
      setErrors((er) => ({ ...er, resume: "Resume must be under 3MB" }));
      return;
    }
    const reader = new FileReader();
    reader.onload = () => setResume({ name: file.name, data: String(reader.result) });
    reader.readAsDataURL(file);
  };

  const applyFor = (title) => {
    setForm((f) => ({ ...f, position: title }));
    formRef.current?.scrollIntoView({ behavior: "smooth", block: "start" });
  };

  const onSubmit = async (ev) => {
    ev.preventDefault();
    const e: Record<string, string> = {};
    if (form.name.trim().length < 2) e.name = "Please enter your name";
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) e.email = "Enter a valid email";
    if (form.phone.replace(/\D/g, "").length < 8) e.phone = "Enter a valid phone number";
    if (!form.position) e.position = "Select a position";
    setErrors(e);
    if (Object.keys(e).length) return;
    setStatus("loading");
    try {
      const res = await submitApplication({ ...form, current_company: form.currentCompany, position_details: form.positionDetails, resume_name: resume.name, resume_data: resume.data });
      setRef(res?.reference || null);
      setStatus("success");
    } catch {
      setStatus("error");
    }
  };

  const jsonLd = { "@context": "https://schema.org", "@type": "WebPage", name: "Careers at Aviokan Technologies" };

  return (
    <div data-testid="careers-page">
      <SEO title="Careers" description="Build your career in enterprise technology at Aviokan Technologies — open positions across architecture, networking, security and digital engineering in Noida, India." path="/about/careers" jsonLd={jsonLd} />

      <PageHero
        eyebrow="CAREERS AT AVIOKAN"
        title={"Build the technology\nthat builds businesses."}
        desc="Work across the full enterprise stack — data centre, network, security, cloud and digital engineering — with learning and mentorship built into the culture."
        breadcrumb={[{ label: "Home", to: "/" }, { label: "About", to: "/about" }, { label: "Careers" }]}
        image="/images/careers/hero.jpg"
      />

      <section className="bg-[#0B0C10] py-24" data-testid="careers-why">
        <div className="mx-auto max-w-[1320px] px-5 md:px-10 grid md:grid-cols-3 gap-5">
          {[
            ["Why Aviokan", "Multi-domain exposure across real enterprise environments — you will never be boxed into a single technology silo."],
            ["Work culture", "Engineering-led, documentation-first and merit-driven. Juniors present to clients; seniors stay hands-on."],
            ["Learning & growth", "Certification support, lab access and structured mentorship across infrastructure, security and software disciplines."],
          ].map(([t, d], i) => (
            <Reveal key={t} delay={i * 0.08}>
              <div className="relative h-full border border-white/10 bg-[#14151A] p-8 hover:border-cy/50 transition-colors duration-300 overflow-hidden">
                <span className="font-tech text-xs text-ember">{String(i + 1).padStart(2, "0")}</span>
                <h2 className="font-display font-bold text-xl text-white mt-4">{t}</h2>
                <p className="text-sm text-white/60 leading-relaxed mt-3">{d}</p>
              </div>
            </Reveal>
          ))}
        </div>
      </section>

      <section className="bg-[#14151A] py-24 border-y border-white/10 overflow-hidden" data-testid="open-positions">
        <div className="mx-auto max-w-[1320px] px-5 md:px-10 relative">
          <div className="grain" aria-hidden="true" />
          <SectionHead eyebrow="Open positions" dark title="Current openings." lead="Every role is hands-on from week one — site surveys, rack floors, client war-rooms. Bring questions; we will bring the mentorship." className="mb-12" />
          <div className="mt-12 border-t border-white/10">
            {jobs.map((j, ji) => (
              <Reveal key={j.slug}>
                <div data-testid={`job-${j.slug}`}>
                  <button
                    className={`group w-full grid grid-cols-[44px_1fr_auto] md:grid-cols-[72px_1fr_auto] items-center gap-4 md:gap-6 py-7 px-3 text-left border-b border-white/10 transition-colors duration-300 ${openJob === j.slug ? "bg-white/[0.05]" : "hover:bg-white/[0.04]"}`}
                    onClick={() => setOpenJob(openJob === j.slug ? null : j.slug)}
                    aria-expanded={openJob === j.slug}
                    data-testid={`job-toggle-${j.slug}`}
                    data-cursor-label={openJob === j.slug ? "CLOSE" : "VIEW"}
                  >
                    <span className="font-tech text-sm text-ember tabular-nums">{String(ji + 1).padStart(2, "0")}</span>
                    <div className="min-w-0">
                      <h3 className={`font-display font-bold text-lg md:text-2xl leading-snug transition-colors duration-300 ${openJob === j.slug ? "text-cy" : "text-white group-hover:text-cy"}`}>{j.title}</h3>
                      <p className="text-[10px] font-tech tracking-[0.18em] text-white/45 mt-2 uppercase flex flex-wrap gap-x-3 gap-y-1">
                        <span>{j.team}</span><span className="text-ember hidden sm:inline">·</span>
                        <span className="flex items-center gap-1"><MapPin size={10} />{j.location}</span><span className="text-ember hidden sm:inline">·</span>
                        <span>{j.type}</span><span className="text-ember hidden sm:inline">·</span>
                        <span>{j.experience}</span>
                      </p>
                    </div>
                    <span className="flex items-center gap-2 text-[10px] font-tech tracking-[0.2em] text-ember shrink-0">
                      {openJob === j.slug ? "CLOSE" : "VIEW & APPLY"}
                      <ChevronDown size={14} className={`transition-transform duration-300 ${openJob === j.slug ? "rotate-180" : ""}`} />
                    </span>
                  </button>
                  {openJob === j.slug && (
                    <div className="px-3 pb-8 grid md:grid-cols-2 gap-8 pt-7 bg-white/[0.04] border-b border-white/10">
                      <div>
                        <p className="text-sm text-white/65 leading-relaxed">{j.description}</p>
                        <p className="text-[11px] font-tech tracking-[0.2em] text-cy mt-5 mb-3">RESPONSIBILITIES</p>
                        <ul className="space-y-2">
                          {(j.responsibilities || []).map((r) => <li key={r} className="text-sm text-white/60 flex gap-2.5"><span className="h-1.5 w-1.5 rotate-45 bg-ember shrink-0 mt-1.5" />{r}</li>)}
                        </ul>
                      </div>
                      <div>
                        <p className="text-[11px] font-tech tracking-[0.2em] text-cy mb-3">REQUIREMENTS</p>
                        <ul className="space-y-2">
                          {j.requirements.map((r) => <li key={r} className="text-sm text-white/60 flex gap-2.5"><span className="h-1.5 w-1.5 rotate-45 bg-cy shrink-0 mt-1.5" />{r}</li>)}
                        </ul>
                        <button onClick={() => applyFor(j.title)} className="mt-6 bg-ember text-white text-xs font-bold px-6 py-3 hover:bg-white hover:text-[#14151A] transition-colors" data-testid={`job-apply-${j.slug}`}>
                          Apply for this role
                        </button>
                      </div>
                    </div>
                  )}
                </div>
              </Reveal>
            ))}
            {jobs.length === 0 && (
              <p className="text-white/45 text-sm" data-testid="jobs-empty">Open positions are being updated — check back shortly or send a general application below.</p>
            )}
          </div>
          <Reveal delay={0.1}>
            <p className="mt-8 text-sm text-white/70 border border-ember/40 bg-ember/10 px-6 py-4" data-testid="internship-note">
              <span className="font-bold text-ember">Internships & graduate opportunities:</span> we run structured internship cohorts across engineering, security operations and NOC. Select “Internship / Graduate Application” below.
            </p>
          </Reveal>
        </div>
      </section>

      {/* Application form */}
      <section className="bg-[#0B0C10] py-24" data-testid="application-section" ref={formRef}>
        <div className="mx-auto max-w-3xl px-5 md:px-10">
          <Reveal>
            <p className="text-[11px] font-tech tracking-[0.3em] text-cy mb-6">APPLY NOW</p>
            <h2 className="font-display font-black text-3xl md:text-4xl text-white tracking-tight mb-12">Join Aviokan.</h2>
          </Reveal>
          {status === "success" ? (
            <div className="border border-cy/40 bg-cy/10 p-10 text-center" data-testid="application-success">
              <CheckCircle2 size={44} className="text-cy mx-auto" />
              <h3 className="font-display font-black text-2xl text-white mt-5">Application received.</h3>
              {ref && <p className="mt-3 inline-block border border-cy/40 bg-white/5 px-4 py-2 font-tech text-sm text-white" data-testid="application-reference">REFERENCE: <b>{ref}</b></p>}
              <p className="text-white/60 text-sm mt-3">A confirmation email from connect@aviokan.com is on its way to your inbox. If your profile matches, our team will reach out.</p>
            </div>
          ) : (
            <form onSubmit={onSubmit} noValidate className="grid grid-cols-1 sm:grid-cols-2 gap-5" data-testid="application-form">
              <label><span className={labelCls}>Name *</span>
                <input className={inputCls} value={form.name} onChange={set("name")} placeholder="Full name" data-testid="application-name-input" required />
                {errors.name && <span className="text-ember text-xs mt-1 block">{errors.name}</span>}
              </label>
              <label><span className={labelCls}>Email *</span>
                <input type="email" className={inputCls} value={form.email} onChange={set("email")} placeholder="you@email.com" data-testid="application-email-input" required />
                {errors.email && <span className="text-ember text-xs mt-1 block">{errors.email}</span>}
              </label>
              <label><span className={labelCls}>Phone *</span>
                <input type="tel" className={inputCls} value={form.phone} onChange={set("phone")} placeholder="+91 ..." data-testid="application-phone-input" required />
                {errors.phone && <span className="text-ember text-xs mt-1 block">{errors.phone}</span>}
              </label>
              <label><span className={labelCls}>Position *</span>
                <select className={`${inputCls}`} value={form.position} onChange={set("position")} data-testid="application-position-select">
                  <option value="">Select position</option>
                  {jobs.map((j) => <option key={j.slug} value={j.title}>{j.title}</option>)}
                  <optgroup label="Sales & Business">
                    <option value="Sales & Business Development">Sales & Business Development</option>
                    <option value="Pre-Sales / Solution Architecture">Pre-Sales / Solution Architecture</option>
                    <option value="Account / Key Account Manager">Account / Key Account Manager</option>
                  </optgroup>
                  <optgroup label="Technical & Engineering">
                    <option value="Network Engineer">Network Engineer</option>
                    <option value="Systems / Infrastructure Engineer">Systems / Infrastructure Engineer</option>
                    <option value="Cybersecurity Engineer / SOC Analyst">Cybersecurity Engineer / SOC Analyst</option>
                    <option value="Cloud Engineer">Cloud Engineer</option>
                    <option value="Software / Digital Engineer">Software / Digital Engineer</option>
                    <option value="Data Engineer / Analyst">Data Engineer / Analyst</option>
                    <option value="Field Service / Support Engineer">Field Service / Support Engineer</option>
                  </optgroup>
                  <optgroup label="Operations & Management">
                    <option value="Project / Delivery Manager">Project / Delivery Manager</option>
                    <option value="Procurement & Vendor Management">Procurement & Vendor Management</option>
                    <option value="Digital Marketing">Digital Marketing</option>
                    <option value="HR & Administration">HR & Administration</option>
                    <option value="Finance & Accounts">Finance & Accounts</option>
                  </optgroup>
                  <option value="Internship / Graduate Application">Internship / Graduate Application</option>
                  <option value="General Application">General Application</option>
                  <option value="Other">Other (specify below)</option>
                </select>
                {errors.position && <span className="text-ember text-xs mt-1 block">{errors.position}</span>}
              </label>
              <label><span className={labelCls}>Current company</span>
                <input className={inputCls} value={form.currentCompany} onChange={set("currentCompany")} placeholder="Where do you work now?" data-testid="application-current-company-input" />
              </label>
              <label><span className={labelCls}>Position details / Other</span>
                <input className={inputCls} value={form.positionDetails} onChange={set("positionDetails")} placeholder="e.g. Senior Network Engineer — or describe your role if 'Other'" data-testid="application-position-details-input" />
              </label>
              <label><span className={labelCls}>Experience</span>
                <input className={inputCls} value={form.experience} onChange={set("experience")} placeholder="e.g. 4 years" data-testid="application-experience-input" />
              </label>
              <label><span className={labelCls}>LinkedIn</span>
                <input className={inputCls} value={form.linkedin} onChange={set("linkedin")} placeholder="linkedin.com/in/…" data-testid="application-linkedin-input" />
              </label>
              <label className="sm:col-span-2"><span className={labelCls}>Resume (PDF/DOC, max 3MB)</span>
                <label htmlFor="resume-upload" className="flex items-center justify-center gap-3 border border-dashed border-white/25 hover:border-cy/60 cursor-pointer px-4 py-6 text-sm text-white/50 hover:text-cy transition-colors" data-testid="application-resume-upload">
                  <Upload size={16} /> {resume.name || "Click to upload your resume"}
                </label>
                <input id="resume-upload" type="file" accept=".pdf,.doc,.docx" className="hidden" onChange={onFile} />
                {errors.resume && <span className="text-ember text-xs mt-1 block">{errors.resume}</span>}
              </label>
              <label className="sm:col-span-2"><span className={labelCls}>Message</span>
                <textarea rows={4} className={inputCls} value={form.message} onChange={set("message")} placeholder="Tell us briefly why you're a fit…" data-testid="application-message-input" />
              </label>
              <input type="text" name="website" value={form.website} onChange={set("website")} className="hidden" tabIndex={-1} autoComplete="off" aria-hidden="true" />
              <div className="sm:col-span-2 flex items-center gap-4">
                <button type="submit" disabled={status === "loading"} className="btn-ember inline-flex items-center justify-center gap-2.5 bg-ember text-white font-bold px-10 py-4 hover:bg-[#E54D16] transition-colors duration-300 disabled:opacity-60" data-testid="application-submit-button">
                  {status === "loading" ? <Loader2 size={17} className="animate-spin" /> : null} Submit Application
                </button>
                {status === "error" && <p className="text-ember text-sm" data-testid="application-error">Something went wrong — please try again.</p>}
              </div>
            </form>
          )}
        </div>
      </section>
    </div>
  );
}
