"use client";
/* eslint-disable @next/next/no-img-element -- served through /api/media with our own responsive variants */

import * as React from "react";
import { useQuery } from "convex/react";
import { AnimatePresence, motion } from "motion/react";
import { Bath, BedDouble, Building2, Check, Mail, MessageCircle, Phone, Send, Users, X, Zap } from "lucide-react";
import { api } from "../../../convex/_generated/api";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";
import { AvailabilityCalendar } from "./availability-calendar";
import { AnimatedText } from "@/components/motion/animated-number";
import { LeadForm } from "./lead-form";
import { track } from "./fb-pixel";
import { fmtMoney } from "@/lib/format";
import { addDays, dayKey, fmtDate, nightsBetween, parseDay, startOfMonth } from "@/lib/dates";
import type { Apartment, Business, Avail } from "./showroom-page";

const src = (id: string, w: number) => `/api/media/${id}?w=${w}`;

/**
 * Apartment detail sheet: gallery, facts, amenities, a live two-month
 * availability calendar that doubles as a date picker, price for the chosen
 * nights and one-tap ways to reach the business.
 */
export function ApartmentSheet({ apartment: a, business, avail, checkIn, checkOut, guests = 2, onDates, onClose, today, onBook }: { apartment: Apartment | null; business: Business; avail?: Avail; checkIn: string; checkOut: string; guests?: number; onDates: (ci: string, co: string) => void; onClose: () => void; today: string; onBook?: (id: string) => void }) {
  const [img, setImg] = React.useState(0);
  const [request, setRequest] = React.useState(false);
  React.useEffect(() => {
    setRequest(false);
    if (a) track("ViewContent", { content_name: a.code, content_type: "apartment" });
  }, [a]);
  const [month, setMonth] = React.useState<Date>(startOfMonth(parseDay(checkIn || today)));
  const [pickStart, setPickStart] = React.useState<string | null>(null);
  React.useEffect(() => {
    setImg(0);
    setPickStart(null);
    setMonth(startOfMonth(parseDay(checkIn || today)));
  }, [a?.id, checkIn, today]);
  const from = dayKey(month);
  const booked = useQuery(api.showroom.calendar, a ? { apartmentId: a.id as never, from, days: 70 } : "skip");
  const taken = React.useMemo(() => new Set(booked ?? []), [booked]);
  const nights = checkIn && checkOut ? nightsBetween(parseDay(checkIn), parseDay(checkOut)) : 0;
  const conflict = nights > 0 && [...Array(nights)].some((_, i) => taken.has(dayKey(addDays(parseDay(checkIn), i))));

  const pick = (day: string) => {
    if (!pickStart) {
      setPickStart(day);
      onDates(day, "");
      return;
    }
    if (day <= pickStart) {
      setPickStart(day);
      onDates(day, "");
      return;
    }
    onDates(pickStart, day);
    setPickStart(null);
  };

  const digits = business.whatsapp.replace(/[^\d]/g, "");
  const msg = a ? encodeURIComponent(`Hello ${business.name}, I would like to book ${a.name} (${a.code})${nights > 0 ? ` from ${checkIn} to ${checkOut} (${nights} night${nights > 1 ? "s" : ""})` : ""} for ${guests} guest${guests > 1 ? "s" : ""}.${nights > 0 && avail ? ` I saw ${avail.subtotal} ${business.currency} for the stay.` : ""}`) : "";

  return (
    <Dialog open={!!a} onOpenChange={(o) => !o && onClose()}>
      <DialogContent size="full" hideClose className="max-h-[94dvh] overflow-hidden p-0 sm:max-h-[90vh]">
        {a ? (
          <>
            <DialogTitle className="sr-only">
              {a.code} · {a.name}
            </DialogTitle>
            <button type="button" onClick={onClose} className="absolute right-3 top-3 z-10 flex size-9 items-center justify-center rounded-full bg-stone-950/50 text-white backdrop-blur transition hover:rotate-90 hover:bg-stone-950/70" aria-label="Close">
              <X className="size-4" />
            </button>
            <div className="grid max-h-[94dvh] overflow-y-auto scrollbar-thin sm:max-h-[90vh] lg:grid-cols-[1.15fr_1fr] lg:overflow-hidden">
              {/* Gallery */}
              <div className="relative bg-stone-950 lg:h-full lg:min-h-[560px]">
                <div className="relative aspect-[4/3] w-full overflow-hidden lg:absolute lg:inset-0 lg:aspect-auto">
                  <AnimatePresence mode="sync">
                    <motion.img key={a.images[img]?.id} src={src(a.images[img]?.id, 1600)} alt={a.images[img]?.caption ?? a.name} initial={{ opacity: 0, scale: 1.04 }} animate={{ opacity: 1, scale: 1 }} exit={{ opacity: 0 }} transition={{ duration: 0.6, ease: [0.16, 1, 0.3, 1] }} className="absolute inset-0 size-full object-cover" />
                  </AnimatePresence>
                  <div className="absolute inset-x-0 bottom-0 h-40 bg-gradient-to-t from-stone-950/85 to-transparent" />
                  <div className="absolute inset-x-0 bottom-0 p-4 text-white lg:p-6">
                    <p className="text-2xs font-semibold uppercase tracking-[0.2em] text-white/70">
                      {a.city}
                      {a.building ? ` · ${a.building}` : ""}
                    </p>
                    <p className="font-display text-2xl font-medium leading-tight lg:text-3xl">{a.name}</p>
                    <p className="mt-0.5 text-xs text-white/75">
                      <span className="font-mono">{a.code}</span> · {a.images[img]?.category ? a.images[img].category.replace(/_/g, " ").toLowerCase() : "photo"} {img + 1}/{a.images.length}
                    </p>
                  </div>
                </div>
                {a.images.length > 1 ? (
                  <div className="flex gap-1.5 overflow-x-auto bg-stone-950 p-2 scrollbar-none lg:absolute lg:right-4 lg:top-4 lg:w-auto lg:max-w-[60%] lg:rounded-xl lg:bg-stone-950/40 lg:p-1.5 lg:backdrop-blur">
                    {a.images.map((im, i) => (
                      <button key={im.id} type="button" onClick={() => setImg(i)} className={cn("relative h-12 w-16 shrink-0 overflow-hidden rounded-md transition-all duration-300", i === img ? "ring-2 ring-white" : "opacity-60 hover:opacity-100")} aria-label={`Photo ${i + 1}`}>
                        <img src={src(im.id, 320)} alt="" className="size-full object-cover" loading="lazy" />
                      </button>
                    ))}
                  </div>
                ) : null}
              </div>

              {/* Details */}
              <div className="flex flex-col gap-5 p-5 lg:max-h-[90vh] lg:overflow-y-auto lg:p-6 scrollbar-thin">
                <div className="flex flex-wrap items-center gap-2 text-sm text-fg-muted">
                  <span className="flex items-center gap-1.5"><BedDouble className="size-4" /> {a.bedrooms ? `${a.bedrooms} bedroom${a.bedrooms > 1 ? "s" : ""}` : "Studio"}</span>
                  <span className="text-fg-subtle">·</span>
                  <span className="flex items-center gap-1.5"><Bath className="size-4" /> {a.bathrooms} bath</span>
                  <span className="text-fg-subtle">·</span>
                  <span className="flex items-center gap-1.5"><Users className="size-4" /> up to {a.maxGuests}</span>
                  {a.floor ? (
                    <>
                      <span className="text-fg-subtle">·</span>
                      <span className="flex items-center gap-1.5"><Building2 className="size-4" /> floor {a.floor}</span>
                    </>
                  ) : null}
                </div>
                <div className="flex items-end justify-between gap-3 rounded-xl border border-border bg-surface-2/50 p-4">
                  <div>
                    <p className="eyebrow">Per night</p>
                    <p className="font-display text-3xl font-medium tabular">{fmtMoney(a.basePrice, business.currency, { whole: true })}</p>
                    {a.weekendPrice ? <p className="text-xs text-fg-muted">{fmtMoney(a.weekendPrice, business.currency, { whole: true })} on weekend nights</p> : null}
                  </div>
                  <div className="text-right">
                    {nights > 0 ? (
                      <>
                        <p className="eyebrow">{nights} night{nights > 1 ? "s" : ""}</p>
                        <p className={cn("text-xl font-semibold tabular", conflict ? "text-negative-600 line-through" : "text-fg")}>
                          <AnimatedText text={fmtMoney(avail?.subtotal ?? a.basePrice * nights, business.currency, { whole: true })} />
                        </p>
                        <p className={cn("text-2xs font-semibold", conflict ? "text-negative-600" : "text-positive-600")}>{conflict ? "Not free on these nights" : "Free for your dates"}</p>
                      </>
                    ) : (
                      <p className="text-xs text-fg-muted">Pick dates below</p>
                    )}
                  </div>
                </div>
                {a.amenities.length ? (
                  <div>
                    <p className="eyebrow mb-2">Amenities</p>
                    <ul className="flex flex-wrap gap-1.5">
                      {a.amenities.map((am, i) => (
                        <motion.li key={am} initial={{ opacity: 0, y: 6 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.03 * i }} className="flex items-center gap-1 rounded-full border border-border bg-surface px-2.5 py-1 text-xs">
                          <Check className="size-3 text-positive-600" /> {am}
                        </motion.li>
                      ))}
                    </ul>
                  </div>
                ) : null}
                <div>
                  <p className="eyebrow mb-2 flex items-center gap-2">
                    Availability <span className="live-dot" aria-label="Live" />
                  </p>
                  {booked === undefined ? <div className="skeleton h-56" /> : <AvailabilityCalendar booked={taken} checkIn={pickStart ?? checkIn} checkOut={pickStart ? "" : checkOut} today={today} onPick={pick} month={month} onMonth={setMonth} />}
                </div>
                <div className="mt-auto space-y-2 border-t border-border pt-4">
                  <p className="text-xs text-fg-muted">
                    {nights > 0 && !conflict ? `${fmtDate(parseDay(checkIn), { style: "weekday" })} → ${fmtDate(parseDay(checkOut), { style: "weekday" })} · check-in from ${business.checkInTime}, check-out by ${business.checkOutTime}` : `Check-in from ${business.checkInTime} · check-out by ${business.checkOutTime}`}
                  </p>
                  <AnimatePresence initial={false}>
                    {request ? (
                      <motion.div key="req" initial={{ height: 0, opacity: 0 }} animate={{ height: "auto", opacity: 1 }} exit={{ height: 0, opacity: 0 }} className="overflow-hidden">
                        <div className="rounded-2xl border border-primary/30 bg-primary/5 p-3">
                          <LeadForm business={business} ctx={{ apartment: { id: a.id, code: a.code, name: a.name }, checkIn: nights > 0 ? checkIn : undefined, checkOut: nights > 0 ? checkOut : undefined, guests }} kind={conflict ? "WAITLIST" : "LEAD_FORM"} compact subtitle={conflict ? "These nights are taken — we call you if they free up or with a similar apartment." : "We confirm by phone or WhatsApp, usually within minutes."} />
                        </div>
                      </motion.div>
                    ) : null}
                  </AnimatePresence>
                  {onBook && !conflict ? (
                    <Button size="lg" className="w-full rounded-xl shine" onClick={() => onBook(a.id)}>
                      <Zap /> Book now{nights > 0 && avail ? ` · ${fmtMoney(avail.subtotal, business.currency, { whole: true })}` : ""}
                    </Button>
                  ) : null}
                  <Button size="lg" variant={request || (onBook && !conflict) ? "secondary" : "primary"} className={cn("w-full rounded-xl", !request && !(onBook && !conflict) && "shine")} onClick={() => setRequest((v) => !v)}>
                    <Send /> {request ? "Hide the request form" : conflict ? "Ask for these dates anyway" : "Ask a question first"}
                  </Button>
                  <div className="grid grid-cols-3 gap-2">
                    {digits ? (
                      <Button size="lg" className="col-span-3 bg-[#25D366] text-white hover:bg-[#1fb857] sm:col-span-1" asChild onClick={() => track("Contact", { method: "whatsapp", content_name: a.code })}>
                        <a href={`https://wa.me/${digits}?text=${msg}`} target="_blank" rel="noreferrer">
                          <MessageCircle /> WhatsApp
                        </a>
                      </Button>
                    ) : null}
                    <Button size="lg" variant="secondary" asChild>
                      <a href={`tel:${business.phone}`}>
                        <Phone /> Call
                      </a>
                    </Button>
                    <Button size="lg" variant="secondary" asChild>
                      <a href={`mailto:${business.email}?subject=${encodeURIComponent(`Booking request · ${a.code}`)}&body=${msg}`}>
                        <Mail /> Email
                      </a>
                    </Button>
                  </div>
                </div>
              </div>
            </div>
          </>
        ) : null}
      </DialogContent>
    </Dialog>
  );
}
