"use client";

import { Send, ShieldCheck } from "lucide-react";
import { useState, type FormEvent } from "react";
import { z } from "zod";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Select } from "@/components/ui/select";
import { Textarea } from "@/components/ui/textarea";

const contactSchema = z.object({
  fullName: z.string().min(2),
  phone: z.string().min(7),
  email: z.string().email().optional().or(z.literal("")),
  subject: z.string().min(2),
  message: z.string().min(5),
});

export function ContactForm() {
  const [submitted, setSubmitted] = useState(false);
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);

  async function handleSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    setSubmitted(false);
    setError("");
    const formData = new FormData(event.currentTarget);
    const values = Object.fromEntries(formData.entries());
    const parsed = contactSchema.safeParse(values);

    if (!parsed.success) {
      setError("Please check all required fields.");
      return;
    }

    setLoading(true);
    try {
      const response = await fetch("/api/contact", {
        method: "POST",
        headers: {
          "content-type": "application/json",
        },
        body: JSON.stringify(parsed.data),
      });
      const result = (await response.json()) as {
        success: boolean;
        error?: string;
      };

      if (!response.ok || !result.success) {
        setError(result.error ?? "Unable to send message right now.");
        return;
      }

      setSubmitted(true);
      event.currentTarget.reset();
    } catch {
      setError("Unable to send message right now.");
    } finally {
      setLoading(false);
    }
  }

  return (
    <form className="soft-card p-6" onSubmit={handleSubmit}>
      <h2 className="text-2xl font-bold text-navy-deep">Send Us a Message</h2>
      <p className="mt-2 text-sm text-navy-muted">
        Fill out the form below and our team will get back to you shortly.
      </p>
      <div className="mt-6 grid gap-4 sm:grid-cols-2">
        <label className="text-sm font-semibold text-navy-deep">
          Full Name *
          <Input className="mt-2" name="fullName" placeholder="Enter your full name" required />
        </label>
        <label className="text-sm font-semibold text-navy-deep">
          Phone Number *
          <Input className="mt-2" name="phone" placeholder="Enter your phone number" required />
        </label>
        <label className="text-sm font-semibold text-navy-deep">
          Email Address
          <Input className="mt-2" name="email" placeholder="Enter your email address" type="email" />
        </label>
        <label className="text-sm font-semibold text-navy-deep">
          Subject *
          <Select className="mt-2" name="subject" required defaultValue="">
            <option value="" disabled>
              Select a subject
            </option>
            <option>General Inquiry</option>
            <option>Sales Question</option>
            <option>Service & Maintenance</option>
            <option>Parts & Accessories</option>
            <option>Financing & Offers</option>
          </Select>
        </label>
        <label className="text-sm font-semibold text-navy-deep sm:col-span-2">
          Message *
          <Textarea className="mt-2" name="message" placeholder="Type your message here..." required />
        </label>
      </div>
      <div className="mt-5 flex items-center gap-2 text-xs font-medium text-navy-muted">
        <ShieldCheck className="h-4 w-4 text-ev" />
        Your information is safe with us. We do not share your details.
      </div>
      {submitted ? (
        <p
          className="mt-4 rounded-xl bg-ev-soft px-4 py-3 text-sm font-bold text-ev-deep"
          role="status"
          aria-live="polite"
        >
          Message received. Our team will contact you shortly.
        </p>
      ) : null}
      {error ? (
        <p className="mt-4 rounded-xl bg-red-50 px-4 py-3 text-sm font-bold text-red-700" role="alert">
          {error}
        </p>
      ) : null}
      <Button className="mt-5 w-full" type="submit" variant="green" disabled={loading}>
        <Send className="h-4 w-4" />
        {loading ? "Sending..." : "Send Message"}
      </Button>
    </form>
  );
}
