"use client";

import { useState, useEffect } from "react";
import Link from "next/link";
import { clientExecute } from "@/lib/api/client";
import type { Accommodation, Paginated } from "@/lib/types";
import StatusBadge from "@/components/StatusBadge";
import VerificationStamp from "@/components/VerificationStamp";
import { Spinner, StayCardSkeleton, TopProgressBar } from "@/components/Loading";

const TOWNS = ["Akim Oda", "New Tafo", "Kade", "Asamankese"];
const TYPES = [
  { value: "hotel",              label: "Hotel" },
  { value: "guesthouse",         label: "Guesthouse" },
  { value: "lodge",              label: "Lodge" },
  { value: "serviced-apartment", label: "Serviced Apartment" },
];
const PRICE_RANGES = [
  { label: "Any price",         min: 0,   max: Infinity },
  { label: "Under GH₵ 150/night", min: 0, max: 149 },
  { label: "GH₵ 150–250/night",  min: 150, max: 250 },
  { label: "GH₵ 250–400/night",  min: 251, max: 400 },
  { label: "Above GH₵ 400/night", min: 401, max: Infinity },
];

function StarRating({ rating }: { rating: number }) {
  return (
    <div className="flex items-center gap-1">
      {[1, 2, 3, 4, 5].map((s) => (
        <svg key={s} viewBox="0 0 24 24" className="w-3.5 h-3.5" 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-xs text-ink-soft ml-0.5">{rating.toFixed(1)}</span>
    </div>
  );
}

function AccommodationCard({ acc }: { acc: Accommodation }) {
  const minPrice = Math.min(...acc.rooms.map((r) => r.pricePerNight));
  const typeLabel = TYPES.find((t) => t.value === acc.type)?.label ?? acc.type;
  const availableRooms = acc.rooms.filter((r) => r.available).length;

  return (
    <div className="bg-white border border-mist rounded-lg shadow-card hover:shadow-card-hover transition-all hover:-translate-y-0.5 overflow-hidden flex flex-col">
      {/* Image */}
      <div className="relative h-48 bg-gradient-to-br from-[#1E3A30] to-[#2A5244] flex items-center justify-center">
        <div className="text-center">
          <svg viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="1.2" className="w-10 h-10 mx-auto mb-1 opacity-30">
            <path d="M3 9l9-7 9 7v11a2 2 0 01-2 2H5a2 2 0 01-2-2V9z" /><polyline points="9 22 9 12 15 12 15 22" />
          </svg>
          <span className="text-white/30 font-mono text-xs uppercase tracking-wider">Photo</span>
        </div>

        {/* Type badge */}
        <div className="absolute top-3 left-3 bg-white/15 backdrop-blur-sm border border-white/20 text-white font-mono text-[10px] uppercase tracking-widest px-2.5 py-1 rounded-pill">
          {typeLabel}
        </div>

        {/* Verification stamp */}
        {acc.status === "verified" && (
          <VerificationStamp variant="property" size={52} className="absolute top-3 right-3" />
        )}

        {/* Availability pill */}
        <div className={`absolute bottom-3 right-3 font-mono text-[10px] uppercase tracking-wider px-2.5 py-1 rounded-pill ${
          availableRooms > 0 ? "bg-forest/90 text-white" : "bg-clay/90 text-white"
        }`}>
          {availableRooms > 0 ? `${availableRooms} room${availableRooms !== 1 ? "s" : ""} available` : "Fully booked"}
        </div>
      </div>

      {/* Content */}
      <div className="p-5 flex flex-col flex-1">
        <div className="mb-1">
          <h3 className="font-display font-semibold text-lg text-forest-deep leading-tight">{acc.name}</h3>
          <p className="text-sm text-ink-soft">{acc.address}</p>
        </div>

        <div className="flex items-center gap-3 my-2">
          <StarRating rating={acc.rating} />
          <span className="text-xs text-ink-soft">({acc.reviewCount} reviews)</span>
        </div>

        <p className="text-sm text-ink-soft line-clamp-2 mb-4 flex-1">{acc.description}</p>

        {/* Amenity pills */}
        <div className="flex flex-wrap gap-1.5 mb-4">
          {acc.amenities.slice(0, 4).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>
          ))}
          {acc.amenities.length > 4 && (
            <span className="text-[10px] font-mono text-ink-soft">+{acc.amenities.length - 4} more</span>
          )}
        </div>

        <div className="flex items-center justify-between mt-auto">
          <div>
            <span className="font-mono text-lg font-semibold text-forest">GH₵ {minPrice}</span>
            <span className="text-xs text-ink-soft"> / night</span>
          </div>
          <Link href={`/stay/${acc.id}`}
            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">
            View & book
          </Link>
        </div>
      </div>
    </div>
  );
}

export default function StayPage() {
  const [query,     setQuery]     = useState("");
  const [town,      setTown]      = useState("");
  const [types,     setTypes]     = useState<string[]>([]);
  const [priceIdx,  setPriceIdx]  = useState(0);
  const [checkIn,   setCheckIn]   = useState("");
  const [checkOut,  setCheckOut]  = useState("");
  const [guests,    setGuests]    = useState(1);

  function toggleType(t: string) {
    setTypes((prev) => prev.includes(t) ? prev.filter((x) => x !== t) : [...prev, t]);
  }

  const [items, setItems] = useState<Accommodation[]>([]);
  const [loading, setLoading] = useState(true);

  function clearFilters() {
    setQuery(""); setTown(""); setTypes([]); setPriceIdx(0); setCheckIn(""); setCheckOut(""); setGuests(1);
  }

  useEffect(() => {
    const { min, max } = PRICE_RANGES[priceIdx];
    const payload: Record<string, unknown> = { guests, limit: 24 };
    if (query.trim()) payload.q = query.trim();
    if (town) payload.town = town;
    if (types.length) payload.types = types;
    if (min > 0) payload.priceMinPerNight = min;
    if (Number.isFinite(max)) payload.priceMaxPerNight = max;

    let cancelled = false;
    setLoading(true);
    const t = setTimeout(async () => {
      try {
        const res = await clientExecute<Paginated<Accommodation>>("accommodation.find-all", payload);
        if (!cancelled) setItems(res.items);
      } catch {
        if (!cancelled) setItems([]);
      } finally {
        if (!cancelled) setLoading(false);
      }
    }, 250);
    return () => { cancelled = true; clearTimeout(t); };
  }, [town, types, priceIdx, query, guests]);

  return (
    <div className="max-w-6xl mx-auto px-6 py-8">

      {/* Hero */}
      <div className="bg-gradient-to-br from-forest-deep to-forest rounded-xl p-8 sm:p-12 mb-8 text-white relative overflow-hidden">
        <div className="absolute inset-0 opacity-10">
          {[...Array(6)].map((_, i) => (
            <div key={i} className="absolute rounded-full border border-white/30"
              style={{ width: `${100 + i * 80}px`, height: `${100 + i * 80}px`, top: `${-20 + i * 30}px`, right: `${-40 + i * 20}px` }} />
          ))}
        </div>
        <div className="relative">
          <div className="font-mono text-xs uppercase tracking-widest text-gold mb-3">Villa Stay</div>
          <h1 className="font-display font-semibold text-3xl sm:text-4xl mb-3 max-w-[18ch]" style={{ color: "#FFFFFF" }}>
            Hotels & guesthouses in Eastern Region
          </h1>
          <p className="max-w-[48ch] mb-6" style={{ color: "rgba(255,255,255,0.75)" }}>
            Every accommodation on Villa Stay is verified — photos, prices, and facilities are checked before listing. Book with confidence.
          </p>

          {/* Search bar */}
          <div className="flex flex-col sm:flex-row gap-3 max-w-2xl">
            <div className="flex items-center gap-3 bg-white/10 backdrop-blur-sm border border-white/20 rounded-pill px-5 py-3 flex-1">
              <svg viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="2" className="w-4 h-4 shrink-0 opacity-60">
                <circle cx="11" cy="11" r="7" /><path d="M21 21l-4.35-4.35" strokeLinecap="round" />
              </svg>
              <input value={query} onChange={(e) => setQuery(e.target.value)}
                placeholder="Search by name or town…"
                className="flex-1 bg-transparent border-none outline-none text-sm text-white placeholder:text-white/50" />
            </div>
            <select value={town} onChange={(e) => setTown(e.target.value)}
              className="bg-white/10 backdrop-blur-sm border border-white/20 rounded-pill px-5 py-3 text-sm text-white outline-none">
              <option value="">All towns</option>
              {TOWNS.map((t) => <option key={t} value={t} className="text-ink">{t}</option>)}
            </select>
          </div>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-[240px_1fr] gap-8 items-start">

        {/* Filters sidebar */}
        <aside className="bg-white border border-mist rounded-md p-5 lg:sticky lg:top-[96px]">
          <div className="flex justify-between items-center mb-4">
            <h3 className="font-semibold text-base">Filter stays</h3>
            <button onClick={clearFilters} className="text-xs text-ink-soft hover:text-clay transition-colors">Clear all</button>
          </div>

          {/* Dates */}
          <div className="mb-5">
            <span className="block font-mono text-xs uppercase tracking-widest text-ink-soft mb-3">Dates</span>
            <div className="flex flex-col gap-2">
              <div>
                <label className="text-xs text-ink-soft mb-1 block">Check-in</label>
                <input type="date" value={checkIn} onChange={(e) => setCheckIn(e.target.value)}
                  className="w-full border border-mist rounded-sm px-3 py-2 text-sm text-ink focus:outline-2 focus:outline-gold" />
              </div>
              <div>
                <label className="text-xs text-ink-soft mb-1 block">Check-out</label>
                <input type="date" value={checkOut} onChange={(e) => setCheckOut(e.target.value)}
                  className="w-full border border-mist rounded-sm px-3 py-2 text-sm text-ink focus:outline-2 focus:outline-gold" />
              </div>
            </div>
          </div>

          {/* Guests */}
          <div className="mb-5">
            <span className="block font-mono text-xs uppercase tracking-widest text-ink-soft mb-3">Guests</span>
            <div className="flex items-center gap-3">
              <button onClick={() => setGuests((g) => Math.max(1, g - 1))}
                className="w-8 h-8 rounded-full border border-mist flex items-center justify-center text-forest hover:bg-sage transition-colors font-bold">−</button>
              <span className="font-mono font-semibold text-lg w-6 text-center">{guests}</span>
              <button onClick={() => setGuests((g) => Math.min(10, g + 1))}
                className="w-8 h-8 rounded-full border border-mist flex items-center justify-center text-forest hover:bg-sage transition-colors font-bold">+</button>
            </div>
          </div>

          {/* Accommodation type */}
          <div className="mb-5">
            <span className="block font-mono text-xs uppercase tracking-widest text-ink-soft mb-3">Type</span>
            <div className="flex flex-col gap-2">
              {TYPES.map((t) => (
                <label key={t.value} className="flex items-center gap-2 text-sm cursor-pointer">
                  <input type="checkbox" checked={types.includes(t.value)} onChange={() => toggleType(t.value)}
                    className="w-4 h-4 accent-forest" />
                  {t.label}
                </label>
              ))}
            </div>
          </div>

          {/* Price per night */}
          <div className="mb-5">
            <span className="block font-mono text-xs uppercase tracking-widest text-ink-soft mb-3">Price per night</span>
            <div className="flex flex-col gap-2">
              {PRICE_RANGES.map((r, i) => (
                <label key={r.label} className="flex items-center gap-2 text-sm cursor-pointer">
                  <input type="radio" name="price" checked={priceIdx === i} onChange={() => setPriceIdx(i)}
                    className="w-4 h-4 accent-forest" />
                  {r.label}
                </label>
              ))}
            </div>
          </div>
        </aside>

        {/* Results */}
        <div>
          <div className="flex items-center justify-between mb-5">
            <p className="flex items-center gap-2.5 text-sm text-ink-soft">
              {loading && <span className="text-forest"><Spinner size="sm" /></span>}
              {loading
                ? "Searching stays…"
                : items.length === 0
                ? "No accommodations found"
                : <><strong className="text-ink">{items.length}</strong> place{items.length !== 1 ? "s" : ""} to stay</>
              }
            </p>
          </div>

          {loading && <TopProgressBar className="mb-5" />}

          {loading ? (
            <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 gap-5">
              {Array.from({ length: 6 }).map((_, i) => (
                <StayCardSkeleton key={i} />
              ))}
            </div>
          ) : items.length === 0 ? (
            <div className="bg-white border border-mist rounded-md py-16 text-center">
              <svg className="w-12 h-12 text-mist mx-auto mb-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4">
                <path d="M3 9l9-7 9 7v11a2 2 0 01-2 2H5a2 2 0 01-2-2V9z" />
              </svg>
              <h3 className="font-display font-semibold text-lg text-forest-deep mb-2">No places found</h3>
              <p className="text-sm text-ink-soft mb-6">Try adjusting your filters.</p>
              <button onClick={clearFilters}
                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">
                Clear filters
              </button>
            </div>
          ) : (
            <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 gap-5">
              {items.map((acc) => <AccommodationCard key={acc.id} acc={acc} />)}
            </div>
          )}

          {/* Villa Stay CTA */}
          <div className="mt-10 bg-gradient-to-br from-forest-deep to-forest rounded-xl p-6 text-white text-center">
            <div className="font-mono text-xs uppercase tracking-widest text-gold mb-2">Own a guesthouse or hotel?</div>
            <h3 className="font-display font-semibold text-xl mb-2" style={{ color: "#FFFFFF" }}>List your accommodation on Villa Stay</h3>
            <p className="text-sm mb-4 max-w-[44ch] mx-auto" style={{ color: "rgba(255,255,255,0.75)" }}>
              Reach verified guests, manage bookings online, and grow your occupancy — at no upfront cost.
            </p>
            <Link href="/stay/register"
              className="inline-flex items-center justify-center font-semibold text-sm px-6 py-3 rounded-pill bg-gold text-forest-deep hover:bg-white transition-colors">
              Register your property
            </Link>
          </div>
        </div>
      </div>
    </div>
  );
}
