"use client";

import { useState, useEffect } from "react";
import Link from "next/link";
import { formatNightPrice } from "@/lib/mock-data";
import ReviewsSection from "@/components/ReviewsSection";
import { clientExecute } from "@/lib/api/client";
import { ApiError } from "@/lib/api/shared";
import type { RoomType, AccommodationBooking, Review, Paginated } from "@/lib/types";
import VerificationStamp from "@/components/VerificationStamp";


function StarRating({ rating, large }: { rating: number; large?: boolean }) {
  const sz = large ? "w-5 h-5" : "w-4 h-4";
  return (
    <div className="flex items-center gap-1">
      {[1, 2, 3, 4, 5].map((s) => (
        <svg key={s} viewBox="0 0 24 24" className={sz} fill={s <= Math.round(rating) ? "#D7A23E" : "none"} stroke="#D7A23E" strokeWidth="1.5">
          <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2" />
        </svg>
      ))}
      <span className={`text-ink-soft ml-1 ${large ? "text-base" : "text-xs"}`}>{rating.toFixed(1)}</span>
    </div>
  );
}

function RoomCard({ room, onBook }: { room: RoomType; onBook: (room: RoomType) => void }) {
  return (
    <div className={`bg-white border rounded-md overflow-hidden ${room.available ? "border-mist hover:border-forest transition-colors" : "border-mist opacity-60"}`}>
      {/* Room image placeholder */}
      <div className="h-36 bg-gradient-to-br from-mist to-sage flex items-center justify-center">
        <svg viewBox="0 0 24 24" fill="none" stroke="#5B6B63" strokeWidth="1.4" className="w-8 h-8">
          <path d="M3 12h18M3 7h18M3 17h18" strokeLinecap="round" />
          <rect x="1" y="4" width="22" height="16" rx="2" />
        </svg>
      </div>

      <div className="p-4">
        <div className="flex justify-between items-start mb-2">
          <h3 className="font-display font-semibold text-forest-deep">{room.name}</h3>
          <span className={`font-mono text-[10px] uppercase tracking-wider px-2 py-0.5 rounded-pill ${room.available ? "bg-[#E8F2EC] text-forest" : "bg-[#F5EAE6] text-clay"}`}>
            {room.available ? "Available" : "Booked"}
          </span>
        </div>
        <p className="text-sm text-ink-soft mb-3">{room.description}</p>

        <div className="flex flex-wrap gap-1.5 mb-3">
          {room.amenities.slice(0, 5).map((a) => (
            <span key={a} className="text-[10px] font-mono uppercase tracking-wider bg-sage border border-mist text-ink-soft px-2 py-0.5 rounded-pill">{a}</span>
          ))}
        </div>

        <div className="flex items-center justify-between">
          <div>
            <span className="font-mono text-xl font-semibold text-forest">{formatNightPrice(room.pricePerNight)}</span>
            <span className="text-xs text-ink-soft"> / night</span>
            <div className="text-xs text-ink-soft mt-0.5">Up to {room.capacity} guest{room.capacity !== 1 ? "s" : ""}</div>
          </div>
          <button
            disabled={!room.available}
            onClick={() => onBook(room)}
            className="inline-flex items-center justify-center font-semibold text-sm px-5 py-2 rounded-pill bg-forest text-white hover:bg-forest-deep transition-colors disabled:opacity-40 disabled:cursor-not-allowed"
          >
            Book now
          </button>
        </div>
      </div>
    </div>
  );
}

// Booking modal
function BookingModal({ room, accName, depositPercent, onClose, onConfirm }: {
  room: RoomType;
  accName: string;
  depositPercent: number;
  onClose: () => void;
  onConfirm: (data: { checkIn: string; checkOut: string; guests: number; name: string; phone: string; email: string; payment: string; ref: string; requests: string }) => Promise<void>;
}) {
  const [step,     setStep]     = useState<"details" | "payment" | "review">("details");
  const [checkIn,  setCheckIn]  = useState("");
  const [checkOut, setCheckOut] = useState("");
  const [guests,   setGuests]   = useState(1);
  const [name,     setName]     = useState("");
  const [phone,    setPhone]    = useState("");
  const [email,    setEmail]    = useState("");
  const [payment,  setPayment]  = useState<"mtn-momo" | "telecel-cash" | "cash-on-arrival">("mtn-momo");
  const [ref,      setRef]      = useState("");
  const [requests, setRequests] = useState("");
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const nights = checkIn && checkOut
    ? Math.max(0, Math.ceil((new Date(checkOut).getTime() - new Date(checkIn).getTime()) / 86400000))
    : 0;
  const total   = nights * room.pricePerNight;
  const deposit = Math.ceil(total * depositPercent / 100);

  const detailsValid = checkIn && checkOut && nights > 0 && guests >= 1 && name.trim() && phone.trim();
  const paymentValid = payment === "cash-on-arrival" || ref.trim().length >= 6;

  const inputCls = "w-full border border-mist rounded-sm px-4 py-2.5 text-sm bg-white text-ink focus:outline-2 focus:outline-gold focus:border-forest";

  async function handleConfirm() {
    setSubmitting(true);
    setError(null);
    try {
      await onConfirm({ checkIn, checkOut, guests, name, phone, email, payment, ref, requests });
    } catch (e) {
      setError(e instanceof ApiError ? e.message : "Booking failed. Please try again.");
      setSubmitting(false);
    }
  }

  return (
    <div className="fixed inset-0 z-50 flex items-end sm:items-center justify-center bg-ink/40 backdrop-blur-sm px-4 py-4 overflow-y-auto">
      <div className="bg-white rounded-xl border border-mist shadow-card-hover w-full max-w-lg my-auto">
        {/* Header */}
        <div className="flex justify-between items-center px-6 py-4 border-b border-mist">
          <div>
            <h3 className="font-display font-semibold text-lg text-forest-deep">{room.name}</h3>
            <p className="text-xs text-ink-soft">{accName}</p>
          </div>
          <button onClick={onClose} className="text-ink-soft hover:text-ink text-2xl leading-none w-8 h-8 flex items-center justify-center">×</button>
        </div>

        {/* Step tabs */}
        <div className="flex border-b border-mist">
          {(["details", "payment", "review"] as const).map((s, i) => (
            <div key={s} className={`flex-1 text-center py-2.5 text-xs font-mono uppercase tracking-wider border-b-2 transition-colors ${step === s ? "border-forest text-forest font-bold" : "border-transparent text-ink-soft"}`}>
              {i + 1}. {s}
            </div>
          ))}
        </div>

        <div className="p-6">
          {step === "details" && (
            <div className="flex flex-col gap-4">
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="block font-mono text-[10px] uppercase tracking-widest text-ink-soft mb-1.5">Check-in</label>
                  <input type="date" value={checkIn} onChange={(e) => setCheckIn(e.target.value)} className={inputCls} />
                </div>
                <div>
                  <label className="block font-mono text-[10px] uppercase tracking-widest text-ink-soft mb-1.5">Check-out</label>
                  <input type="date" value={checkOut} onChange={(e) => setCheckOut(e.target.value)} className={inputCls} />
                </div>
              </div>

              <div>
                <label className="block font-mono text-[10px] uppercase tracking-widest text-ink-soft mb-1.5">Number of guests (max {room.capacity})</label>
                <div className="flex items-center gap-3">
                  <button type="button" onClick={() => setGuests((g) => Math.max(1, g - 1))} className="w-9 h-9 rounded-full border border-mist flex items-center justify-center hover:bg-sage transition-colors font-bold text-forest">−</button>
                  <span className="font-mono font-semibold text-xl w-8 text-center">{guests}</span>
                  <button type="button" onClick={() => setGuests((g) => Math.min(room.capacity, g + 1))} className="w-9 h-9 rounded-full border border-mist flex items-center justify-center hover:bg-sage transition-colors font-bold text-forest">+</button>
                </div>
              </div>

              <div>
                <label className="block font-mono text-[10px] uppercase tracking-widest text-ink-soft mb-1.5">Full name</label>
                <input value={name} onChange={(e) => setName(e.target.value)} placeholder="Your full name" className={inputCls} />
              </div>
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="block font-mono text-[10px] uppercase tracking-widest text-ink-soft mb-1.5">Phone number</label>
                  <input type="tel" value={phone} onChange={(e) => setPhone(e.target.value)} placeholder="024 000 0000" className={inputCls} />
                </div>
                <div>
                  <label className="block font-mono text-[10px] uppercase tracking-widest text-ink-soft mb-1.5">Email (optional)</label>
                  <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="you@example.com" className={inputCls} />
                </div>
              </div>
              <div>
                <label className="block font-mono text-[10px] uppercase tracking-widest text-ink-soft mb-1.5">Special requests (optional)</label>
                <textarea value={requests} onChange={(e) => setRequests(e.target.value)} placeholder="e.g. early check-in, extra pillows…" rows={2} className={`${inputCls} resize-none`} />
              </div>

              {nights > 0 && (
                <div className="bg-sage border border-mist rounded-sm px-4 py-3 text-sm">
                  <div className="flex justify-between mb-1">
                    <span className="text-ink-soft">{formatNightPrice(room.pricePerNight)} × {nights} night{nights !== 1 ? "s" : ""}</span>
                    <span className="font-mono font-semibold">GH₵ {total.toLocaleString()}</span>
                  </div>
                  {depositPercent > 0 && (
                    <div className="flex justify-between text-xs text-gold-deep">
                      <span>Deposit required ({depositPercent}%)</span>
                      <span className="font-mono font-semibold">GH₵ {deposit.toLocaleString()}</span>
                    </div>
                  )}
                </div>
              )}
            </div>
          )}

          {step === "payment" && (
            <div className="flex flex-col gap-4">
              {/* Amount summary */}
              <div className="bg-sage border border-mist rounded-md px-4 py-3 text-sm">
                <div className="font-semibold text-forest-deep mb-2">{room.name} · {nights} night{nights !== 1 ? "s" : ""}</div>
                <div className="flex justify-between text-ink-soft">
                  <span>GH₵ {room.pricePerNight.toLocaleString()} × {nights} night{nights !== 1 ? "s" : ""}</span>
                  <span className="font-mono font-semibold text-ink">GH₵ {total.toLocaleString()}</span>
                </div>
                {depositPercent > 0 && (
                  <div className="flex justify-between text-gold-deep text-xs mt-1.5 pt-1.5 border-t border-mist">
                    <span>Deposit required now ({depositPercent}%)</span>
                    <span className="font-mono font-bold">GH₵ {deposit.toLocaleString()}</span>
                  </div>
                )}
              </div>

              {/* Payment method selector */}
              <div>
                <label className="block font-mono text-[10px] uppercase tracking-widest text-ink-soft mb-3">Select payment method</label>
                <div className="flex flex-col gap-2">
                  {[
                    {
                      value: "mtn-momo",
                      label: "MTN Mobile Money",
                      sub: "Pay with MTN MoMo — instant",
                      icon: (
                        <div className="w-9 h-9 rounded-full flex items-center justify-center shrink-0" style={{ background: "#FFCC00" }}>
                          <span className="font-bold text-[11px]" style={{ color: "#1A1A1A" }}>MTN</span>
                        </div>
                      ),
                    },
                    {
                      value: "telecel-cash",
                      label: "Telecel Cash",
                      sub: "Pay with Telecel Cash (Vodafone)",
                      icon: (
                        <div className="w-9 h-9 rounded-full flex items-center justify-center shrink-0" style={{ background: "#E2001A" }}>
                          <span className="font-bold text-[10px] text-white">TEL</span>
                        </div>
                      ),
                    },
                    {
                      value: "cash-on-arrival",
                      label: "Cash on arrival",
                      sub: "Pay the full amount when you check in",
                      icon: (
                        <div className="w-9 h-9 rounded-full bg-mist flex items-center justify-center shrink-0">
                          <svg viewBox="0 0 24 24" fill="none" stroke="#5B6B63" strokeWidth="1.8" className="w-5 h-5">
                            <rect x="2" y="6" width="20" height="12" rx="2"/><circle cx="12" cy="12" r="2"/>
                            <path d="M6 12h.01M18 12h.01" strokeLinecap="round"/>
                          </svg>
                        </div>
                      ),
                    },
                  ].map((opt) => (
                    <label key={opt.value}
                      className={`flex items-center gap-3 p-3 border-2 rounded-md cursor-pointer transition-colors ${payment === opt.value ? "border-forest bg-[#E8F2EC]" : "border-mist bg-white hover:border-forest"}`}>
                      <input type="radio" name="payment" value={opt.value}
                        checked={payment === opt.value}
                        onChange={() => { setPayment(opt.value as typeof payment); setRef(""); }}
                        className="accent-forest shrink-0" />
                      {opt.icon}
                      <div>
                        <div className="text-sm font-semibold text-forest-deep">{opt.label}</div>
                        <div className="text-xs text-ink-soft">{opt.sub}</div>
                      </div>
                    </label>
                  ))}
                </div>
              </div>

              {/* MTN MoMo USSD flow */}
              {payment === "mtn-momo" && (
                <div className="border border-mist rounded-md overflow-hidden">
                  <div className="flex items-center gap-2 px-4 py-3 border-b border-mist" style={{ background: "#FFCC00" }}>
                    <span className="font-bold text-sm" style={{ color: "#1A1A1A" }}>MTN Mobile Money — How to pay</span>
                  </div>
                  <div className="p-4 flex flex-col gap-3">
                    {[
                      { n: "1", text: <>Dial <strong className="font-mono text-forest">*170#</strong> on your MTN line</> },
                      { n: "2", text: <>Select <strong>1</strong> — Transfer Money</> },
                      { n: "3", text: <>Select <strong>2</strong> — MoMo User</> },
                      { n: "4", text: <>Enter Villa&apos;s merchant number: <strong className="font-mono text-forest">0241234567</strong></> },
                      { n: "5", text: <>Enter amount: <strong className="font-mono text-forest">GH₵ {deposit.toLocaleString()}</strong></> },
                      { n: "6", text: <>Enter your PIN and confirm. You will receive an SMS with your transaction ID.</> },
                    ].map(({ n, text }) => (
                      <div key={n} className="flex items-start gap-3 text-sm">
                        <div className="w-6 h-6 rounded-full flex items-center justify-center text-xs font-bold shrink-0 text-forest-deep" style={{ background: "#FFCC00" }}>{n}</div>
                        <p className="text-ink-soft leading-snug">{text}</p>
                      </div>
                    ))}
                    <div className="bg-[#FBF1E1] border border-gold rounded-sm px-3 py-2 text-xs text-gold-deep">
                      Send <strong>GH₵ {deposit.toLocaleString()}</strong> to <strong>0241234567 (Villa Payments)</strong>. Your booking reference will be sent by SMS once payment is verified.
                    </div>
                    <div>
                      <label className="block font-mono text-[10px] uppercase tracking-widest text-ink-soft mb-1.5">Enter your MTN MoMo transaction ID</label>
                      <input value={ref} onChange={(e) => setRef(e.target.value)}
                        placeholder="e.g. MTN-2026-88271"
                        className="w-full border border-mist rounded-sm px-4 py-2.5 text-sm font-mono focus:outline-2 focus:outline-gold focus:border-forest" />
                      <p className="text-xs text-ink-soft mt-1.5">Found in the SMS confirmation from MTN after payment.</p>
                    </div>
                  </div>
                </div>
              )}

              {/* Telecel Cash USSD flow */}
              {payment === "telecel-cash" && (
                <div className="border border-mist rounded-md overflow-hidden">
                  <div className="flex items-center gap-2 px-4 py-3 border-b border-mist" style={{ background: "#E2001A" }}>
                    <span className="font-bold text-sm text-white">Telecel Cash — How to pay</span>
                  </div>
                  <div className="p-4 flex flex-col gap-3">
                    {[
                      { n: "1", text: <>Dial <strong className="font-mono text-forest">*110#</strong> on your Telecel line</> },
                      { n: "2", text: <>Select <strong>1</strong> — Send Money</> },
                      { n: "3", text: <>Select <strong>2</strong> — To Telecel Cash User</> },
                      { n: "4", text: <>Enter Villa&apos;s number: <strong className="font-mono text-forest">0201234567</strong></> },
                      { n: "5", text: <>Enter amount: <strong className="font-mono text-forest">GH₵ {deposit.toLocaleString()}</strong></> },
                      { n: "6", text: <>Enter your PIN and confirm. You will receive an SMS with your transaction ID.</> },
                    ].map(({ n, text }) => (
                      <div key={n} className="flex items-start gap-3 text-sm">
                        <div className="w-6 h-6 rounded-full flex items-center justify-center text-xs font-bold text-white shrink-0" style={{ background: "#E2001A" }}>{n}</div>
                        <p className="text-ink-soft leading-snug">{text}</p>
                      </div>
                    ))}
                    <div className="bg-[#FBF1E1] border border-gold rounded-sm px-3 py-2 text-xs text-gold-deep">
                      Send <strong>GH₵ {deposit.toLocaleString()}</strong> to <strong>0201234567 (Villa Payments)</strong>. Verification may take up to 5 minutes.
                    </div>
                    <div>
                      <label className="block font-mono text-[10px] uppercase tracking-widest text-ink-soft mb-1.5">Enter your Telecel Cash transaction ID</label>
                      <input value={ref} onChange={(e) => setRef(e.target.value)}
                        placeholder="e.g. TC-2026-44891"
                        className="w-full border border-mist rounded-sm px-4 py-2.5 text-sm font-mono focus:outline-2 focus:outline-gold focus:border-forest" />
                      <p className="text-xs text-ink-soft mt-1.5">Found in the SMS confirmation from Telecel after payment.</p>
                    </div>
                  </div>
                </div>
              )}

              {/* Cash on arrival notice */}
              {payment === "cash-on-arrival" && (
                <div className="bg-[#FBF1E1] border border-gold rounded-md px-4 py-4 text-sm text-gold-deep">
                  <div className="font-semibold mb-1">Important — cash payment</div>
                  <ul className="text-xs space-y-1 text-gold-deep/80 list-disc pl-4">
                    <li>Pay <strong>GH₵ {total.toLocaleString()}</strong> in full on arrival at the property</li>
                    <li>Your booking will be held for <strong>2 hours</strong> after scheduled check-in time</li>
                    <li>Please have the exact amount ready — change may not be available</li>
                    <li>A receipt will be issued by the property on payment</li>
                  </ul>
                </div>
              )}
            </div>
          )}

          {step === "review" && (
            <div className="flex flex-col gap-4">
              <div className="text-sm font-mono uppercase tracking-widest text-gold-deep mb-1">Review your booking</div>
              {[
                ["Property", accName],
                ["Room", room.name],
                ["Check-in", checkIn],
                ["Check-out", checkOut],
                ["Nights", String(nights)],
                ["Guests", String(guests)],
                ["Guest name", name],
                ["Phone", phone],
                ["Payment", payment === "mtn-momo" ? `MTN MoMo (${ref})` : payment === "telecel-cash" ? `Telecel Cash (${ref})` : "Cash on arrival"],
                ["Total", `GH₵ ${total.toLocaleString()}`],
              ].map(([label, value]) => (
                <div key={label} className="flex justify-between py-2 border-b border-mist last:border-b-0 text-sm">
                  <span className="text-ink-soft">{label}</span>
                  <span className="font-medium text-ink text-right max-w-[60%]">{value}</span>
                </div>
              ))}
              {requests && (
                <div className="bg-sage border border-mist rounded-sm px-3 py-2 text-xs text-ink-soft">
                  <strong className="text-ink">Requests:</strong> {requests}
                </div>
              )}
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="px-6 pb-5 flex justify-between items-center border-t border-mist pt-4">
          {step === "details" && (
            <>
              <button onClick={onClose} className="inline-flex items-center font-semibold text-sm px-5 py-2.5 rounded-pill border border-mist text-forest hover:bg-forest hover:border-forest hover:text-white transition-colors">Cancel</button>
              <button disabled={!detailsValid} onClick={() => setStep("payment")}
                className="inline-flex items-center font-semibold text-sm px-6 py-2.5 rounded-pill bg-forest text-white hover:bg-forest-deep transition-colors disabled:opacity-40">
                Continue to payment →
              </button>
            </>
          )}
          {step === "payment" && (
            <>
              <button onClick={() => setStep("details")} className="inline-flex items-center font-semibold text-sm px-5 py-2.5 rounded-pill border border-mist text-forest hover:bg-forest hover:border-forest hover:text-white transition-colors">← Back</button>
              <button disabled={!paymentValid} onClick={() => setStep("review")}
                className="inline-flex items-center font-semibold text-sm px-6 py-2.5 rounded-pill bg-forest text-white hover:bg-forest-deep transition-colors disabled:opacity-40">
                Review booking →
              </button>
            </>
          )}
          {step === "review" && (
            <>
              {error && <p className="w-full text-sm text-red-600 mb-2">{error}</p>}
              <button onClick={() => setStep("payment")} className="inline-flex items-center font-semibold text-sm px-5 py-2.5 rounded-pill border border-mist text-forest hover:bg-forest hover:border-forest hover:text-white transition-colors">← Back</button>
              <button disabled={submitting} onClick={handleConfirm}
                className="inline-flex items-center gap-2 font-semibold text-sm px-6 py-2.5 rounded-pill bg-gold text-forest-deep hover:bg-forest hover:text-white transition-colors disabled:opacity-60">
                {submitting ? (
                  <><div className="w-4 h-4 border-2 border-forest-deep border-t-transparent rounded-full animate-spin" /> Confirming…</>
                ) : "Confirm booking"}
              </button>
            </>
          )}
        </div>
      </div>
    </div>
  );
}

export default function AccommodationDetail({ acc }: { acc: import("@/lib/mock-data").Accommodation }) {
  const [bookingRoom, setBookingRoom]   = useState<RoomType | null>(null);
  const [confirmed,   setConfirmed]     = useState(false);
  const [bookingRef,  setBookingRef]    = useState("");
  const [lastBooking, setLastBooking]   = useState<{
    roomTypeName: string; checkIn: string; checkOut: string; guests: number;
    totalPrice: number; depositAmount: number; paymentMethod: string; paymentReference?: string;
  } | null>(null);

  const [reviews, setReviews] = useState<Review[]>([]);
  const [avgRating, setAvgRating] = useState(acc.rating ?? 0);

  useEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        const [page, summary] = await Promise.all([
          clientExecute<Paginated<Review>>("review.find-by-target", { targetId: acc.id, limit: 5 }),
          clientExecute<{ average: number }>("review.get-summary", { targetId: acc.id }),
        ]);
        if (cancelled) return;
        setReviews(page.items);
        setAvgRating(summary.average || acc.rating || 0);
      } catch {
        /* leave defaults */
      }
    })();
    return () => { cancelled = true; };
  }, [acc.id, acc.rating]);

  const typeLabel = {
    hotel: "Hotel", guesthouse: "Guesthouse", lodge: "Lodge", "serviced-apartment": "Serviced Apartment",
  }[acc.type] ?? acc.type;

  function handleConfirm() {
    const ref = `VBK-${Date.now().toString().slice(-6)}`;
    setBookingRef(ref);
    setConfirmed(true);
    setBookingRoom(null);
  }

  // Creates the booking via the API (deposit/total/reference computed server-side;
  // the backend also fires the guest + owner SMS). Throws on failure so the modal
  // can surface the error and stay open.
  async function handleBookingConfirm(
    data: { checkIn: string; checkOut: string; guests: number; name: string; phone: string; email: string; payment: string; ref: string; requests: string },
    room: RoomType,
  ) {
    const booking = await clientExecute<AccommodationBooking>("booking.create", {
      accommodationId: acc.id,
      roomTypeId: room.id,
      checkIn: data.checkIn,
      checkOut: data.checkOut,
      guests: data.guests,
      guestName: data.name,
      guestPhone: data.phone,
      guestEmail: data.email || undefined,
      paymentMethod: data.payment,
      paymentReference: data.ref || undefined,
      specialRequests: data.requests || undefined,
    });

    setLastBooking({
      roomTypeName: booking.roomTypeName,
      checkIn: booking.checkIn,
      checkOut: booking.checkOut,
      guests: booking.guests,
      totalPrice: booking.totalPrice,
      depositAmount: booking.depositAmount,
      paymentMethod: booking.paymentMethod,
      paymentReference: booking.paymentReference,
    });
    setBookingRef(booking.reference ?? booking.id);
    setConfirmed(true);
    setBookingRoom(null);
  }

  if (confirmed) {
    return (
      <div className="max-w-xl mx-auto px-6 py-16">
        {/* Success header */}
        <div className="text-center mb-8">
          <div className="w-20 h-20 rounded-full bg-[#E8F2EC] flex items-center justify-center mx-auto mb-5">
            <svg viewBox="0 0 24 24" fill="none" stroke="#1E4A3D" strokeWidth="2" className="w-10 h-10">
              <path d="M5 12l5 5 9-11" strokeLinecap="round" strokeLinejoin="round" />
            </svg>
          </div>
          <div className="font-mono text-xs uppercase tracking-widest text-gold-deep mb-2">Booking submitted</div>
          <h1 className="font-display font-semibold text-2xl text-forest-deep mb-2">Request sent to {acc.name}</h1>
          <p className="text-sm text-ink-soft">The property will confirm within a few hours. You will receive an SMS to the number you provided.</p>
        </div>

        {/* Receipt card */}
        <div className="bg-white border border-mist rounded-lg overflow-hidden shadow-card mb-6">
          {/* Receipt header */}
          <div className="bg-forest px-5 py-4 flex items-center justify-between">
            <div>
              <div className="font-mono text-xs text-white/60 uppercase tracking-wider mb-1">Booking receipt</div>
              <div className="font-mono font-bold text-xl text-white">{bookingRef}</div>
            </div>
            <div className="w-10 h-10 rounded-full bg-white/10 flex items-center justify-center">
              <svg viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="1.6" className="w-6 h-6">
                <path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z"/><polyline points="14 2 14 8 20 8"/>
                <line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/>
              </svg>
            </div>
          </div>

          {/* Receipt details */}
          <div className="divide-y divide-mist">
            {[
              ["Property",  acc.name],
              ["Room",      lastBooking?.roomTypeName ?? ""],
              ["Check-in",  lastBooking?.checkIn ?? ""],
              ["Check-out", lastBooking?.checkOut ?? ""],
              ["Guests",    String(lastBooking?.guests ?? 1)],
              ["Total",     `GH₵ ${(lastBooking?.totalPrice ?? 0).toLocaleString()}`],
              ["Deposit paid", `GH₵ ${(lastBooking?.depositAmount ?? 0).toLocaleString()}`],
              ["Balance due on arrival", `GH₵ ${((lastBooking?.totalPrice ?? 0) - (lastBooking?.depositAmount ?? 0)).toLocaleString()}`],
            ].map(([label, value]) => (
              <div key={label as string} className="flex justify-between px-5 py-3 text-sm">
                <span className="text-ink-soft">{label}</span>
                <span className="font-medium text-ink text-right">{value}</span>
              </div>
            ))}
          </div>

          {/* Payment status */}
          <div className="px-5 py-4 border-t border-mist bg-sage/40">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-2">
                <div className="w-2 h-2 rounded-full bg-gold animate-pulse" />
                <span className="text-sm font-semibold text-gold-deep">
                  {lastBooking?.paymentMethod === "cash-on-arrival" ? "Cash — payable on arrival" : "Payment verification pending"}
                </span>
              </div>
              {lastBooking?.paymentReference && (
                <span className="font-mono text-xs text-ink-soft">{lastBooking.paymentReference}</span>
              )}
            </div>
            {lastBooking?.paymentMethod !== "cash-on-arrival" && (
              <p className="text-xs text-ink-soft mt-1">Villa will verify your payment reference within 30 minutes and send SMS confirmation.</p>
            )}
          </div>
        </div>

        {/* Actions */}
        <div className="flex flex-col sm:flex-row gap-3 justify-center">
          <Link href="/dashboard" className="inline-flex items-center justify-center font-semibold text-sm px-6 py-3 rounded-pill bg-forest text-white hover:bg-forest-deep transition-colors">
            View my bookings
          </Link>
          <Link href="/stay" className="inline-flex items-center justify-center font-semibold text-sm px-6 py-3 rounded-pill border border-mist text-forest hover:bg-forest hover:border-forest hover:text-white transition-colors">
            Browse more stays
          </Link>
        </div>
      </div>
    );
  }

  return (
    <div className="max-w-6xl mx-auto px-6 py-8">
      {/* Breadcrumb */}
      <div className="text-sm text-ink-soft mb-5">
        <Link href="/" className="hover:text-forest">Home</Link> {" / "}
        <Link href="/stay" className="hover:text-forest">Villa Stay</Link> {" / "}
        {acc.name}
      </div>

      {/* Hero */}
      <div className="grid grid-cols-1 lg:grid-cols-[1fr_320px] gap-8 items-start">
        <div>
          {/* Photo grid */}
          <div className="grid grid-cols-3 gap-2 mb-6 rounded-xl overflow-hidden">
            <div className="col-span-2 bg-gradient-to-br from-[#1E3A30] to-[#2A5244] h-64 flex items-center justify-center">
              <span className="text-white/20 font-mono text-xs uppercase tracking-wider">Main photo</span>
            </div>
            <div className="grid grid-rows-2 gap-2">
              <div className="bg-gradient-to-br from-[#2A4A3A] to-[#1E3A30] flex items-center justify-center">
                <span className="text-white/20 font-mono text-xs uppercase tracking-wider text-center px-2">Room</span>
              </div>
              <div className="bg-gradient-to-br from-[#1E3030] to-[#2A3A35] flex items-center justify-center">
                <span className="text-white/20 font-mono text-xs uppercase tracking-wider text-center px-2">View</span>
              </div>
            </div>
          </div>

          {/* Name + rating */}
          <div className="flex flex-wrap justify-between items-start gap-4 mb-4">
            <div>
              <div className="flex items-center gap-2 mb-1">
                <span className="font-mono text-xs uppercase tracking-wider text-gold-deep">{typeLabel}</span>
                {acc.status === "verified" && (
                  <span className="font-mono text-[10px] uppercase tracking-wider bg-[#E8F2EC] text-forest border border-forest/20 px-2 py-0.5 rounded-pill">
                    Villa verified
                  </span>
                )}
              </div>
              <h1 className="font-display font-semibold text-3xl text-forest-deep">{acc.name}</h1>
              <p className="text-ink-soft">{acc.address}</p>
            </div>
            <div className="text-right">
              <div className="flex items-center justify-end gap-2 mb-1">
                <span className="font-mono text-2xl font-bold text-forest">
                  GH₵ {Math.min(...acc.rooms.map((r) => r.pricePerNight))}
                </span>
                <span className="text-ink-soft text-sm">/ night</span>
              </div>
              <div className="flex items-center justify-end gap-1">
                {[1, 2, 3, 4, 5].map((s) => (
                  <svg key={s} viewBox="0 0 24 24" className="w-4 h-4" fill={s <= Math.round(acc.rating) ? "#D7A23E" : "none"} stroke="#D7A23E" strokeWidth="1.5">
                    <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2" />
                  </svg>
                ))}
                <span className="text-sm text-ink-soft ml-1">{acc.rating} ({acc.reviewCount} reviews)</span>
              </div>
            </div>
          </div>

          {/* About */}
          <section className="mb-8">
            <h2 className="font-display font-semibold text-xl text-forest-deep mb-3">About this place</h2>
            <p className="text-ink-soft text-[15px] leading-relaxed">{acc.description}</p>
          </section>

          {/* Amenities */}
          <section className="mb-8">
            <h2 className="font-display font-semibold text-xl text-forest-deep mb-3">Amenities</h2>
            <div className="grid grid-cols-2 sm:grid-cols-3 gap-2">
              {acc.amenities.map((a) => (
                <div key={a} className="flex items-center gap-2 text-sm bg-white border border-mist rounded-sm px-3 py-2">
                  <svg viewBox="0 0 24 24" fill="none" stroke="#1E4A3D" strokeWidth="2" className="w-4 h-4 shrink-0">
                    <path d="M5 12l5 5 9-11" strokeLinecap="round" strokeLinejoin="round" />
                  </svg>
                  {a}
                </div>
              ))}
            </div>
          </section>

          {/* Room types */}
          <section className="mb-8">
            <h2 className="font-display font-semibold text-xl text-forest-deep mb-1">Available rooms</h2>
            <p className="text-sm text-ink-soft mb-4">Select a room type to see details and book.</p>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              {acc.rooms.map((room) => (
                <RoomCard key={room.id} room={room} onBook={setBookingRoom} />
              ))}
            </div>
          </section>

          {/* Policies */}
          <section className="mb-8">
            <h2 className="font-display font-semibold text-xl text-forest-deep mb-3">Policies</h2>
            <div className="bg-white border border-mist rounded-md p-5">
              {[
                { label: "Check-in", value: acc.checkInTime },
                { label: "Check-out", value: acc.checkOutTime },
                { label: "Cancellation", value: acc.cancellationPolicy },
                { label: "Deposit", value: acc.depositRequired ? `${acc.depositPercent}% of booking total required to confirm` : "No deposit required — pay on arrival" },
              ].map(({ label, value }) => (
                <div key={label} className="flex gap-4 py-3 border-b border-mist last:border-b-0 text-sm">
                  <span className="text-ink-soft w-28 shrink-0">{label}</span>
                  <span className="text-ink">{value}</span>
                </div>
              ))}
            </div>
          </section>
        </div>

        {/* Sticky sidebar CTA */}
        <aside className="bg-white border border-mist rounded-xl p-5 shadow-card lg:sticky lg:top-[96px]">
          {acc.status === "verified" && (
            <div className="flex items-center gap-2 mb-4">
              <VerificationStamp variant="property" size={40} />
              <div>
                <div className="text-xs font-semibold text-forest">Villa verified</div>
                <div className="text-xs text-ink-soft">Photos and details confirmed</div>
              </div>
            </div>
          )}

          <div className="font-mono text-2xl font-bold text-forest mb-0.5">
            GH₵ {Math.min(...acc.rooms.map((r) => r.pricePerNight))}
          </div>
          <div className="text-xs text-ink-soft mb-4">per night · from</div>

          <div className="flex flex-col gap-3 text-sm border-t border-mist pt-4 mb-5">
            <div className="flex justify-between">
              <span className="text-ink-soft">Check-in</span>
              <span className="font-mono">{acc.checkInTime}</span>
            </div>
            <div className="flex justify-between">
              <span className="text-ink-soft">Check-out</span>
              <span className="font-mono">{acc.checkOutTime}</span>
            </div>
            <div className="flex justify-between">
              <span className="text-ink-soft">Rooms available</span>
              <span className="font-mono">{acc.rooms.filter((r) => r.available).length} of {acc.rooms.length}</span>
            </div>
          </div>

          <p className="text-xs text-ink-soft mb-4">Choose a room type above and click Book now to start your booking.</p>

          <div className="text-xs text-ink-soft flex items-center gap-1.5">
            <svg viewBox="0 0 24 24" fill="none" stroke="#5B6B63" strokeWidth="1.8" className="w-4 h-4 shrink-0">
              <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z" />
            </svg>
            Booking is free to request — you only pay the deposit once confirmed
          </div>
        </aside>
      </div>

      {/* Reviews */}
      <div className="mt-10">
        <ReviewsSection
          targetId={acc.id}
          targetName={acc.name}
          targetType="accommodation"
          initialReviews={reviews}
          averageRating={avgRating}
          showWriteReview={true}
        />
      </div>

      {/* Booking modal */}
      {bookingRoom && (
        <BookingModal
          room={bookingRoom}
          accName={acc.name}
          depositPercent={acc.depositPercent}
          onClose={() => setBookingRoom(null)}
          onConfirm={(data) => handleBookingConfirm(data, bookingRoom)}
        />
      )}
    </div>
  );
}
