"use client";

import { useSearchParams } from "next/navigation";
import { FormEvent, useState } from "react";

type ContactResponse = {
  success: boolean;
  message: string;
  fieldErrors?: Record<string, string>;
};

const projectOptions = [
  { value: "", label: "Select a project type" },
  { value: "masonry-supplies", label: "Masonry supplies" },
  { value: "landscaping-supplies", label: "Landscaping supplies" },
  { value: "delivery-quote", label: "Delivery quote" },
  { value: "bulk-order", label: "Bulk order" },
  { value: "general-question", label: "General question" },
];

export function ContactForm() {
  const searchParams = useSearchParams();
  const materialInterest = searchParams.get("material") ?? "";
  const [formData, setFormData] = useState({
    name: "",
    phone: "",
    email: "",
    projectType: "",
    message: "",
  });
  const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({});
  const [status, setStatus] = useState<ContactResponse | null>(null);
  const [isSubmitting, setIsSubmitting] = useState(false);

  async function handleSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    setIsSubmitting(true);
    setStatus(null);
    setFieldErrors({});

    try {
      const response = await fetch("/api/contact", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          ...formData,
          materialInterest,
        }),
      });

      const payload = (await response.json()) as ContactResponse;
      setStatus(payload);
      setFieldErrors(payload.fieldErrors ?? {});

      if (payload.success) {
        setFormData({
          name: "",
          phone: "",
          email: "",
          projectType: "",
          message: "",
        });
      }
    } catch {
      setStatus({
        success: false,
        message: "Something went wrong while sending the form. Please call the yard directly.",
      });
    } finally {
      setIsSubmitting(false);
    }
  }

  return (
    <form className="form-grid" onSubmit={handleSubmit} noValidate>
      <div className="form-row">
        <div className="field">
          <label htmlFor="name">Full name</label>
          <input
            id="name"
            name="name"
            autoComplete="name"
            value={formData.name}
            onChange={(event) =>
              setFormData((current) => ({ ...current, name: event.target.value }))
            }
          />
          {fieldErrors.name ? <span className="field-error">{fieldErrors.name}</span> : null}
        </div>

        <div className="field">
          <label htmlFor="phone">Phone number</label>
          <input
            id="phone"
            name="phone"
            autoComplete="tel"
            value={formData.phone}
            onChange={(event) =>
              setFormData((current) => ({ ...current, phone: event.target.value }))
            }
          />
          {fieldErrors.phone ? <span className="field-error">{fieldErrors.phone}</span> : null}
        </div>
      </div>

      <div className="field">
        <label htmlFor="email">Email address</label>
        <input
          id="email"
          name="email"
          type="email"
          autoComplete="email"
          value={formData.email}
          onChange={(event) =>
            setFormData((current) => ({ ...current, email: event.target.value }))
          }
        />
        {fieldErrors.email ? <span className="field-error">{fieldErrors.email}</span> : null}
      </div>

      <div className="field">
        <label htmlFor="projectType">Project type</label>
        <select
          id="projectType"
          name="projectType"
          value={formData.projectType}
          onChange={(event) =>
            setFormData((current) => ({
              ...current,
              projectType: event.target.value,
            }))
          }
        >
          {projectOptions.map((option) => (
            <option key={option.value || "empty"} value={option.value}>
              {option.label}
            </option>
          ))}
        </select>
      </div>

      {materialInterest ? (
        <div className="field">
          <label htmlFor="materialInterest">Material interest</label>
          <input id="materialInterest" value={materialInterest} readOnly />
        </div>
      ) : null}

      <div className="field">
        <label htmlFor="message">Project details</label>
        <textarea
          id="message"
          name="message"
          value={formData.message}
          onChange={(event) =>
            setFormData((current) => ({ ...current, message: event.target.value }))
          }
          placeholder="Tell us what material you need, approximate quantity, and whether delivery is required."
        />
        {fieldErrors.message ? <span className="field-error">{fieldErrors.message}</span> : null}
      </div>

      {status ? (
        <div className={`form-status ${status.success ? "success" : "error"}`}>
          {status.message}
        </div>
      ) : null}

      <button type="submit" className="button button-primary" disabled={isSubmitting}>
        {isSubmitting ? "Sending..." : "Send message"}
      </button>
    </form>
  );
}
