import { useRef, useState, type FormEvent } from "react";
import { useServerFn } from "@tanstack/react-start";
import { CheckCircle2, FileText, Loader2, Send, Upload } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { applicationSchema, resumeError } from "@/lib/application-schema";
import { submitApplication } from "@/lib/application.functions";
import oceanWash from "@/assets/ocean-soft-wash.jpg";

export function ApplicationForm() {
  const submit = useServerFn(submitApplication);
  const fileRef = useRef<HTMLInputElement>(null);
  const [fileName, setFileName] = useState("");
  const [pending, setPending] = useState(false);
  const [error, setError] = useState("");
  const [success, setSuccess] = useState(false);

  async function handleSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    if (pending) return;
    const form = event.currentTarget;
    const data = new FormData(form);
    const parsed = applicationSchema.safeParse(Object.fromEntries(data));
    if (!parsed.success) { setError(parsed.error.issues[0]?.message ?? "Please check your details."); return; }
    const file = data.get("resume");
    const fileError = file instanceof File ? resumeError(file) : "Please upload your résumé.";
    if (fileError) { setError(fileError); return; }
    setPending(true);
    setError("");
    try {
      const result = await submit({ data });
      if (!result.ok) { setError(result.message); return; }
      form.reset();
      setFileName("");
      setSuccess(true);
    } catch { setError("Your application could not be submitted. Please try again or call us."); }
    finally { setPending(false); }
  }

  return (
    <section className="relative overflow-hidden border-t bg-muted">
      <img src={oceanWash} alt="" aria-hidden loading="lazy" className="ocean-wash-image pointer-events-none absolute inset-0 h-full w-full object-cover opacity-70 mix-blend-multiply" />
      <div className="relative mx-auto max-w-3xl px-6 py-12 sm:py-16">
        <h2 className="text-3xl text-primary sm:text-4xl">Apply to Join Our Team</h2>
        {success ? <div role="status" className="mt-6 space-y-4"><CheckCircle2 className="h-8 w-8 text-accent" /><p>Your application and résumé have been received. Thank you for your interest in Premier Pediatric Therapy.</p><Button variant="soft" onClick={() => setSuccess(false)}>Submit Another Application</Button></div> : (
          <form onSubmit={handleSubmit} className="mt-6 space-y-5">
            <fieldset disabled={pending} className="grid gap-5 sm:grid-cols-2">
              <div className="space-y-2"><label htmlFor="application-name" className="text-sm font-medium">Name *</label><Input id="application-name" name="name" required maxLength={100} autoComplete="name" className="h-12 bg-card" /></div>
              <div className="space-y-2"><label htmlFor="application-email" className="text-sm font-medium">Email *</label><Input id="application-email" name="email" type="email" required maxLength={255} autoComplete="email" className="h-12 bg-card" /></div>
              <div className="space-y-2"><label htmlFor="application-phone" className="text-sm font-medium">Phone (optional)</label><Input id="application-phone" name="phone" type="tel" maxLength={30} autoComplete="tel" className="h-12 bg-card" /></div>
              <div className="space-y-2"><label htmlFor="application-position" className="text-sm font-medium">Position of Interest *</label><Input id="application-position" name="position" required maxLength={150} className="h-12 bg-card" /></div>
              <div className="space-y-2 sm:col-span-2"><label htmlFor="application-message" className="text-sm font-medium">Additional Information (optional)</label><Textarea id="application-message" name="message" maxLength={3000} rows={4} className="bg-card" /></div>
              <div className="space-y-3 sm:col-span-2">
                <label htmlFor="application-resume" className="block text-sm font-medium">Résumé * <span className="font-normal text-muted-foreground">(PDF, up to 5 MB)</span></label>
                <input ref={fileRef} id="application-resume" name="resume" type="file" accept=".pdf,application/pdf" className="sr-only" tabIndex={-1} onChange={(event) => {
                  const file = event.target.files?.[0];
                  if (!file) { setFileName(""); return; }
                  const issue = resumeError(file);
                  setError(issue);
                  if (issue) { event.target.value = ""; setFileName(""); } else setFileName(file.name);
                }} />
                <Button type="button" variant="soft" onClick={() => fileRef.current?.click()}><Upload />{fileName ? "Replace Résumé" : "Upload Résumé"}</Button>
                {fileName && <p className="flex items-start gap-2 break-all text-sm text-secondary"><FileText className="h-4 w-4 shrink-0" />{fileName}</p>}
              </div>
              <div hidden aria-hidden="true"><input name="website" tabIndex={-1} autoComplete="off" /></div>
            </fieldset>
            {error && <p role="alert" className="text-sm text-destructive">{error}</p>}
            <Button type="submit" variant="pill" size="xl" disabled={pending} className="w-full sm:w-auto">{pending ? <Loader2 className="animate-spin" /> : <Send />}{pending ? "Submitting…" : "Submit Application"}</Button>
          </form>
        )}
      </div>
    </section>
  );
}