"use client";

import { useState } from "react";
import { ChevronDown } from "lucide-react";
import {
  budgetRanges,
  isLocationSlug,
  locales,
  serviceSlugs,
  timelines,
  type Locale,
  type ServiceSlug,
} from "@alterra/shared";
import { useLeadForm } from "@/lib/useLeadForm";
import { Consent, Honeypot, StatusLine, type FormMessages } from "./FormBits";
import type { ContactCopy } from "@/lib/contactCopy";

const field =
  "w-full border-0 border-b border-ink/20 bg-transparent py-2.5 text-ink outline-none transition placeholder:text-stone focus:border-gold";

type Option = { value: string; label: string };

function Select({ name, label, options, placeholder, defaultValue = "" }: { name: string; label: string; options: Option[]; placeholder?: string; defaultValue?: string }) {
  return (
    <label className="relative block">
      <span className="eyebrow text-[0.6rem] text-stone">{label}</span>
      <select name={name} defaultValue={defaultValue} className={`${field} cursor-pointer appearance-none pr-8`}>
        {placeholder !== undefined && <option value="">{placeholder}</option>}
        {options.map((o) => (
          <option key={o.value} value={o.value}>
            {o.label}
          </option>
        ))}
      </select>
      <ChevronDown size={15} strokeWidth={1.4} className="pointer-events-none absolute bottom-3.5 right-0 text-gold-ink" />
    </label>
  );
}

/** Full private consultation form (contact page). */
export default function ContactForm({
  copy,
  lang,
  messages,
  serviceNames,
  zones,
}: {
  copy: ContactCopy;
  lang: Locale;
  messages: FormMessages;
  serviceNames: Record<ServiceSlug, string>;
  zones: Option[];
}) {
  const { status, submit, sending } = useLeadForm("contact", lang);
  const [services, setServices] = useState<ServiceSlug[]>([]);

  const toggle = (slug: ServiceSlug) => setServices((s) => (s.includes(slug) ? s.filter((x) => x !== slug) : [...s, slug]));

  const onSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    const form = e.currentTarget;
    const data = new FormData(form);
    const zone = String(data.get("zone") ?? "");
    const budget = String(data.get("budgetRange") ?? "");
    const timeline = String(data.get("timeline") ?? "");
    const ok = await submit(data, {
      services: services.length ? services : undefined,
      zone: isLocationSlug(zone) ? zone : undefined,
      budgetRange: (budgetRanges as readonly string[]).includes(budget) ? (budget as (typeof budgetRanges)[number]) : undefined,
      timeline: (timelines as readonly string[]).includes(timeline) ? (timeline as (typeof timelines)[number]) : undefined,
      details: { preferredLanguage: String(data.get("preferredLanguage") ?? lang) },
    });
    if (ok) {
      form.reset();
      setServices([]);
    }
  };

  return (
    <form onSubmit={onSubmit} className="relative grid gap-x-8 gap-y-7 border border-sand bg-white/70 p-6 sm:grid-cols-2 md:p-10">
      <Honeypot />
      <label className="block">
        <span className="eyebrow text-[0.6rem] text-stone">{copy.name}</span>
        <input name="name" required autoComplete="name" className={field} />
      </label>
      <label className="block">
        <span className="eyebrow text-[0.6rem] text-stone">{copy.email}</span>
        <input name="email" type="email" required autoComplete="email" className={field} />
      </label>
      <label className="block">
        <span className="eyebrow text-[0.6rem] text-stone">{copy.phone}</span>
        <input name="phone" type="tel" autoComplete="tel" className={field} />
      </label>
      <label className="block">
        <span className="eyebrow text-[0.6rem] text-stone">{copy.country}</span>
        <input name="country" autoComplete="country-name" className={field} />
      </label>
      <Select
        name="preferredLanguage"
        label={copy.preferredLanguage}
        options={locales.map((l) => ({ value: l, label: copy.languages[l] }))}
        defaultValue={lang}
      />
      <Select name="zone" label={copy.zone} options={zones} placeholder={copy.zoneAny} />

      <fieldset className="sm:col-span-2">
        <legend className="eyebrow text-[0.6rem] text-stone">{copy.services}</legend>
        <div className="mt-4 flex flex-wrap gap-3">
          {serviceSlugs.map((slug) => {
            const on = services.includes(slug);
            return (
              <button
                key={slug}
                type="button"
                aria-pressed={on}
                onClick={() => toggle(slug)}
                className={`border px-4 py-2 text-sm transition ${on ? "border-forest bg-forest text-cream" : "border-ink/20 hover:border-ink"}`}
              >
                {serviceNames[slug]}
              </button>
            );
          })}
        </div>
      </fieldset>

      <Select
        name="budgetRange"
        label={copy.budget}
        options={budgetRanges.map((b) => ({ value: b, label: copy.budgets[b] }))}
        placeholder={copy.select}
      />
      <Select name="timeline" label={copy.timeline} options={timelines.map((t) => ({ value: t, label: copy.timelines[t] }))} placeholder={copy.select} />

      <label className="block sm:col-span-2">
        <span className="eyebrow text-[0.6rem] text-stone">{copy.message}</span>
        <textarea name="message" rows={4} className={`${field} resize-none`} />
      </label>
      <div className="sm:col-span-2">
        <Consent messages={messages} />
      </div>
      <div className="sm:col-span-2">
        <button
          type="submit"
          disabled={sending}
          className="bg-ink px-8 py-4 text-[0.78rem] tracking-[0.16em] uppercase text-cream transition hover:bg-forest disabled:opacity-60"
        >
          {copy.submit}
        </button>
        <div className="mt-4">
          <StatusLine status={status} messages={messages} />
        </div>
      </div>
    </form>
  );
}
