"use client";
import React, { useState } from "react";
import { useRouter } from "next/navigation";
import { ChevronRight } from "lucide-react";
import { useAppSelector } from "@/store/hooks";
import { MARKETPLACE_CATEGORIES } from "@/constants/marketplace";

const CATEGORY_EMOJI_MAP: Record<string, string> = {
  Electronics: "📱",
  Vehicles: "🚗",
  Furniture: "🛋️",
  Books: "📚",
  Sports: "⚽",
  "Home Appliances": "🏠",
  Fashion: "👗",
  Property: "🏢",
  Jobs: "💼",
  Services: "🔧",
  "Kids & Baby": "👶",
  Pets: "🐾",
  Music: "🎵",
  "Art & Collectibles": "🎨",
};

function getCategoryEmoji(name: string): string {
  return CATEGORY_EMOJI_MAP[name] ?? "📦";
}

function slugify(name: string): string {
  return name.toLowerCase().replace(/\s+/g, "-").replace(/[^a-z0-9-]/g, "");
}

export function CategoriesPage() {
  const router = useRouter();
  const [expanded, setExpanded] = useState<string | null>(null);

  const { categories: apiCategories, isLoading } = useAppSelector(
    (s) => s.marketplaceCategory
  );

  const categories =
    apiCategories.length > 0
      ? apiCategories
          .filter((c) => c.status === 1)
          .sort((a, b) => a.sort_order - b.sort_order)
          .map((c) => ({
            id: String(c.id),
            slug: slugify(c.name),
            label: c.name,
            icon: getCategoryEmoji(c.name),
            image: c.image,
          }))
      : MARKETPLACE_CATEGORIES.map((c) => ({
          id: c.id,
          slug: c.slug,
          label: c.label,
          icon: c.icon,
          image: undefined as string | undefined,
        }));

  return (
    <div className="p-4 md:p-6 max-w-6xl mx-auto">
      <div className="mb-6">
        <h1 className="text-xl font-bold" style={{ color: "var(--text-primary)" }}>
          Browse Categories
        </h1>
        <p className="text-sm mt-0.5" style={{ color: "var(--text-muted)" }}>
          Find what you&apos;re looking for
        </p>
      </div>

      {isLoading ? (
        <div className="space-y-2">
          {Array.from({ length: 6 }).map((_, i) => (
            <div
              key={i}
              className="h-14 rounded-2xl animate-pulse"
              style={{ background: "var(--card)" }}
            />
          ))}
        </div>
      ) : (
        <div className="space-y-2">
          {categories.map((cat) => (
            <div key={cat.id}>
              <button
                onClick={() => {
                  setExpanded((prev) => (prev === cat.id ? null : cat.id));
                  router.push(`/marketplace/search?category=${cat.slug}`);
                }}
                className="w-full flex items-center gap-3 p-3 rounded-2xl transition-all hover:opacity-90"
                style={{ background: "var(--card)", border: "1px solid var(--border)" }}
              >
                {cat.image && !cat.image.includes("no_img") ? (
                  <img
                    src={cat.image}
                    alt={cat.label}
                    className="w-9 h-9 rounded-xl object-cover shrink-0"
                  />
                ) : (
                  <span className="text-2xl">{cat.icon}</span>
                )}
                <span
                  className="flex-1 text-left text-sm font-medium"
                  style={{ color: "var(--text-primary)" }}
                >
                  {cat.label}
                </span>
                <ChevronRight
                  size={16}
                  style={{
                    color: "var(--text-muted)",
                    transform: expanded === cat.id ? "rotate(90deg)" : "none",
                    transition: "transform 0.2s",
                  }}
                />
              </button>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
