import { useState, type FormEvent } from "react";
import { useServerFn } from "@tanstack/react-start";
import { CheckCircle2, Loader2, Send } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { contactSchema } from "@/lib/contact-schema";
import { submitContact } from "@/lib/contact.functions";
import oceanWash from "@/assets/ocean-soft-wash.jpg";

export function ContactForm() {
  const submit = useServerFn(submitContact);
  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 parsed = contactSchema.safeParse(Object.fromEntries(new FormData(form)));
    if (!parsed.success) {
      setError(parsed.error.issues[0]?.message ?? "Please check your details.");
      return;
    }
    setPending(true);
    setError("");
    try {
      const result = await submit({ data: parsed.data });
      if (!result.ok) {
        setError(result.message);
        return;
      }
      form.reset();
      setSuccess(true);
    } catch {
      setError("Your message 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 width={1280} height={800} 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">Send Us a Message</h2>
        {success ? (
          <div role="status" className="mt-6 space-y-4">
            <CheckCircle2 className="h-8 w-8 text-accent" />
            <p>Your message has been received. Thank you for contacting Premier Pediatric Therapy.</p>
            <Button variant="soft" onClick={() => setSuccess(false)}>Send Another Message</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="contact-name" className="text-sm font-medium">Name <span aria-hidden="true">*</span></label><Input id="contact-name" name="name" autoComplete="name" required maxLength={100} className="h-12 bg-card" /></div>
              <div className="space-y-2"><label htmlFor="contact-email" className="text-sm font-medium">Email <span aria-hidden="true">*</span></label><Input id="contact-email" name="email" type="email" autoComplete="email" required maxLength={255} className="h-12 bg-card" /></div>
              <div className="space-y-2 sm:col-span-2"><label htmlFor="contact-phone" className="text-sm font-medium">Phone (optional)</label><Input id="contact-phone" name="phone" type="tel" autoComplete="tel" maxLength={30} className="h-12 bg-card" /></div>
              <div className="space-y-2 sm:col-span-2"><label htmlFor="contact-message" className="text-sm font-medium">Message <span aria-hidden="true">*</span></label><Textarea id="contact-message" name="message" required maxLength={3000} rows={6} className="bg-card" /></div>
              <div hidden aria-hidden="true"><label htmlFor="contact-website">Website</label><input id="contact-website" name="website" tabIndex={-1} autoComplete="off" /></div>
            </fieldset>
            <p className="text-sm text-muted-foreground">Please do not include medical records or sensitive health information.</p>
            {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 ? "Sending…" : "Send Message"}</Button>
          </form>
        )}
      </div>
    </section>
  );
}