import { createFileRoute } from "@tanstack/react-router";
import { useServerFn } from "@tanstack/react-start";
import { useState } from "react";
import { CheckCircle2, GraduationCap, HeartPulse, Landmark, Paperclip, TrendingUp, Users2, ShieldCheck } from "lucide-react";
import people from "@/assets/story-people.jpg";
import { Reveal } from "@/components/site/Reveal";
import { submitCareerApplication } from "@/lib/careers.functions";

export const Route = createFileRoute("/careers")({
  head: () => ({
    meta: [
      { title: "Careers — Vigor Group of Companies" },
      {
        name: "description",
        content:
          "Build your career with Vigor Group of Companies across seven sectors — healthcare, hospitality, manufacturing, trading, real estate, investment and community development — in Tanzania.",
      },
      { property: "og:title", content: "Careers — Vigor Group of Companies" },
      { property: "og:description", content: "Life at Vigor, benefits and how to join our team." },
      { property: "og:type", content: "website" },
      { property: "og:url", content: "/careers" },
    ],
    links: [{ rel: "canonical", href: "/careers" }],
  }),
  component: Careers,
});

const benefits = [
  { Icon: TrendingUp, k: "Career Growth", v: "Move between sectors and roles as the group grows." },
  { Icon: GraduationCap, k: "Training", v: "On-the-job development and professional mentorship." },
  { Icon: HeartPulse, k: "Healthcare", v: "Access to care through our own hospital network." },
  { Icon: Users2, k: "Team Culture", v: "Collaborative teams that respect people and expertise." },
  { Icon: ShieldCheck, k: "Stability", v: "A group with four decades of continuous operation." },
  { Icon: Landmark, k: "Impact", v: "Work that visibly improves life in Tanzanian communities." },
];

const areas = [
  "Healthcare & Clinical Services",
  "Hospitality & Guest Experience",
  "Manufacturing & Production",
  "Sales, Trading & Distribution",
  "Real Estate & Construction",
  "Finance, HR, ICT & Legal",
];

function fileToBase64(file: File): Promise<string> {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = () => resolve(String(reader.result).split(",")[1] ?? "");
    reader.onerror = () => reject(reader.error);
    reader.readAsDataURL(file);
  });
}

function Careers() {
  const [sent, setSent] = useState(false);
  const [fileName, setFileName] = useState<string | null>(null);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const sendApplication = useServerFn(submitCareerApplication);

  return (
    <>
      <section className="relative">
        <div className="relative min-h-[420px] h-[55vh]">
          <img src={people} alt="Team members of Vigor Group of Companies" className="absolute inset-0 w-full h-full object-cover" />
          <div className="absolute inset-0 bg-navy-deep/75" />
          <div className="relative container-x h-full flex items-end pb-14 text-white">
            <div className="max-w-3xl">
              <p className="eyebrow text-white/70">Careers</p>
              <h1 className="mt-4 text-5xl md:text-7xl leading-[1]">
                Build Tanzania's <span className="italic">Future</span> with Us
              </h1>
              <p className="mt-6 max-w-xl text-white/80 leading-relaxed">
                Our businesses are powered by Tanzanian talent. If you care about doing
                excellent work for your community, there is a place for you here.
              </p>
            </div>
          </div>
        </div>
      </section>

      <section className="container-x py-16 md:py-20 grid lg:grid-cols-12 gap-12">
        <div className="lg:col-span-5">
          <p className="eyebrow">Life at Vigor</p>
          <h2 className="mt-4 text-4xl md:text-5xl leading-tight">
            Professional standards, human culture.
          </h2>
        </div>
        <div className="lg:col-span-7 space-y-6 text-lg text-ink-soft leading-relaxed">
          <p>
            Working at Vigor Group of Companies means joining teams that operate to
            international standards while staying rooted in Zanzibar and Tanzania. Our
            people run hospitals, hotels, factories and developments that thousands of
            families rely on every day.
          </p>
          <p>
            We hire for character as much as credentials — integrity, accountability and a
            willingness to keep learning. In return we invest in training, offer genuine
            mobility across sectors, and give people the responsibility to do their best work.
          </p>
        </div>
      </section>

      <section className="bg-secondary/60 border-y border-border">
        <div className="container-x py-16 md:py-20">
          <div className="max-w-2xl">
            <p className="eyebrow">Benefits</p>
            <h2 className="mt-4 text-4xl md:text-5xl">What We Offer</h2>
          </div>
          <div className="mt-12 grid sm:grid-cols-2 lg:grid-cols-3 gap-x-10 gap-y-12">
            {benefits.map((b, i) => (
              <Reveal key={b.k} delay={i * 60}>
                <div className="border-t-2 border-crimson pt-6">
                  <b.Icon size={26} strokeWidth={1.4} className="text-crimson" />
                  <h3 className="mt-5 text-2xl">{b.k}</h3>
                  <p className="mt-3 text-muted-foreground leading-relaxed">{b.v}</p>
                </div>
              </Reveal>
            ))}
          </div>
        </div>
      </section>

      <section className="container-x py-16 md:py-20 grid lg:grid-cols-12 gap-12 items-start">
        <div className="lg:col-span-6">
          <p className="eyebrow">Where we hire</p>
          <h2 className="mt-4 text-4xl md:text-5xl leading-tight">Build the Future of Tanzania</h2>
          <ul className="mt-10 grid sm:grid-cols-2 gap-x-8 gap-y-4">
            {areas.map((a) => (
              <li key={a} className="border-t border-border pt-4 font-semibold text-ink-soft">{a}</li>
            ))}
          </ul>
        </div>
        <Reveal delay={100} className="lg:col-span-6">
          {sent ? (
            <div role="status" className="bg-secondary/50 border border-border p-8 md:p-10 text-center">
              <CheckCircle2 className="mx-auto text-primary" size={40} />
              <h2 className="mt-5 text-2xl">Application received</h2>
              <p className="mt-3 text-ink-soft leading-relaxed">
                Thank you. Your CV has been sent to our HR team for consideration.
              </p>
              <button type="button" className="btn-ghost mt-7" onClick={() => { setSent(false); setFileName(null); }}>
                Submit another application
              </button>
            </div>
          ) : (
            <form
              className="bg-secondary/50 border border-border p-8 md:p-10 space-y-5"
              onSubmit={async (event) => {
                event.preventDefault();
                const form = event.currentTarget;
                const data = new FormData(form);
                const file = data.get("cv");
                setError(null);
                setSubmitting(true);
                try {
                  if (!(file instanceof File) || file.size === 0) throw new Error("Please attach your CV.");
                  if (file.size > 5 * 1024 * 1024) throw new Error("Your CV must be 5 MB or smaller.");
                  await sendApplication({ data: {
                    name: String(data.get("name") ?? ""),
                    email: String(data.get("email") ?? ""),
                    phone: String(data.get("phone") ?? ""),
                    area: String(data.get("area") ?? ""),
                    message: String(data.get("message") ?? "") || undefined,
                    attachment: { filename: file.name, content: await fileToBase64(file) },
                  } });
                  form.reset();
                  setSent(true);
                } catch (caught) {
                  setError(caught instanceof Error ? caught.message : "Something went wrong. Please try again.");
                } finally {
                  setSubmitting(false);
                }
              }}
            >
              <h2 className="text-2xl">Join our team</h2>
              <p className="text-sm text-ink-soft leading-relaxed">Submit your details and CV to our HR team.</p>
              <div className="grid sm:grid-cols-2 gap-5">
                <label className="block">
                  <span className="text-xs uppercase tracking-[0.18em] font-semibold">Full name</span>
                  <input name="name" required maxLength={100} className="mt-2 w-full bg-background border border-border px-4 py-3 focus:outline-none focus:border-primary" />
                </label>
                <label className="block">
                  <span className="text-xs uppercase tracking-[0.18em] font-semibold">Email</span>
                  <input name="email" type="email" required maxLength={255} className="mt-2 w-full bg-background border border-border px-4 py-3 focus:outline-none focus:border-primary" />
                </label>
              </div>
              <label className="block">
                <span className="text-xs uppercase tracking-[0.18em] font-semibold">Phone number</span>
                <input name="phone" type="tel" required maxLength={40} className="mt-2 w-full bg-background border border-border px-4 py-3 focus:outline-none focus:border-primary" />
              </label>
              <label className="block">
                <span className="text-xs uppercase tracking-[0.18em] font-semibold">Area of interest</span>
                <select name="area" required defaultValue="" className="mt-2 w-full bg-background border border-border px-4 py-3 focus:outline-none focus:border-primary">
                  <option value="" disabled>Select where you would like to work</option>
                  {areas.map((area) => <option key={area} value={area}>{area}</option>)}
                </select>
              </label>
              <label className="block">
                <span className="text-xs uppercase tracking-[0.18em] font-semibold">Short note <span className="text-ink-soft normal-case tracking-normal">(optional)</span></span>
                <textarea name="message" rows={4} maxLength={2000} placeholder="Tell us about the kind of role you are looking for." className="mt-2 w-full bg-background border border-border px-4 py-3 focus:outline-none focus:border-primary" />
              </label>
              <div>
                <span className="text-xs uppercase tracking-[0.18em] font-semibold">CV attachment</span>
                <label className="mt-2 flex items-center gap-3 border border-dashed border-border bg-background px-4 py-3 cursor-pointer hover:border-primary transition-colors">
                  <Paperclip size={16} className="text-primary shrink-0" />
                  <span className="text-sm text-ink-soft truncate">{fileName ?? "Attach your CV (PDF, DOC or DOCX; max 5 MB)"}</span>
                  <input type="file" name="cv" required accept=".pdf,.doc,.docx,application/pdf,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document" className="sr-only" onChange={(event) => setFileName(event.target.files?.[0]?.name ?? null)} />
                </label>
              </div>
              {error && <p role="alert" className="text-sm text-primary">{error}</p>}
              <button type="submit" className="btn-primary" disabled={submitting}>{submitting ? "Submitting…" : "Submit application"}</button>
            </form>
          )}
        </Reveal>
      </section>
    </>
  );
}
