"use client";
import React from "react";
import { PackageSearch } from "lucide-react";
import { ListingCard } from "./ListingCard";
import { ListingGridSkeleton } from "./LoadingSkeleton";
import { EmptyState } from "./EmptyState";
import type { Listing } from "@/types/marketplace";

interface ListingGridProps {
  listings: Listing[];
  loading?: boolean;
  error?: string | null;
  wishlistedIds?: Set<string>;
  onWishlistToggle?: (id: string) => void;
  emptyTitle?: string;
  emptyDescription?: string;
  emptyAction?: { label: string; onClick: () => void };
  columns?: 2 | 3 | 4;
  skeletonCount?: number;
}

const GRID_CLASS: Record<number, string> = {
  2: "grid-cols-2",
  3: "grid-cols-2 sm:grid-cols-3",
  4: "grid-cols-2 sm:grid-cols-3 lg:grid-cols-4",
};

export function ListingGrid({
  listings,
  loading = false,
  error,
  wishlistedIds,
  onWishlistToggle,
  emptyTitle = "No listings found",
  emptyDescription = "Try adjusting your search or filters.",
  emptyAction,
  columns = 4,
  skeletonCount = 8,
}: ListingGridProps) {
  if (loading) {
    return <ListingGridSkeleton count={skeletonCount} />;
  }

  if (error) {
    return (
      <div
        className="rounded-2xl p-6 text-center"
        style={{ background: "var(--card)", border: "1px solid var(--border)" }}
      >
        <p className="text-sm" style={{ color: "var(--text-muted)" }}>
          {error}
        </p>
      </div>
    );
  }

  if (!listings.length) {
    return (
      <EmptyState
        icon={PackageSearch}
        title={emptyTitle}
        description={emptyDescription}
        action={emptyAction}
      />
    );
  }

  return (
    <div className={`grid ${GRID_CLASS[columns]} gap-3 md:gap-4`}>
      {listings.map((listing) => (
        <ListingCard
          key={listing.id}
          listing={listing}
          isWishlisted={wishlistedIds?.has(listing.id)}
          onWishlistToggle={onWishlistToggle}
        />
      ))}
    </div>
  );
}
