"use client";

import { useState, useEffect, ReactNode } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import VillaLogo from "@/components/VillaLogo";
import VerificationStamp from "@/components/VerificationStamp";
import { formatNightPrice } from "@/lib/mock-data";
import type { AccommodationBooking, Accommodation, RoomType, Paginated } from "@/lib/types";
import { useToast, useConfirm } from "@/components/SharedUI";
import TablePagination, { usePagination } from "@/components/TablePagination";
import StatusBadge from "@/components/StatusBadge";
import { clientExecute } from "@/lib/api/client";
import { ApiError } from "@/lib/api/shared";
import { useAuth } from "@/lib/auth-context";
import { Spinner, PageLoader } from "@/components/Loading";

type Section = "overview" | "bookings" | "calendar" | "rooms" | "earnings" | "settings";

function Btn({ children, onClick, variant = "primary", disabled = false }: {
  children: ReactNode; onClick?: () => void; variant?: "primary" | "ghost" | "danger"; disabled?: boolean;
}) {
  const s = { primary: "bg-forest text-white hover:bg-forest-deep", ghost: "border border-mist text-forest hover:bg-forest hover:border-forest hover:text-white", danger: "bg-clay text-white hover:opacity-90" };
  return <button disabled={disabled} onClick={onClick} className={`inline-flex items-center justify-center gap-1.5 font-semibold text-sm px-5 py-2 rounded-pill transition-colors disabled:opacity-40 whitespace-nowrap ${s[variant]}`}>{children}</button>;
}

function Card({ children, className = "" }: { children: ReactNode; className?: string }) {
  return <div className={`bg-white border border-mist rounded-md overflow-hidden ${className}`}>{children}</div>;
}

function StatCard({ label, value, sub, color = "forest" }: { label: string; value: string; sub?: string; color?: string }) {
  return (
    <div className="bg-white border border-mist rounded-md p-5">
      <div className="font-mono text-xs uppercase tracking-widest text-ink-soft mb-2">{label}</div>
      <div className={`font-display text-3xl font-semibold text-${color}-deep mb-1`}>{value}</div>
      {sub && <div className="text-xs text-ink-soft">{sub}</div>}
    </div>
  );
}

function BookingStatusBadge({ status }: { status: AccommodationBooking["status"] }) {
  const cfg: Record<string, { label: string; cls: string }> = {
    pending:    { label: "Pending",    cls: "bg-[#FBF1E1] text-gold-deep border-gold" },
    confirmed:  { label: "Confirmed",  cls: "bg-[#E8F2EC] text-forest border-forest" },
    declined:   { label: "Declined",   cls: "bg-[#F5EAE6] text-clay border-clay" },
    "checked-in": { label: "Checked in", cls: "bg-[#E8F2EC] text-forest border-forest" },
    completed:  { label: "Completed",  cls: "bg-mist text-ink-soft border-mist" },
    cancelled:  { label: "Cancelled",  cls: "bg-[#F5EAE6] text-clay border-clay" },
  };
  const { label, cls } = cfg[status] ?? cfg.pending;
  return <span className={`inline-flex items-center gap-1.5 font-mono text-[10px] uppercase tracking-wider px-3 py-1.5 rounded-pill border font-medium ${cls}`}><span className="w-1.5 h-1.5 rounded-full bg-current" />{label}</span>;
}

// Mini calendar showing bookings by date
function BookingCalendar({ bookings }: { bookings: AccommodationBooking[] }) {
  const now = new Date();
  const year = now.getFullYear();
  const month = now.getMonth();
  const daysInMonth = new Date(year, month + 1, 0).getDate();
  const firstDay = new Date(year, month, 1).getDay();
  const monthName = now.toLocaleString("default", { month: "long" });

  function isBooked(day: number): boolean {
    const dateStr = `${year}-${String(month + 1).padStart(2, "0")}-${String(day).padStart(2, "0")}`;
    return bookings.some((b) => b.status !== "cancelled" && b.status !== "declined" && b.checkIn <= dateStr && b.checkOut > dateStr);
  }

  return (
    <div className="bg-white border border-mist rounded-md p-5">
      <div className="font-display font-semibold text-lg text-forest-deep mb-4">{monthName} {year}</div>
      <div className="grid grid-cols-7 gap-1 mb-2">
        {["Su","Mo","Tu","We","Th","Fr","Sa"].map((d) => (
          <div key={d} className="text-center font-mono text-[10px] uppercase text-ink-soft">{d}</div>
        ))}
      </div>
      <div className="grid grid-cols-7 gap-1">
        {Array.from({ length: firstDay }).map((_, i) => <div key={`e${i}`} />)}
        {Array.from({ length: daysInMonth }, (_, i) => i + 1).map((day) => {
          const booked = isBooked(day);
          const today = day === now.getDate();
          return (
            <div key={day} className={`aspect-square rounded-sm flex items-center justify-center text-sm font-mono transition-colors ${
              today ? "bg-forest text-white font-bold" :
              booked ? "bg-gold/20 text-gold-deep border border-gold/30" :
              "text-ink-soft hover:bg-sage"
            }`}>
              {day}
            </div>
          );
        })}
      </div>
      <div className="flex gap-4 mt-3 text-xs text-ink-soft">
        <span className="flex items-center gap-1.5"><span className="w-3 h-3 rounded-sm bg-gold/20 border border-gold/30 inline-block" />Booked</span>
        <span className="flex items-center gap-1.5"><span className="w-3 h-3 rounded-sm bg-forest inline-block" />Today</span>
      </div>
    </div>
  );
}

export default function AccommodationDashboardPage() {
  const router = useRouter();
  const { user, loading: authLoading, logout } = useAuth();

  const [kycStatus, setKycStatus] = useState<"not_started" | "pending" | "approved" | "rejected">("not_started");
  const [section, setSection] = useState<Section>("overview");
  const [accommodation, setAccommodation] = useState<Accommodation | null>(null);
  const [bookings, setBookings] = useState<AccommodationBooking[]>([]);
  const [settingsForm, setSettingsForm] = useState({
    name: "", type: "guesthouse", town: "", address: "", checkInTime: "", checkOutTime: "",
    depositPercent: 0, ownerPhone: "", cancellationPolicy: "",
  });
  const [savingSettings, setSavingSettings] = useState(false);

  type EditableRoom = { id: string; name: string; capacity: number; price: number; description: string; available: boolean; isNew?: boolean };
  const [editableRooms, setEditableRooms] = useState<EditableRoom[]>([]);
  const [editingRoom, setEditingRoom] = useState<EditableRoom & { isNew?: boolean } | null>(null);

  const { show: showToast, node: toastNode } = useToast();
  const { confirm, node: confirmNode } = useConfirm();

  const accId = accommodation?.id ?? "";

  async function loadData() {
    try {
      const acc = await clientExecute<Accommodation>("accommodation.find-by-owner");
      setAccommodation(acc);
      setEditableRooms((acc?.rooms ?? []).map((r: RoomType) => ({ id: r.id, name: r.name, capacity: r.capacity, price: r.pricePerNight, description: r.description, available: r.available })));
      if (acc) setSettingsForm({
        name: acc.name, type: acc.type, town: acc.town, address: acc.address,
        checkInTime: acc.checkInTime, checkOutTime: acc.checkOutTime, depositPercent: acc.depositPercent,
        ownerPhone: acc.ownerPhone, cancellationPolicy: acc.cancellationPolicy,
      });
    } catch { /* ignore */ }
    try {
      const s = await clientExecute<{ status: "not_started" | "pending" | "approved" | "rejected" }>("stay-kyc.get-status");
      setKycStatus(s.status);
    } catch { /* ignore */ }
    try {
      const b = await clientExecute<Paginated<AccommodationBooking>>("booking.find-by-owner", { limit: 100 });
      setBookings(b.items);
    } catch { /* ignore */ }
  }
  useEffect(() => { void loadData(); }, []);

  async function toggleRoomAvailability(id: string) {
    const room = editableRooms.find((r) => r.id === id);
    try {
      await clientExecute("accommodation.toggle-room-availability", { accommodationId: accId, roomId: id });
      setEditableRooms((prev) => prev.map((r) => r.id === id ? { ...r, available: !r.available } : r));
      if (room) showToast(`${room.name} marked as ${room.available ? "unavailable" : "available"}`);
    } catch (e) { showToast(e instanceof ApiError ? e.message : "Couldn't update.", "error"); }
  }

  async function handleLogout() { await logout(); router.push("/"); router.refresh(); }

  async function handleSaveSettings() {
    setSavingSettings(true);
    try {
      const updated = await clientExecute<Accommodation>("accommodation.update-settings", {
        id: accId,
        name: settingsForm.name, type: settingsForm.type, town: settingsForm.town, address: settingsForm.address,
        checkInTime: settingsForm.checkInTime, checkOutTime: settingsForm.checkOutTime,
        depositPercent: Number(settingsForm.depositPercent), ownerPhone: settingsForm.ownerPhone,
        cancellationPolicy: settingsForm.cancellationPolicy,
      });
      setAccommodation(updated);
      showToast("Property settings saved");
    } catch (e) { showToast(e instanceof ApiError ? e.message : "Couldn't save settings.", "error"); }
    finally { setSavingSettings(false); }
  }

  const bookingsPag = usePagination(bookings, 5);

  const pending   = bookings.filter((b) => b.status === "pending");
  const confirmed = bookings.filter((b) => b.status === "confirmed" || b.status === "checked-in");
  const completed = bookings.filter((b) => b.status === "completed");
  const totalRevenue = completed.reduce((sum, b) => sum + b.depositAmount, 0);

  async function handleConfirmBooking(b: AccommodationBooking) {
    const ok = await confirm({ title: "Confirm this booking?", body: `${b.guestName} — ${b.roomTypeName} · ${b.checkIn} to ${b.checkOut}`, confirmLabel: "Confirm booking" });
    if (ok) {
      try {
        await clientExecute("booking.confirm", { id: b.id });
        setBookings((prev) => prev.map((x) => x.id === b.id ? { ...x, status: "confirmed" } : x));
        showToast(`Booking confirmed for ${b.guestName}`);
      } catch (e) { showToast(e instanceof ApiError ? e.message : "Couldn't confirm.", "error"); }
    }
  }

  async function handleDeclineBooking(b: AccommodationBooking) {
    const ok = await confirm({ title: "Decline this booking?", body: `${b.guestName}'s booking request will be cancelled.`, confirmLabel: "Decline", danger: true });
    if (ok) {
      try {
        await clientExecute("booking.decline", { id: b.id });
        setBookings((prev) => prev.map((x) => x.id === b.id ? { ...x, status: "declined" } : x));
        showToast(`${b.guestName}'s booking declined`, "info");
      } catch (e) { showToast(e instanceof ApiError ? e.message : "Couldn't decline.", "error"); }
    }
  }

  // Access is gated by middleware (accommodation_owner). Show a loader while the
  // session hydrates rather than a separate in-page login form.
  if (authLoading || !user) {
    return (
      <div className="max-w-6xl mx-auto px-6 min-h-[60vh] flex items-center justify-center">
        <PageLoader label="Loading your dashboard" />
      </div>
    );
  }

  // KYC gate render
  if (kycStatus !== "approved") {
    return (
      <div className="max-w-3xl mx-auto px-6 py-12">
        <div className="grid grid-cols-1 lg:grid-cols-[240px_1fr] gap-8 items-start">
          <div className="bg-white border border-mist rounded-md p-5">
            <div className="font-display font-semibold text-lg text-forest-deep">{accommodation?.name ?? "Your property"}</div>
            <div className="font-mono text-xs uppercase tracking-widest text-ink-soft mb-3">Accommodation owner</div>
            <span className={`inline-flex items-center gap-1.5 font-mono text-xs uppercase tracking-wider px-3 py-1.5 rounded-pill border ${kycStatus === "pending" ? "bg-[#FBF1E1] text-gold-deep border-gold" : "bg-mist text-ink-soft border-mist"}`}>
              <span className="w-1.5 h-1.5 rounded-full bg-current" />
              {kycStatus === "pending" ? "KYC under review" : "KYC required"}
            </span>
            <div className="mt-4 pt-4 border-t border-mist flex flex-col gap-1 opacity-40 select-none">
              {["Overview","Bookings","Calendar","Rooms & rates","Earnings","Settings"].map((l) => (
                <div key={l} className="flex items-center gap-3 px-3 py-2.5 text-sm text-ink-soft">{l}</div>
              ))}
            </div>
            <p className="text-xs text-ink-soft mt-4 pt-4 border-t border-mist">Dashboard unlocks after KYC approval.</p>
          </div>
          <div className="max-w-xl py-8 px-6 text-center">
            {kycStatus === "not_started" ? (
              <>
                <VerificationStamp variant="pending" size={80} className="mx-auto mb-6" />
                <h2 className="font-display font-semibold text-2xl text-forest-deep mb-3">Verify your identity to go live</h2>
                <p className="text-ink-soft mb-8 max-w-[44ch] mx-auto">
                  All accommodation owners on Villa Stay must complete identity and property authority verification before their listing goes live. This protects guests and builds platform trust.
                </p>
                <div className="bg-white border border-mist rounded-md p-5 mb-8 text-left">
                  {[
                    { icon: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" className="w-5 h-5"><rect x="2" y="5" width="20" height="14" rx="2"/><circle cx="8" cy="12" r="2"/><path d="M14 9h4M14 12h4M14 15h2" strokeLinecap="round"/></svg>, label: "Government-issued ID", desc: "Ghana Card, Passport, or Voter's ID" },
                    { icon: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" className="w-5 h-5"><path d="M23 19a2 2 0 01-2 2H3a2 2 0 01-2-2V8a2 2 0 012-2h4l2-3h6l2 3h4a2 2 0 012 2z"/><circle cx="12" cy="13" r="4"/></svg>, label: "Selfie with your ID", desc: "A photo of you holding your document" },
                    { icon: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" className="w-5 h-5"><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>, label: "Property authority document", desc: "Title deed, management letter, or authorisation" },
                    { icon: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" className="w-5 h-5"><circle cx="12" cy="12" r="10"/><path d="M12 6v6l4 2" strokeLinecap="round"/></svg>, label: "1–2 business days", desc: "Villa reviews and notifies you by email" },
                  ].map(({ icon, label, desc }) => (
                    <div key={label} className="flex items-start gap-4 py-3 border-b border-mist last:border-b-0">
                      <div className="shrink-0 mt-0.5 text-forest">{icon}</div>
                      <div><div className="text-sm font-semibold text-ink">{label}</div><div className="text-xs text-ink-soft">{desc}</div></div>
                    </div>
                  ))}
                </div>
                <Link href="/stay/kyc"
                  className="inline-flex items-center justify-center font-semibold text-sm px-7 py-3.5 rounded-pill bg-forest text-white hover:bg-forest-deep transition-colors mb-4">
                  Start KYC verification
                </Link>
              </>
            ) : (
              <>
                <VerificationStamp variant="pending" size={80} className="mx-auto mb-6" />
                <h2 className="font-display font-semibold text-2xl text-forest-deep mb-3">KYC under review</h2>
                <p className="text-ink-soft mb-4 max-w-[44ch] mx-auto">
                  Your KYC application is being reviewed. This usually takes <strong>1–2 business days</strong>. You&apos;ll receive an SMS once approved.
                </p>
                <div className="bg-[#FBF1E1] border border-gold rounded-md px-5 py-4 text-sm text-gold-deep mb-6">
                  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="w-4 h-4 inline-block mr-1.5 -mt-0.5"><circle cx="12" cy="12" r="10"/><path d="M12 6v6l4 2" strokeLinecap="round"/></svg>Application submitted — awaiting review
                </div>
              </>
            )}
          </div>
        </div>
      </div>
    );
  }

  const navItems: { id: Section; label: string; icon: ReactNode; badge?: number }[] = [
    { id: "overview",  label: "Overview",      icon: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" className="w-[18px] h-[18px]"><path d="M3 12l9-9 9 9M5 10v10h14V10" strokeLinecap="round" strokeLinejoin="round"/></svg> },
    { id: "bookings",  label: "Bookings",       icon: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" className="w-[18px] h-[18px]"><path d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" strokeLinecap="round"/><path d="M9 12l2 2 4-4" strokeLinecap="round" strokeLinejoin="round"/></svg>, badge: pending.length },
    { id: "calendar",  label: "Booking calendar", icon: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" className="w-[18px] h-[18px]"><rect x="3" y="4" width="18" height="18" rx="2"/><path d="M16 2v4M8 2v4M3 10h18" strokeLinecap="round"/></svg> },
    { id: "rooms",     label: "Rooms & rates",  icon: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" className="w-[18px] h-[18px]"><path d="M2 20v-8a2 2 0 012-2h16a2 2 0 012 2v8M2 20h20M2 12V8a2 2 0 014-2h8a2 2 0 014 2v4" strokeLinecap="round"/></svg> },
    { id: "earnings",  label: "Earnings",       icon: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" className="w-[18px] h-[18px]"><path d="M12 2v20M17 5H9.5a3.5 3.5 0 000 7h5a3.5 3.5 0 010 7H6" strokeLinecap="round" strokeLinejoin="round"/></svg> },
    { id: "settings",  label: "Property settings", icon: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" className="w-[18px] h-[18px]"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 00.33 1.82l.06.06a2 2 0 010 2.83 2 2 0 01-2.83 0l-.06-.06a1.65 1.65 0 00-1.82-.33 1.65 1.65 0 00-1 1.51V21a2 2 0 01-4 0v-.09A1.65 1.65 0 009 19.4a1.65 1.65 0 00-1.82.33l-.06.06a2 2 0 01-2.83-2.83l.06-.06A1.65 1.65 0 004.68 15a1.65 1.65 0 00-1.51-1H3a2 2 0 010-4h.09A1.65 1.65 0 004.6 9a1.65 1.65 0 00-.33-1.82l-.06-.06a2 2 0 012.83-2.83l.06.06A1.65 1.65 0 009 4.68a1.65 1.65 0 001-1.51V3a2 2 0 014 0v.09a1.65 1.65 0 001 1.51 1.65 1.65 0 001.82-.33l.06-.06a2 2 0 012.83 2.83l-.06.06A1.65 1.65 0 0019.4 9a1.65 1.65 0 001.51 1H21a2 2 0 010 4h-.09a1.65 1.65 0 00-1.51 1z" strokeLinecap="round"/></svg> },
  ];

  return (
    <div className="max-w-6xl mx-auto px-6 py-8">
      <div className="grid grid-cols-1 lg:grid-cols-[240px_1fr] gap-8 items-start">

        {/* Sidebar */}
        <aside className="bg-white border border-mist rounded-md p-5 lg:sticky lg:top-[96px]">
          <div className="mb-5 pb-5 border-b border-mist">
            <div className="font-display font-semibold text-lg text-forest-deep">{accommodation?.name ?? "Your property"}</div>
            <div className="font-mono text-xs uppercase tracking-widest text-ink-soft mb-2">Accommodation owner</div>
            <span className="inline-flex items-center gap-1.5 font-mono text-xs uppercase tracking-wider px-3 py-1.5 rounded-pill bg-[#E8F2EC] text-forest border border-forest/20">
              <span className="w-1.5 h-1.5 rounded-full bg-forest" />Villa verified
            </span>
          </div>
          <nav className="flex flex-col gap-1">
            {navItems.map(({ id, label, icon, badge }) => (
              <button key={id} onClick={() => setSection(id)}
                className={`flex items-center gap-3 px-3 py-2.5 rounded-sm text-sm font-medium transition-colors text-left w-full ${section === id ? "bg-forest text-white" : "text-ink-soft hover:bg-sage hover:text-forest"}`}>
                <span className="shrink-0">{icon}</span>
                <span className="flex-1">{label}</span>
                {badge !== undefined && badge > 0 && (
                  <span className={`inline-flex items-center justify-center min-w-[18px] h-[18px] rounded-full text-[11px] font-bold px-1 ${section === id ? "bg-white text-forest" : "bg-gold text-forest-deep"}`}>{badge}</span>
                )}
              </button>
            ))}
          </nav>
          <div className="mt-5 pt-5 border-t border-mist flex flex-col gap-2">
            <Link href="/stay/acc1" className="text-sm text-forest hover:underline">View public listing →</Link>
            <button onClick={handleLogout} className="text-sm text-ink-soft hover:text-clay transition-colors">Log out</button>
          </div>
        </aside>

        {/* Main content */}
        <div>

          {/* Overview */}
          {section === "overview" && (
            <div>
              <div className="mb-6">
                <h1 className="font-display font-semibold text-2xl text-forest-deep">Dashboard</h1>
                <p className="text-sm text-ink-soft">Manage your bookings, rooms, and accommodation listing.</p>
              </div>

              <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
                <StatCard label="Pending"   value={String(pending.length)}   sub="Awaiting your response" />
                <StatCard label="Confirmed" value={String(confirmed.length)} sub="Upcoming stays" />
                <StatCard label="Completed" value={String(completed.length)} sub="Past bookings" />
                <StatCard label="Deposit collected" value={`GH₵ ${totalRevenue.toLocaleString()}`} sub="From completed stays" />
              </div>

              {/* Pending bookings */}
              {pending.length > 0 && (
                <Card className="mb-5">
                  <div className="flex justify-between items-center px-5 py-4 border-b border-mist">
                    <h3 className="font-display font-semibold text-lg">Pending requests</h3>
                    <span className="font-mono text-xs bg-gold text-forest-deep px-3 py-1 rounded-pill font-bold">{pending.length} new</span>
                  </div>
                  <div className="divide-y divide-mist">
                    {pending.map((b) => (
                      <div key={b.id} className="px-5 py-4 flex flex-wrap items-center justify-between gap-4">
                        <div>
                          <div className="font-display font-semibold text-forest-deep">{b.guestName}</div>
                          <div className="text-sm text-ink-soft">{b.roomTypeName} · {b.nights} night{b.nights !== 1 ? "s" : ""}</div>
                          <div className="text-sm text-ink-soft">{b.checkIn} → {b.checkOut} · {b.guests} guest{b.guests !== 1 ? "s" : ""}</div>
                          <div className="font-mono text-sm font-semibold text-forest mt-1">GH₵ {b.totalPrice.toLocaleString()}</div>
                        </div>
                        <div className="flex gap-2">
                          <Btn variant="primary" onClick={() => handleConfirmBooking(b)}>Confirm</Btn>
                          <Btn variant="danger" onClick={() => handleDeclineBooking(b)}>Decline</Btn>
                        </div>
                      </div>
                    ))}
                  </div>
                </Card>
              )}

              {/* Upcoming */}
              {confirmed.length > 0 && (
                <Card>
                  <div className="px-5 py-4 border-b border-mist">
                    <h3 className="font-display font-semibold text-lg">Upcoming stays</h3>
                  </div>
                  <div className="divide-y divide-mist">
                    {confirmed.map((b) => (
                      <div key={b.id} className="px-5 py-4 flex flex-wrap items-center justify-between gap-3">
                        <div>
                          <div className="font-semibold text-forest-deep">{b.guestName}</div>
                          <div className="text-sm text-ink-soft">{b.roomTypeName} · {b.checkIn} to {b.checkOut}</div>
                          {b.specialRequests && <div className="text-xs text-gold-deep mt-0.5">"{b.specialRequests}"</div>}
                        </div>
                        <div className="flex items-center gap-3">
                          <BookingStatusBadge status={b.status} />
                          <span className="font-mono font-semibold text-forest">GH₵ {b.totalPrice.toLocaleString()}</span>
                        </div>
                      </div>
                    ))}
                  </div>
                </Card>
              )}
            </div>
          )}

          {/* All bookings */}
          {section === "bookings" && (
            <div>
              <h2 className="font-display font-semibold text-xl text-forest-deep mb-5">All bookings</h2>
              <Card>
                <div className="overflow-x-auto">
                  <table className="w-full border-collapse">
                    <thead>
                      <tr className="bg-sage">
                        {["Guest", "Room", "Dates", "Nights", "Total", "Payment", "Status", ""].map((h) => (
                          <th key={h} className="text-left font-mono text-[10px] uppercase tracking-widest text-ink-soft px-5 py-3 border-b border-mist whitespace-nowrap">{h}</th>
                        ))}
                      </tr>
                    </thead>
                    <tbody>
                      {bookingsPag.paged.map((b) => (
                        <tr key={b.id} className="border-b border-mist last:border-b-0 hover:bg-sage/40 transition-colors">
                          <td className="px-5 py-4">
                            <div className="font-semibold text-forest-deep">{b.guestName}</div>
                            <div className="text-xs text-ink-soft">{b.guestPhone}</div>
                          </td>
                          <td className="px-5 py-4 text-sm whitespace-nowrap">{b.roomTypeName}</td>
                          <td className="px-5 py-4 text-sm text-ink-soft whitespace-nowrap">{b.checkIn} → {b.checkOut}</td>
                          <td className="px-5 py-4 font-mono text-sm">{b.nights}</td>
                          <td className="px-5 py-4 font-mono text-sm font-semibold text-forest whitespace-nowrap">GH₵ {b.totalPrice.toLocaleString()}</td>
                          <td className="px-5 py-4 text-sm text-ink-soft whitespace-nowrap capitalize">
                            {b.paymentMethod === "mobile-money" ? "Mobile money" : "Cash"}
                          </td>
                          <td className="px-5 py-4 whitespace-nowrap"><BookingStatusBadge status={b.status} /></td>
                          <td className="px-5 py-4">
                            {b.status === "pending" && (
                              <div className="flex gap-2">
                                <button onClick={() => handleConfirmBooking(b)} className="text-xs text-forest font-semibold hover:underline">Confirm</button>
                                <button onClick={() => handleDeclineBooking(b)} className="text-xs text-clay font-semibold hover:underline">Decline</button>
                              </div>
                            )}
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
                <TablePagination page={bookingsPag.page} totalPages={bookingsPag.totalPages} total={bookings.length} perPage={5} onPage={bookingsPag.goTo} label="booking" />
              </Card>
            </div>
          )}

          {/* Calendar */}
          {section === "calendar" && (
            <div>
              <h2 className="font-display font-semibold text-xl text-forest-deep mb-5">Booking calendar</h2>
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-5">
                <BookingCalendar bookings={bookings} />
                <Card>
                  <div className="px-5 py-4 border-b border-mist">
                    <h3 className="font-semibold">June 2026 — at a glance</h3>
                  </div>
                  <div className="divide-y divide-mist">
                    {bookings.filter((b) => b.status !== "cancelled" && b.status !== "declined").map((b) => (
                      <div key={b.id} className="px-5 py-3">
                        <div className="flex items-center gap-2 mb-0.5">
                          <BookingStatusBadge status={b.status} />
                          <span className="text-sm font-semibold text-forest-deep">{b.guestName}</span>
                        </div>
                        <div className="text-xs text-ink-soft">{b.roomTypeName} · {b.checkIn} → {b.checkOut}</div>
                      </div>
                    ))}
                  </div>
                </Card>
              </div>
              <div className="mt-5 bg-[#FBF1E1] border border-gold rounded-md px-5 py-4 text-sm text-gold-deep">
                <strong>Coming soon:</strong> Block dates manually for maintenance or private use. Real-time availability sync in Phase 2.
              </div>
            </div>
          )}

          {/* Rooms */}
          {section === "rooms" && (
            <div>
              <h2 className="font-display font-semibold text-xl text-forest-deep mb-5">Rooms & rates</h2>
              <div className="flex flex-col gap-4">
                {editableRooms.map((room) => (
                  <Card key={room.id}>
                    <div className="flex flex-wrap items-center justify-between gap-4 px-5 py-4">
                      <div>
                        <div className="font-display font-semibold text-forest-deep">{room.name}</div>
                        <div className="text-sm text-ink-soft">Up to {room.capacity} guests · {room.description}</div>
                      </div>
                      <div className="flex items-center gap-3">
                        <div>
                          <span className="font-mono text-xl font-bold text-forest">GH₵ {room.price}</span>
                          <span className="text-xs text-ink-soft"> / night</span>
                        </div>
                        <button
                          onClick={() => toggleRoomAvailability(room.id)}
                          className={`font-mono text-[10px] uppercase tracking-wider px-3 py-1.5 rounded-pill border transition-colors cursor-pointer hover:opacity-80 ${room.available ? "bg-[#E8F2EC] text-forest border-forest/20" : "bg-[#F5EAE6] text-clay border-clay/20"}`}
                          title={room.available ? "Click to mark unavailable" : "Click to mark available"}
                        >
                          {room.available ? "Available" : "Unavailable"}
                        </button>
                        <Btn variant="ghost" onClick={() => setEditingRoom(room)}>Edit</Btn>
                      </div>
                    </div>
                  </Card>
                ))}
              </div>
              <button
                onClick={() => setEditingRoom({ id: "", name: "", capacity: 2, price: 0, description: "", available: true, isNew: true })}
                className="mt-4 inline-flex items-center gap-2 font-semibold text-sm px-5 py-2.5 rounded-pill border-2 border-dashed border-mist text-forest hover:border-forest transition-colors">
                + Add room type
              </button>

              {/* Edit / Add room modal */}
              {editingRoom && (
                <div className="fixed inset-0 z-50 flex items-center justify-center bg-ink/40 backdrop-blur-sm px-4">
                  <div className="bg-white rounded-xl border border-mist shadow-card-hover w-full max-w-md">
                    <div className="flex justify-between items-center px-6 py-4 border-b border-mist">
                      <h3 className="font-display font-semibold text-lg text-forest-deep">
                        {editingRoom.isNew ? "Add room type" : `Edit — ${editingRoom.name}`}
                      </h3>
                      <button onClick={() => setEditingRoom(null)} className="text-ink-soft hover:text-ink text-2xl leading-none">×</button>
                    </div>
                    <div className="p-6 flex flex-col gap-4">
                      <div>
                        <label className="block font-mono text-xs uppercase tracking-widest text-ink-soft mb-2">Room type name</label>
                        <input value={editingRoom.name} onChange={(e) => setEditingRoom((r) => r ? { ...r, name: e.target.value } : r)}
                          placeholder="e.g. Standard Room" className="w-full border border-mist rounded-sm px-4 py-3 text-sm focus:outline-2 focus:outline-gold" />
                      </div>
                      <div className="grid grid-cols-2 gap-4">
                        <div>
                          <label className="block font-mono text-xs uppercase tracking-widest text-ink-soft mb-2">Price / night (GH₵)</label>
                          <input type="number" value={editingRoom.price || ""} onChange={(e) => setEditingRoom((r) => r ? { ...r, price: Number(e.target.value) } : r)}
                            placeholder="e.g. 180" className="w-full border border-mist rounded-sm px-4 py-3 text-sm focus:outline-2 focus:outline-gold" />
                        </div>
                        <div>
                          <label className="block font-mono text-xs uppercase tracking-widest text-ink-soft mb-2">Max guests</label>
                          <select value={editingRoom.capacity} onChange={(e) => setEditingRoom((r) => r ? { ...r, capacity: Number(e.target.value) } : r)}
                            className="w-full border border-mist rounded-sm px-4 py-3 text-sm focus:outline-2 focus:outline-gold">
                            {[1,2,3,4,5,6].map((n) => <option key={n} value={n}>{n} guest{n !== 1 ? "s" : ""}</option>)}
                          </select>
                        </div>
                      </div>
                      <div>
                        <label className="block font-mono text-xs uppercase tracking-widest text-ink-soft mb-2">Description</label>
                        <textarea value={editingRoom.description} onChange={(e) => setEditingRoom((r) => r ? { ...r, description: e.target.value } : r)}
                          placeholder="Describe this room type…" rows={3}
                          className="w-full border border-mist rounded-sm px-4 py-3 text-sm resize-none focus:outline-2 focus:outline-gold" />
                      </div>
                      <label className="flex items-center gap-2 cursor-pointer text-sm">
                        <input type="checkbox" checked={editingRoom.available} onChange={(e) => setEditingRoom((r) => r ? { ...r, available: e.target.checked } : r)} className="w-4 h-4 accent-forest" />
                        Mark as available for booking
                      </label>
                    </div>
                    <div className="px-6 pb-5 flex justify-between">
                      {!editingRoom.isNew && (
                        <button onClick={async () => {
                          const rm = editingRoom;
                          try {
                            await clientExecute("accommodation.delete-room", { accommodationId: accId, roomId: rm.id });
                            setEditableRooms((prev) => prev.filter((r) => r.id !== rm.id));
                            setEditingRoom(null);
                            showToast("Room type removed");
                          } catch (e) { showToast(e instanceof ApiError ? e.message : "Couldn't remove.", "error"); }
                        }}
                          className="text-sm text-clay font-semibold hover:underline">Remove room type</button>
                      )}
                      <div className="flex gap-3 ml-auto">
                        <Btn variant="ghost" onClick={() => setEditingRoom(null)}>Cancel</Btn>
                        <Btn onClick={async () => {
                          const rm = editingRoom;
                          try {
                            if (rm.isNew) {
                              const created = await clientExecute<RoomType>("accommodation.create-room", {
                                accommodationId: accId, name: rm.name, pricePerNight: rm.price, capacity: rm.capacity, description: rm.description,
                              });
                              setEditableRooms((prev) => [...prev, { id: created.id, name: created.name, capacity: created.capacity, price: created.pricePerNight, description: created.description, available: created.available }]);
                              showToast("Room type added");
                            } else {
                              await clientExecute("accommodation.update-room", {
                                accommodationId: accId, roomId: rm.id, name: rm.name, pricePerNight: rm.price, capacity: rm.capacity, description: rm.description, available: rm.available,
                              });
                              setEditableRooms((prev) => prev.map((r) => r.id === rm.id ? rm : r));
                              showToast("Room type updated");
                            }
                            setEditingRoom(null);
                          } catch (e) { showToast(e instanceof ApiError ? e.message : "Couldn't save room.", "error"); }
                        }} disabled={!editingRoom.name || !editingRoom.price}>
                          {editingRoom.isNew ? "Add room" : "Save changes"}
                        </Btn>
                      </div>
                    </div>
                  </div>
                </div>
              )}
            </div>
          )}

          {/* Earnings */}
          {section === "earnings" && (
            <div>
              <h2 className="font-display font-semibold text-xl text-forest-deep mb-5">Earnings summary</h2>
              <div className="grid grid-cols-2 lg:grid-cols-3 gap-4 mb-6">
                <StatCard label="Total bookings" value={String(bookings.length)} />
                <StatCard label="Confirmed revenue" value={`GH₵ ${bookings.filter((b) => b.status === "confirmed" || b.status === "completed").reduce((s, b) => s + b.totalPrice, 0).toLocaleString()}`} sub="From confirmed bookings" />
                <StatCard label="Deposits collected" value={`GH₵ ${totalRevenue.toLocaleString()}`} sub="From completed stays" />
              </div>
              <Card>
                <div className="px-5 py-4 border-b border-mist font-semibold">Booking history</div>
                <div className="overflow-x-auto">
                  <table className="w-full border-collapse">
                    <thead>
                      <tr className="bg-sage">
                        {["Guest", "Room", "Dates", "Total", "Deposit", "Status"].map((h) => (
                          <th key={h} className="text-left font-mono text-[10px] uppercase tracking-widest text-ink-soft px-5 py-3 border-b border-mist">{h}</th>
                        ))}
                      </tr>
                    </thead>
                    <tbody>
                      {bookings.map((b) => (
                        <tr key={b.id} className="border-b border-mist last:border-b-0 hover:bg-sage/40">
                          <td className="px-5 py-3 text-sm font-semibold text-forest-deep whitespace-nowrap">{b.guestName}</td>
                          <td className="px-5 py-3 text-sm whitespace-nowrap">{b.roomTypeName}</td>
                          <td className="px-5 py-3 text-sm text-ink-soft whitespace-nowrap">{b.checkIn} → {b.checkOut}</td>
                          <td className="px-5 py-3 font-mono text-sm font-semibold text-forest whitespace-nowrap">GH₵ {b.totalPrice.toLocaleString()}</td>
                          <td className="px-5 py-3 font-mono text-sm whitespace-nowrap">GH₵ {b.depositAmount.toLocaleString()}</td>
                          <td className="px-5 py-3"><BookingStatusBadge status={b.status} /></td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </Card>
            </div>
          )}

          {/* Settings */}
          {section === "settings" && (
            <div>
              <h2 className="font-display font-semibold text-xl text-forest-deep mb-5">Property settings</h2>
              <Card>
                <div className="px-5 py-4 border-b border-mist font-semibold">General information</div>
                <div className="p-5 grid grid-cols-1 sm:grid-cols-2 gap-4">
                  {(() => { const fieldCls = "w-full border border-mist rounded-sm px-4 py-2.5 text-sm bg-white text-ink focus:outline-2 focus:outline-gold"; const labelCls = "block font-mono text-[10px] uppercase tracking-widest text-ink-soft mb-1.5"; return (
                  <>
                    <div>
                      <label className={labelCls}>Property name</label>
                      <input value={settingsForm.name} onChange={(e) => setSettingsForm((s) => ({ ...s, name: e.target.value }))} className={fieldCls} />
                    </div>
                    <div>
                      <label className={labelCls}>Property type</label>
                      <select value={settingsForm.type} onChange={(e) => setSettingsForm((s) => ({ ...s, type: e.target.value }))} className={fieldCls}>
                        <option value="hotel">Hotel</option>
                        <option value="guesthouse">Guesthouse</option>
                        <option value="lodge">Lodge</option>
                        <option value="serviced-apartment">Serviced Apartment</option>
                      </select>
                    </div>
                    <div>
                      <label className={labelCls}>Town</label>
                      <input value={settingsForm.town} onChange={(e) => setSettingsForm((s) => ({ ...s, town: e.target.value }))} className={fieldCls} />
                    </div>
                    <div>
                      <label className={labelCls}>Address</label>
                      <input value={settingsForm.address} onChange={(e) => setSettingsForm((s) => ({ ...s, address: e.target.value }))} className={fieldCls} />
                    </div>
                    <div>
                      <label className={labelCls}>Check-in time</label>
                      <input value={settingsForm.checkInTime} onChange={(e) => setSettingsForm((s) => ({ ...s, checkInTime: e.target.value }))} className={fieldCls} />
                    </div>
                    <div>
                      <label className={labelCls}>Check-out time</label>
                      <input value={settingsForm.checkOutTime} onChange={(e) => setSettingsForm((s) => ({ ...s, checkOutTime: e.target.value }))} className={fieldCls} />
                    </div>
                    <div>
                      <label className={labelCls}>Deposit required (%)</label>
                      <input type="number" value={settingsForm.depositPercent} onChange={(e) => setSettingsForm((s) => ({ ...s, depositPercent: Number(e.target.value) || 0 }))} className={fieldCls} />
                    </div>
                    <div>
                      <label className={labelCls}>Contact phone</label>
                      <input value={settingsForm.ownerPhone} onChange={(e) => setSettingsForm((s) => ({ ...s, ownerPhone: e.target.value }))} className={fieldCls} />
                    </div>
                    <div className="sm:col-span-2">
                      <label className={labelCls}>Cancellation policy</label>
                      <textarea value={settingsForm.cancellationPolicy} onChange={(e) => setSettingsForm((s) => ({ ...s, cancellationPolicy: e.target.value }))} rows={3} className={`${fieldCls} resize-none`} />
                    </div>
                  </>
                  ); })()}
                </div>
                <div className="px-5 pb-5">
                  <Btn variant="primary" onClick={handleSaveSettings} disabled={savingSettings}>{savingSettings ? <span className="inline-flex items-center gap-2"><Spinner size="sm" />Saving…</span> : "Save changes"}</Btn>
                </div>
              </Card>
            </div>
          )}

        </div>
      </div>
      {confirmNode}
      {toastNode}
    </div>
  );
}
