"use client";

import * as React from "react";
import { useMutation } from "convex/react";
import { AnimatePresence, motion } from "motion/react";
import { Check, MessageCircle, Phone, Send } from "lucide-react";
import { api } from "../../../convex/_generated/api";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { getAttribution } from "@/lib/attribution";
import { fmtDate, parseDay } from "@/lib/dates";
import { track } from "./fb-pixel";
import type { Business } from "./showroom-page";

export interface LeadContext {
  apartment?: { id: string; code: string; name: string } | null;
  checkIn?: string;
  checkOut?: string;
  guests?: number;
}
const digitsOf = (s: string) => s.replace(/[^\d]/g, "");

/**
 * The "don't lose the visitor" form: name + phone, optional dates, one tap.
 * Works for a booking request on an apartment, a waitlist when nothing is
 * free, or a call-back. On success it offers to continue on WhatsApp with
 * the request already written.
 */
export function LeadForm({ business, ctx, kind = "LEAD_FORM", title, subtitle, className, compact, onDone, initialName = "", initialPhone = "" }: { business: Business; ctx: LeadContext; kind?: "LEAD_FORM" | "WAITLIST" | "CALLBACK" | "EXIT"; title?: string; subtitle?: string; className?: string; compact?: boolean; onDone?: () => void; initialName?: string; initialPhone?: string }) {
  const submit = useMutation(api.showroom.submitLead);
  const [name, setName] = React.useState(initialName);
  const [phone, setPhone] = React.useState(initialPhone);
  const [msg, setMsg] = React.useState("");
  const [busy, setBusy] = React.useState(false);
  const [error, setError] = React.useState<string | null>(null);
  const [done, setDone] = React.useState(false);
  const nights = ctx.checkIn && ctx.checkOut ? Math.round((Date.parse(ctx.checkOut) - Date.parse(ctx.checkIn)) / 864e5) : 0;
  const stay = nights > 0 ? `${fmtDate(parseDay(ctx.checkIn!), { style: "weekday" })} → ${fmtDate(parseDay(ctx.checkOut!), { style: "weekday" })} · ${nights} night${nights > 1 ? "s" : ""}` : "";

  async function send(e?: React.FormEvent) {
    e?.preventDefault();
    if (busy) return;
    if (name.trim().length < 2) return setError("Your name, please.");
    if (digitsOf(phone).length < 8) return setError("A phone number we can reach you on.");
    setBusy(true);
    setError(null);
    try {
      const r = await submit({ name: name.trim(), phone: phone.trim(), apartmentId: (ctx.apartment?.id as never) ?? undefined, checkIn: nights > 0 ? ctx.checkIn : undefined, checkOut: nights > 0 ? ctx.checkOut : undefined, guests: ctx.guests ?? 1, message: msg.trim() || undefined, kind, attribution: getAttribution() });
      if (!r.ok) {
        setError(r.error ?? "Please try again.");
        return;
      }
      setDone(true);
      track("Lead", { content_name: ctx.apartment?.code ?? kind });
      if ("vibrate" in navigator) navigator.vibrate?.(12);
      onDone?.();
    } catch {
      setError("Could not send right now — message us on WhatsApp instead.");
    } finally {
      setBusy(false);
    }
  }

  const waText = `Hello ${business.name}, I'm ${name.trim() || "…"}. ${ctx.apartment ? `I would like to book ${ctx.apartment.name} (${ctx.apartment.code})` : kind === "WAITLIST" ? "I'm looking for an apartment" : "I'd like some information"}${stay ? ` for ${stay}` : ""}${ctx.guests ? ` for ${ctx.guests} guest${ctx.guests > 1 ? "s" : ""}` : ""}.${msg.trim() ? ` ${msg.trim()}` : ""}`;
  const wa = `https://wa.me/${digitsOf(business.whatsapp)}?text=${encodeURIComponent(waText)}`;

  return (
    <div className={cn("relative", className)}>
      <AnimatePresence mode="wait" initial={false}>
        {done ? (
          <motion.div key="done" initial={{ opacity: 0, scale: 0.96 }} animate={{ opacity: 1, scale: 1 }} className="flex flex-col items-center py-3 text-center">
            <motion.span initial={{ scale: 0 }} animate={{ scale: 1 }} transition={{ type: "spring", stiffness: 380, damping: 16, delay: 0.08 }} className="flex size-14 items-center justify-center rounded-full bg-positive-500/15 text-positive-600">
              <Check className="size-7" />
            </motion.span>
            <p className="mt-3 font-display text-xl font-medium">Got it, {name.trim().split(" ")[0]}.</p>
            <p className="mt-1 max-w-xs text-sm text-fg-muted">The team will contact you {business.replyMinutes ? `within about ${business.replyMinutes} minutes` : "shortly"} on {phone}. Prefer to talk now?</p>
            <div className="mt-4 flex w-full flex-col gap-2 sm:flex-row">
              {digitsOf(business.whatsapp) ? (
                <Button className="flex-1 bg-[#25D366] text-white hover:bg-[#1fb857]" asChild onClick={() => track("Contact", { method: "whatsapp" })}>
                  <a href={wa} target="_blank" rel="noreferrer"><MessageCircle /> Continue on WhatsApp</a>
                </Button>
              ) : null}
              <Button variant="secondary" className="flex-1" asChild onClick={() => track("Contact", { method: "call" })}>
                <a href={`tel:${business.phone}`}><Phone /> Call us</a>
              </Button>
            </div>
          </motion.div>
        ) : (
          <motion.form key="form" onSubmit={send} initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0, y: -8 }} className="space-y-2.5">
            {title ? <p className="font-display text-lg font-medium leading-tight">{title}</p> : null}
            {subtitle ? <p className="-mt-1 text-xs text-fg-muted">{subtitle}</p> : null}
            {stay ? <p className="rounded-lg bg-surface-2 px-2.5 py-1.5 text-xs text-fg-muted">{ctx.apartment ? `${ctx.apartment.name} · ` : ""}{stay}{ctx.guests ? ` · ${ctx.guests} guest${ctx.guests > 1 ? "s" : ""}` : ""}</p> : null}
            <div className={cn("grid gap-2", compact ? "" : "sm:grid-cols-2")}>
              <Input value={name} onChange={(e) => setName(e.target.value)} placeholder="Your name" autoComplete="name" className="h-11 rounded-xl" aria-label="Name" />
              <Input value={phone} onChange={(e) => setPhone(e.target.value)} placeholder="+212 6 XX XX XX XX" inputMode="tel" autoComplete="tel" className="h-11 rounded-xl" aria-label="Phone" />
            </div>
            {!compact ? <Input value={msg} onChange={(e) => setMsg(e.target.value)} placeholder="Anything we should know? (optional)" className="h-11 rounded-xl" aria-label="Message" /> : null}
            {error ? <p role="alert" className="text-xs font-medium text-negative-600 animate-slide-up">{error}</p> : null}
            <Button type="submit" size="lg" className="w-full rounded-xl shine" loading={busy}>
              <Send /> {kind === "WAITLIST" ? "Call me when something is free" : kind === "CALLBACK" || kind === "EXIT" ? "Call me back" : "Request this apartment"}
            </Button>
            <p className="text-center text-2xs text-fg-subtle">No account needed · your number is only used to answer you.</p>
          </motion.form>
        )}
      </AnimatePresence>
    </div>
  );
}
