import listingOne from "@/assets/listing-1.jpg";
import listingTwo from "@/assets/listing-2.jpg";
import listingThree from "@/assets/listing-3.jpg";
import listingFour from "@/assets/listing-4.jpg";
import type { StaticImageData } from "next/image";
import { API_URL } from "@/lib/api";

export type Listing = {
  id: string;
  name: string;
  location: string;
  price: number;
  rating: number;
  reviews: number;
  guests: number;
  bedrooms: number;
  baths: number;
  image: StaticImageData | string;
  description: string;
  amenities: string[];
};

export const listings: Listing[] = [
  {
    id: "cliffside-villa",
    name: "Cliffside Ember Villa",
    location: "Cape Town, South Africa",
    price: 320,
    rating: 4.96,
    reviews: 84,
    guests: 6,
    bedrooms: 3,
    baths: 3,
    image: listingOne,
    description: "A sun-washed coastal retreat with an infinity pool and uninterrupted Atlantic views.",
    amenities: ["Ocean view", "Private pool", "Chef's kitchen", "Fast Wi-Fi"],
  },
  {
    id: "kyoto-machiya",
    name: "Quiet Kyoto Machiya",
    location: "Kyoto, Japan",
    price: 210,
    rating: 4.91,
    reviews: 126,
    guests: 4,
    bedrooms: 2,
    baths: 2,
    image: listingTwo,
    description: "A restored wooden townhouse where traditional craft meets calm, modern comfort.",
    amenities: ["Garden", "Tea room", "Soaking tub", "Workspace"],
  },
  {
    id: "lisbon-loft",
    name: "Alfama Light Loft",
    location: "Lisbon, Portugal",
    price: 175,
    rating: 4.88,
    reviews: 97,
    guests: 3,
    bedrooms: 1,
    baths: 1,
    image: listingThree,
    description: "An airy design loft among tiled lanes, neighborhood cafés, and river overlooks.",
    amenities: ["River view", "Balcony", "Air conditioning", "Kitchen"],
  },
  {
    id: "marrakech-riad",
    name: "Secret Garden Riad",
    location: "Marrakech, Morocco",
    price: 245,
    rating: 4.94,
    reviews: 73,
    guests: 5,
    bedrooms: 3,
    baths: 2,
    image: listingFour,
    description: "A private courtyard hideaway filled with hand-cut tile, citrus trees, and soft light.",
    amenities: ["Courtyard pool", "Breakfast", "Roof terrace", "Airport pickup"],
  },
];

export const findListing = (id: string) => listings.find((listing) => listing.id === id);

type ApiListing = {
  id: string;
  title: string;
  city: string;
  country: string;
  base_price_usd: string | number;
  average_rating: string | number | null;
  reviews_count: number;
  max_guests: number;
  bedrooms: number;
  bathrooms: number;
  description: string;
  images?: Array<{ url: string }>;
  amenities?: Array<{ name: string }>;
};

type ListingQuery = { q?: string; guests?: number; featured?: boolean; limit?: number };

function fromApi(listing: ApiListing, index = 0): Listing {
  const fallback = listings[index % listings.length];
  return {
    id: listing.id,
    name: listing.title,
    location: [listing.city, listing.country].filter(Boolean).join(", "),
    price: Number(listing.base_price_usd),
    rating: Number(listing.average_rating ?? 0),
    reviews: listing.reviews_count,
    guests: listing.max_guests,
    bedrooms: listing.bedrooms,
    baths: listing.bathrooms,
    image: listing.images?.[0]?.url || fallback.image,
    description: listing.description,
    amenities: listing.amenities?.map(({ name }) => name) ?? [],
  };
}

export async function loadListings(query: ListingQuery = {}): Promise<Listing[]> {
  const params = new URLSearchParams({ limit: String(query.limit ?? 20) });
  if (query.q) params.set("q", query.q);
  if (query.guests) params.set("minGuests", String(query.guests));
  const path = query.featured ? "/listings/featured" : "/listings";

  try {
    const response = await fetch(`${API_URL}${path}?${params}`, { next: { revalidate: 60 } });
    if (!response.ok) throw new Error(`Listings API returned ${response.status}`);
    const body = (await response.json()) as ApiListing[] | { data: ApiListing[] };
    const data = Array.isArray(body) ? body : body.data;
    return data.map(fromApi);
  } catch {
    const term = query.q?.trim().toLowerCase();
    return listings
      .filter((listing) => (!term || `${listing.name} ${listing.location}`.toLowerCase().includes(term)))
      .filter((listing) => (!query.guests || listing.guests >= query.guests))
      .slice(0, query.limit ?? listings.length);
  }
}

export async function loadListing(id: string): Promise<Listing | undefined> {
  try {
    const response = await fetch(`${API_URL}/listings/${encodeURIComponent(id)}`, { next: { revalidate: 60 } });
    if (!response.ok) return findListing(id);
    return fromApi((await response.json()) as ApiListing);
  } catch {
    return findListing(id);
  }
}
