"use client";

import { useState } from "react";
import { ChevronDown, ImagePlus, MessageCircle } from "lucide-react";
import { isLocationSlug, type Locale } from "@alterra/shared";
import { whatsappUrl } from "@/lib/i18n";
import { useLeadForm } from "@/lib/useLeadForm";
import { Consent, Honeypot, StatusLine, type FormMessages } from "../forms/FormBits";
import type { CompanyCopy } from "@/lib/companyContent";

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";
const MAX_PHOTOS = 10;

type Option = { value: string; label: string };

/**
 * Owner valuation request. The lead is stored now; photo files are only counted here and will be
 * uploaded to object storage from the owners' flow (the advisor requests them after the first contact).
 */
export default function ValuationForm({
  copy,
  types,
  zones,
  lang,
  messages,
}: {
  copy: CompanyCopy["sell"]["form"];
  types: Option[];
  zones: Option[];
  lang: Locale;
  messages: FormMessages;
}) {
  const { status, submit, sending } = useLeadForm("valuation", lang);
  const [photoCount, setPhotoCount] = useState(0);

  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 details = Object.fromEntries(
      [
        ["type", data.get("type")],
        ["builtArea", data.get("builtArea")],
        ["lotArea", data.get("lotArea")],
        ["expectedPrice", data.get("expectedPrice")],
        ["photosSelected", photoCount ? String(photoCount) : ""],
      ]
        .map(([k, v]) => [String(k), String(v ?? "").trim()])
        .filter(([, v]) => v),
    );
    const ok = await submit(data, {
      zone: isLocationSlug(zone) || zone === "other" ? (zone as "other") : undefined,
      services: ["luxury-real-estate"],
      details,
    });
    if (ok) {
      form.reset();
      setPhotoCount(0);
    }
  };

  const select = (name: string, label: string, options: Option[]) => (
    <label className="relative block">
      <span className="eyebrow text-[0.6rem] text-stone">{label}</span>
      <select name={name} required defaultValue="" className={`${field} cursor-pointer appearance-none pr-8`}>
        <option value="" disabled>
          —
        </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>
  );

  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 />
      {select("type", copy.type, types)}
      {select("zone", copy.zone, [...zones, { value: "other", label: copy.other }])}
      <label className="block">
        <span className="eyebrow text-[0.6rem] text-stone">{copy.builtArea}</span>
        <input name="builtArea" inputMode="numeric" className={field} />
      </label>
      <label className="block">
        <span className="eyebrow text-[0.6rem] text-stone">{copy.lotArea}</span>
        <input name="lotArea" inputMode="numeric" className={field} />
      </label>
      <label className="block sm:col-span-2">
        <span className="eyebrow text-[0.6rem] text-stone">{copy.expectedPrice}</span>
        <input name="expectedPrice" className={field} />
      </label>

      <div className="sm:col-span-2">
        <span className="eyebrow text-[0.6rem] text-stone">{copy.photos}</span>
        <label className="mt-3 flex cursor-pointer items-center gap-4 border border-dashed border-ink/25 p-5 transition hover:border-gold">
          <ImagePlus size={24} strokeWidth={1.2} className="shrink-0 text-gold-ink" />
          <span className="text-sm text-stone">{photoCount ? copy.selected.replace("{n}", String(photoCount)) : copy.photosHint}</span>
          <input
            type="file"
            accept="image/jpeg,image/png"
            multiple
            className="sr-only"
            onChange={(e) => setPhotoCount(Math.min(e.target.files?.length ?? 0, MAX_PHOTOS))}
          />
        </label>
      </div>

      <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 sm:col-span-2">
        <span className="eyebrow text-[0.6rem] text-stone">{copy.phone}</span>
        <input name="phone" type="tel" autoComplete="tel" className={field} />
      </label>
      <label className="block sm:col-span-2">
        <span className="eyebrow text-[0.6rem] text-stone">{copy.message}</span>
        <textarea name="message" rows={3} className={`${field} resize-none`} />
      </label>
      <div className="sm:col-span-2">
        <Consent messages={messages} />
      </div>

      <div className="flex flex-col gap-4 sm:col-span-2 sm:flex-row">
        <button
          type="submit"
          disabled={sending}
          className="bg-ink px-8 py-4 text-[0.75rem] tracking-[0.16em] uppercase text-cream transition hover:bg-forest disabled:opacity-60"
        >
          {copy.submit}
        </button>
        <a
          href={whatsappUrl()}
          target="_blank"
          rel="noopener"
          className="flex items-center justify-center gap-2 border border-forest px-6 py-4 text-[0.72rem] tracking-[0.16em] uppercase text-forest transition hover:bg-forest hover:text-cream"
        >
          <MessageCircle size={15} strokeWidth={1.5} /> {copy.whatsapp}
        </a>
      </div>
      <div className="sm:col-span-2">
        <StatusLine status={status} messages={messages} />
      </div>
    </form>
  );
}
