"use client";

import { zodResolver } from "@hookform/resolvers/zod";
import { CalendarCheck, ShieldCheck } from "lucide-react";
import { useState } from "react";
import type { ReactNode } from "react";
import { useForm } from "react-hook-form";
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";
import { branches, scooters } from "@/lib/mock-data";

const testRideSchema = z.object({
  fullName: z.string().min(2, "Full name is required"),
  phone: z.string().min(7, "Phone number is required"),
  email: z.string().email("Enter a valid email address"),
  branch: z.string().min(1, "Select a branch"),
  scooter: z.string().min(1, "Select a scooter"),
  date: z.string().min(1, "Select a preferred date"),
  time: z.string().min(1, "Select a preferred time"),
  message: z.string().optional(),
});

type TestRideFormValues = z.infer<typeof testRideSchema>;

export function TestRideForm() {
  const [success, setSuccess] = useState(false);
  const [submitError, setSubmitError] = useState("");
  const {
    register,
    handleSubmit,
    reset,
    formState: { errors, isSubmitting },
  } = useForm<TestRideFormValues>({
    resolver: zodResolver(testRideSchema),
    defaultValues: {
      fullName: "",
      phone: "",
      email: "",
      branch: "",
      scooter: "",
      date: "",
      time: "",
      message: "",
    },
  });

  async function onSubmit(values: TestRideFormValues) {
    setSuccess(false);
    setSubmitError("");

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

      if (!response.ok || !result.success) {
        setSubmitError(result.error ?? "Unable to submit booking right now.");
        return;
      }

      setSuccess(true);
      reset();
    } catch {
      setSubmitError("Unable to submit booking right now.");
    }
  }

  return (
    <form className="soft-card p-6" onSubmit={handleSubmit(onSubmit)}>
      <div className="flex items-center gap-3">
        <CalendarCheck className="h-7 w-7 text-ev" />
        <div>
          <h2 className="text-2xl font-bold text-navy-deep">Book Your Test Ride</h2>
          <p className="mt-1 text-sm text-navy-muted">
            Fill in your details and we&apos;ll take care of the rest.
          </p>
        </div>
      </div>

      <div className="mt-6 grid gap-4 sm:grid-cols-2">
        <FieldError label="Full Name *" error={errors.fullName?.message}>
          <Input placeholder="Enter your full name" {...register("fullName")} />
        </FieldError>
        <FieldError label="Phone Number *" error={errors.phone?.message}>
          <Input placeholder="Enter your phone number" {...register("phone")} />
        </FieldError>
        <FieldError className="sm:col-span-2" label="Email Address *" error={errors.email?.message}>
          <Input placeholder="Enter your email address" type="email" {...register("email")} />
        </FieldError>
        <FieldError label="Preferred Branch *" error={errors.branch?.message}>
          <Select {...register("branch")} defaultValue="">
            <option value="" disabled>
              Select branch
            </option>
            {branches.map((branch) => (
              <option value={branch.slug} key={branch.id}>
                {branch.city}, {branch.district}
              </option>
            ))}
          </Select>
        </FieldError>
        <FieldError label="Preferred Scooter Model *" error={errors.scooter?.message}>
          <Select {...register("scooter")} defaultValue="">
            <option value="" disabled>
              Select scooter
            </option>
            {scooters.map((scooter) => (
              <option value={scooter.slug} key={scooter.id}>
                {scooter.name}
              </option>
            ))}
          </Select>
        </FieldError>
        <FieldError label="Preferred Date *" error={errors.date?.message}>
          <Input type="date" {...register("date")} />
        </FieldError>
        <FieldError label="Preferred Time *" error={errors.time?.message}>
          <Input type="time" {...register("time")} />
        </FieldError>
        <FieldError className="sm:col-span-2" label="Message (Optional)" error={errors.message?.message}>
          <Textarea placeholder="Anything specific you'd like us to know?" {...register("message")} />
        </FieldError>
      </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 respect your privacy.
      </div>
      {success ? (
        <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"
        >
          Test ride request received. Our team will confirm your booking shortly.
        </p>
      ) : null}
      {submitError ? (
        <p
          className="mt-4 rounded-xl bg-red-50 px-4 py-3 text-sm font-bold text-red-700"
          role="alert"
        >
          {submitError}
        </p>
      ) : null}
      <Button className="mt-5 w-full" type="submit" variant="green" disabled={isSubmitting}>
        <CalendarCheck className="h-4 w-4" />
        {isSubmitting ? "Submitting..." : "Book My Test Ride"}
      </Button>
    </form>
  );
}

function FieldError({
  label,
  error,
  className,
  children,
}: {
  label: string;
  error?: string;
  className?: string;
  children: ReactNode;
}) {
  return (
    <label className={`text-sm font-semibold text-navy-deep ${className ?? ""}`}>
      {label}
      <span className="mt-2 block">{children}</span>
      {error ? <span className="mt-1 block text-xs text-red-600">{error}</span> : null}
    </label>
  );
}
