"use client";

import { useState, useEffect } from "react";
import { useAuth } from "@/lib/AuthContext";
import { useRouter } from "next/navigation";
import {
  Search,
  Star,
  Clock,
  X,
  ShoppingBag,
  Filter,
  Loader2,
  SlidersHorizontal,
  ChevronDown,
  ArrowUpDown,
  Plus,
} from "lucide-react";

/* ------------------------------------------------------------------ */
/*  Types                                                             */
/* ------------------------------------------------------------------ */

interface SouqListing {
  id: string;
  title: string;
  description?: string;
  priceFlh: number;
  category?: string;
  featured?: boolean;
  rating?: number;
  reviewCount?: number;
  salesCount?: number;
  deliveryDays?: number;
  images?: string;
  tags?: string;
  packages?: string;
  seller: {
    id: string;
    name: string;
    email: string;
    avatar: string | null;
  };
}

/* ------------------------------------------------------------------ */
/*  Hardcoded categories                                              */
/* ------------------------------------------------------------------ */

const CATEGORIES = [
  { id: "graphics-design", name: "Graphics & Design", icon: "🎨", color: "bg-pink-900/30 text-pink-400" },
  { id: "digital-marketing", name: "Digital Marketing", icon: "📈", color: "bg-emerald-900/30 text-emerald-400" },
  { id: "writing-translation", name: "Writing & Translation", icon: "✍️", color: "bg-amber-900/30 text-amber-400" },
  { id: "video-animation", name: "Video & Animation", icon: "🎬", color: "bg-red-900/30 text-red-400" },
  { id: "music-audio", name: "Music & Audio", icon: "🎵", color: "bg-purple-900/30 text-purple-400" },
  { id: "programming-tech", name: "Programming & Tech", icon: "💻", color: "bg-blue-900/30 text-blue-400" },
  { id: "ai-services", name: "AI Services", icon: "🤖", color: "bg-cyan-900/30 text-cyan-400" },
  { id: "consulting", name: "Consulting", icon: "💼", color: "bg-slate-700/30 text-slate-400" },
  { id: "data", name: "Data", icon: "📊", color: "bg-teal-900/30 text-teal-400" },
  { id: "business", name: "Business", icon: "🏢", color: "bg-indigo-900/30 text-indigo-400" },
  { id: "personal-growth", name: "Personal Growth", icon: "🌱", color: "bg-lime-900/30 text-lime-400" },
  { id: "photography", name: "Photography", icon: "📷", color: "bg-orange-900/30 text-orange-400" },
  { id: "finance", name: "Finance", icon: "💰", color: "bg-yellow-900/30 text-yellow-400" },
];

/* ------------------------------------------------------------------ */
/*  Helpers                                                           */
/* ------------------------------------------------------------------ */

function renderStars(rating: number) {
  const full = Math.floor(rating);
  const half = rating - full >= 0.5;
  const empty = 5 - full - (half ? 1 : 0);
  return (
    <span className="inline-flex items-center gap-0.5">
      {"★".repeat(full)}
      {half && "½"}
      {"☆".repeat(empty)}
    </span>
  );
}

const CATEGORY_VISUALS: Record<string, { emoji: string; bg: string }> = {
  "graphics-design":    { emoji: "🎨", bg: "from-pink-900/40 to-pink-800/20" },
  "digital-marketing":  { emoji: "📈", bg: "from-emerald-900/40 to-emerald-800/20" },
  "writing-translation": { emoji: "✍️", bg: "from-amber-900/40 to-amber-800/20" },
  "video-animation":    { emoji: "🎬", bg: "from-red-900/40 to-red-800/20" },
  "music-audio":        { emoji: "🎵", bg: "from-purple-900/40 to-purple-800/20" },
  "programming-tech":   { emoji: "💻", bg: "from-blue-900/40 to-blue-800/20" },
  "ai-services":        { emoji: "🤖", bg: "from-cyan-900/40 to-cyan-800/20" },
  "consulting":         { emoji: "💼", bg: "from-slate-700/40 to-slate-600/20" },
  "data":               { emoji: "📊", bg: "from-teal-900/40 to-teal-800/20" },
  "business":           { emoji: "🏢", bg: "from-indigo-900/40 to-indigo-800/20" },
  "personal-growth":    { emoji: "🌱", bg: "from-lime-900/40 to-lime-800/20" },
  "photography":        { emoji: "📷", bg: "from-orange-900/40 to-orange-800/20" },
  "finance":            { emoji: "💰", bg: "from-yellow-900/40 to-yellow-800/20" },
};

function listingVisual(cat?: string): { emoji: string; bg: string } {
  if (cat && CATEGORY_VISUALS[cat]) return CATEGORY_VISUALS[cat];
  return { emoji: "🛍️", bg: "from-gray-800/40 to-gray-700/20" };
}

/* ------------------------------------------------------------------ */
/*  Page Component                                                    */
/* ------------------------------------------------------------------ */

export default function SouqBrowsePage() {
  const { user, token, loading } = useAuth();
  const router = useRouter();

  const [listings, setListings] = useState<SouqListing[]>([]);
  const [fetching, setFetching] = useState(true);
  const [activeCategory, setActiveCategory] = useState<string | null>(null);
  const [searchQuery, setSearchQuery] = useState("");
  const [showFilters, setShowFilters] = useState(false);
  const [draftSortBy, setDraftSortBy] = useState("");
  const [draftMinPrice, setDraftMinPrice] = useState("");
  const [draftMaxPrice, setDraftMaxPrice] = useState("");
  const [draftDeliveryDays, setDraftDeliveryDays] = useState("");
  const [appliedSortBy, setAppliedSortBy] = useState("");
  const [appliedMinPrice, setAppliedMinPrice] = useState("");
  const [appliedMaxPrice, setAppliedMaxPrice] = useState("");
  const [appliedDeliveryDays, setAppliedDeliveryDays] = useState("");

  useEffect(() => {
    if (!loading && !token) router.push("/auth");
  }, [loading, token, router]);

  useEffect(() => {
    if (!token) return;
    setFetching(true);
    const params = new URLSearchParams();
    if (appliedSortBy) params.set("sortBy", appliedSortBy);
    if (appliedMinPrice) params.set("minPrice", appliedMinPrice);
    if (appliedMaxPrice) params.set("maxPrice", appliedMaxPrice);
    if (appliedDeliveryDays) params.set("deliveryDays", appliedDeliveryDays);
    const qs = params.toString();
    const url = `/mobile/api/souq/listings${qs ? `?${qs}` : ""}`;
    fetch(url, {
      headers: { Authorization: `Bearer ${token}` },
    })
      .then((r) => (r.ok ? r.json() : Promise.resolve({ listings: [] })))
      .then((data: { listings: SouqListing[] }) => setListings(data.listings || []))
      .catch(() => setListings([]))
      .finally(() => setFetching(false));
  }, [token, appliedSortBy, appliedMinPrice, appliedMaxPrice, appliedDeliveryDays]);

  const filtered = listings.filter((l) => {
    const matchesCategory = !activeCategory || l.category === activeCategory;
    const q = searchQuery.toLowerCase().trim();
    const matchesSearch =
      !q ||
      l.title.toLowerCase().includes(q) ||
      (l.seller?.name && l.seller.name.toLowerCase().includes(q)) ||
      (l.description && l.description.toLowerCase().includes(q));
    return matchesCategory && matchesSearch;
  });

  const featured = filtered.filter((l) => l.featured);
  const regular = filtered.filter((l) => !l.featured);

  const categoryCounts: Record<string, number> = {};
  listings.forEach((l) => {
    if (l.category) categoryCounts[l.category] = (categoryCounts[l.category] || 0) + 1;
  });

  if (loading) {
    return (
      <div className="min-h-dvh bg-[#0a0a0f] flex items-center justify-center">
        <div className="w-8 h-8 rounded-full border-2 border-[#D4AF37]/30 border-t-[#D4AF37] animate-spin" />
      </div>
    );
  }

  if (!user) return null;

  return (
    <div className="min-h-dvh bg-[#0a0a0f] pb-24">
      <div className="px-4 pt-6 pb-4">
        <div className="flex items-center justify-between mb-3">
          <div>
            <h1 className="text-xl font-bold text-white">Souq</h1>
            <p className="text-xs text-gray-500 mt-0.5">Browse freelance services</p>
          </div>
          <div className="flex items-center gap-2">
            <a
              href="/souq/create"
              className="flex items-center gap-1.5 text-xs font-medium text-[#D4AF37] bg-[#D4AF37]/10 border border-[#D4AF37]/20 rounded-xl px-3 py-2 hover:bg-[#D4AF37]/20 transition active:scale-95 whitespace-nowrap"
            >
              <Plus size={14} /> Sell a Service
            </a>
            <div className="w-10 h-10 rounded-xl bg-[#D4AF37]/15 flex items-center justify-center">
              <ShoppingBag size={20} className="text-[#D4AF37]" />
            </div>
          </div>
        </div>

        <div className="flex items-center gap-2">
          <div className="relative flex-1">
            <Search
              size={16}
              className="absolute left-4 top-1/2 -translate-y-1/2 text-gray-500 pointer-events-none"
            />
            <input
              type="text"
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              placeholder="Search services..."
              className="w-full bg-[#111118] border border-gray-800/60 rounded-xl pl-11 pr-10 py-4 text-sm text-white placeholder-gray-600 focus:outline-none focus:border-[#D4AF37]/50 focus:ring-1 focus:ring-[#D4AF37]/30 transition min-h-[48px]"
            />
            {searchQuery && (
              <button
                onClick={() => setSearchQuery("")}
                className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-300 transition"
              >
                <X size={16} />
              </button>
            )}
          </div>
          <button
            onClick={() => setShowFilters(!showFilters)}
            className={`w-10 h-[48px] rounded-xl flex items-center justify-center shrink-0 transition ${
              showFilters
                ? "bg-[#D4AF37]/15 border border-[#D4AF37]/40 text-[#D4AF37]"
                : "bg-[#111118] border border-gray-800/60 text-gray-500 hover:text-gray-300"
            }`}
          >
            <SlidersHorizontal size={16} />
          </button>
        </div>
      </div>

      {showFilters && (
        <div className="px-4 pb-2">
          <div className="bg-[#111118] border border-gray-800/60 rounded-2xl p-4 space-y-4">
            {/* Sort dropdown */}
            <div>
              <label className="text-xs font-medium text-gray-500 mb-1.5 block">Sort By</label>
              <div className="relative">
                <select
                  value={draftSortBy}
                  onChange={(e) => setDraftSortBy(e.target.value)}
                  className="w-full bg-[#0a0a0f] border border-gray-800/60 rounded-xl pl-3 pr-10 py-2.5 text-sm text-white appearance-none focus:outline-none focus:border-[#D4AF37]/50 focus:ring-1 focus:ring-[#D4AF37]/30"
                >
                  <option value="">Default</option>
                  <option value="newest">Newest</option>
                  <option value="price_asc">Price: Low to High</option>
                  <option value="price_desc">Price: High to Low</option>
                  <option value="rating">Top Rated</option>
                  <option value="popular">Most Popular</option>
                </select>
                <ChevronDown size={14} className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 pointer-events-none" />
              </div>
            </div>

            {/* Price range */}
            <div>
              <label className="text-xs font-medium text-gray-500 mb-1.5 block">Price Range (FLH)</label>
              <div className="flex items-center gap-2">
                <input
                  type="number"
                  value={draftMinPrice}
                  onChange={(e) => setDraftMinPrice(e.target.value)}
                  placeholder="Min"
                  min={0}
                  className="w-full bg-[#0a0a0f] border border-gray-800/60 rounded-xl px-3 py-2.5 text-sm text-white placeholder-gray-600 focus:outline-none focus:border-[#D4AF37]/50 focus:ring-1 focus:ring-[#D4AF37]/30 min-h-[44px]"
                />
                <span className="text-gray-600 text-xs">—</span>
                <input
                  type="number"
                  value={draftMaxPrice}
                  onChange={(e) => setDraftMaxPrice(e.target.value)}
                  placeholder="Max"
                  min={0}
                  className="w-full bg-[#0a0a0f] border border-gray-800/60 rounded-xl px-3 py-2.5 text-sm text-white placeholder-gray-600 focus:outline-none focus:border-[#D4AF37]/50 focus:ring-1 focus:ring-[#D4AF37]/30 min-h-[44px]"
                />
              </div>
            </div>

            {/* Max delivery days */}
            <div>
              <label className="text-xs font-medium text-gray-500 mb-1.5 block">Max Delivery (days)</label>
              <input
                type="number"
                value={draftDeliveryDays}
                onChange={(e) => setDraftDeliveryDays(e.target.value)}
                placeholder="Any"
                min={1}
                className="w-full bg-[#0a0a0f] border border-gray-800/60 rounded-xl px-3 py-2.5 text-sm text-white placeholder-gray-600 focus:outline-none focus:border-[#D4AF37]/50 focus:ring-1 focus:ring-[#D4AF37]/30 min-h-[44px]"
              />
            </div>

            {/* Apply / Clear */}
            <div className="flex items-center gap-2 pt-1">
              <button
                onClick={() => {
                  setAppliedSortBy(draftSortBy);
                  setAppliedMinPrice(draftMinPrice);
                  setAppliedMaxPrice(draftMaxPrice);
                  setAppliedDeliveryDays(draftDeliveryDays);
                  setShowFilters(false);
                }}
                className="flex-1 bg-[#D4AF37] text-black text-sm font-semibold rounded-xl py-2.5 hover:bg-[#D4AF37]/90 transition active:scale-[0.97]"
              >
                Apply Filters
              </button>
              <button
                onClick={() => {
                  setDraftSortBy("");
                  setDraftMinPrice("");
                  setDraftMaxPrice("");
                  setDraftDeliveryDays("");
                  setAppliedSortBy("");
                  setAppliedMinPrice("");
                  setAppliedMaxPrice("");
                  setAppliedDeliveryDays("");
                  setShowFilters(false);
                }}
                className="flex-1 bg-[#0a0a0f] border border-gray-800/60 text-gray-400 text-sm font-medium rounded-xl py-2.5 hover:text-white transition active:scale-[0.97]"
              >
                Clear
              </button>
            </div>
          </div>
        </div>
      )}

      <div className="px-4 mb-5">
        <h2 className="text-xs font-semibold text-gray-500 uppercase tracking-wider mb-3">
          Categories
        </h2>
        <div className="grid grid-cols-3 gap-3">
          {CATEGORIES.map((cat) => {
            const count = categoryCounts[cat.id] ?? 0;
            const isActive = activeCategory === cat.id;
            return (
              <button
                key={cat.id}
                onClick={() => setActiveCategory(isActive ? null : cat.id)}
                className={`relative bg-[#111118] border rounded-2xl p-4 text-center active:scale-95 transition min-h-[88px] ${
                  isActive
                    ? "border-[#D4AF37]/50 ring-1 ring-[#D4AF37]/30"
                    : "border-gray-800/60 hover:border-gray-700/60"
                }`}
              >
                <div className={`w-9 h-9 rounded-xl mx-auto mb-1.5 flex items-center justify-center ${cat.color}`}>
                  <span className="text-lg">{cat.icon}</span>
                </div>
                <p className="text-[11px] font-medium text-white leading-tight line-clamp-2">
                  {cat.name}
                </p>
                {count > 0 && (
                  <p className="text-[10px] text-gray-600 mt-0.5">
                    {count} item{count !== 1 ? "s" : ""}
                  </p>
                )}
              </button>
            );
          })}
        </div>
      </div>

      {activeCategory && (
        <div className="px-4 mb-4 flex items-center gap-2">
          <span className="text-xs text-gray-500">Filtered by:</span>
          <span className="inline-flex items-center gap-1.5 text-xs font-medium text-[#D4AF37] bg-[#D4AF37]/10 border border-[#D4AF37]/20 rounded-full px-3 py-1.5">
            {CATEGORIES.find((c) => c.id === activeCategory)?.icon}{" "}
            {CATEGORIES.find((c) => c.id === activeCategory)?.name}
            <button onClick={() => setActiveCategory(null)} className="ml-0.5 text-[#D4AF37]/60 hover:text-[#D4AF37] transition">
              <X size={12} />
            </button>
          </span>
        </div>
      )}

      {fetching ? (
        <div className="flex flex-col items-center justify-center py-20">
          <div className="w-8 h-8 rounded-full border-2 border-[#D4AF37]/30 border-t-[#D4AF37] animate-spin mb-3" />
          <p className="text-xs text-gray-600">Loading listings…</p>
        </div>
      ) : filtered.length === 0 ? (
        <div className="mx-4 bg-[#111118] border border-gray-800/60 rounded-2xl p-8 text-center">
          <ShoppingBag size={32} className="mx-auto text-gray-700 mb-3" />
          <p className="text-sm text-gray-500">No listings found</p>
          <p className="text-xs text-gray-700 mt-1">
            {activeCategory ? "Try a different category" : "Check back later for new services"}
          </p>
          {activeCategory && (
            <button onClick={() => setActiveCategory(null)} className="mt-4 text-xs text-[#D4AF37] underline underline-offset-2">
              Clear filter
            </button>
          )}
        </div>
      ) : (
        <>
          {featured.length > 0 && (
            <div className="mb-5">
              <div className="px-4 mb-3 flex items-center justify-between">
                <h2 className="text-sm font-semibold text-white flex items-center gap-2">
                  <Star size={14} className="text-[#D4AF37]" />
                  Featured
                </h2>
                <span className="text-xs text-gray-600">{featured.length} items</span>
              </div>
              <div className="flex gap-3 overflow-x-auto px-4 pb-1 scrollbar-thin scrollbar-thumb-gray-800">
                {featured.map((listing) => (
                  <FeaturedCard key={listing.id} listing={listing} router={router} />
                ))}
              </div>
            </div>
          )}

          <div className="px-4">
            <div className="flex items-center justify-between mb-3">
              <h2 className="text-sm font-semibold text-white flex items-center gap-2">
                <Filter size={14} className="text-gray-500" />
                {activeCategory
                  ? CATEGORIES.find((c) => c.id === activeCategory)?.name ?? "All Services"
                  : "All Services"}
              </h2>
              <span className="text-xs text-gray-600">
                {regular.length + featured.length} item{(regular.length + featured.length) !== 1 ? "s" : ""}
              </span>
            </div>

            <div className="grid grid-cols-2 gap-3">
              {regular.map((listing) => (
                <ListingCard key={listing.id} listing={listing} router={router} />
              ))}
              {regular.length === 0 &&
                featured.slice(0, 4).map((listing) => (
                  <ListingCard key={`dup-${listing.id}`} listing={listing} router={router} />
                ))}
            </div>
          </div>
        </>
      )}

      <div className="h-6" />
    </div>
  );
}

/* ------------------------------------------------------------------ */
/*  Featured Card                                                      */
/* ------------------------------------------------------------------ */

function FeaturedCard({
  listing,
  router,
}: {
  listing: SouqListing;
  router: ReturnType<typeof useRouter>;
}) {
  const vis = listingVisual(listing.category);
  const rating = listing.rating ?? 0;

  return (
    <button
      onClick={() => router.push(`/souq/${listing.id}`)}
      className="shrink-0 w-64 bg-[#111118] border border-gray-800/60 rounded-2xl overflow-hidden text-left active:scale-[0.97] transition min-h-[160px]"
    >
      <div className={`h-28 bg-gradient-to-br ${vis.bg} flex items-center justify-center`}>
        <span className="text-4xl">{vis.emoji}</span>
      </div>
      <div className="p-3 space-y-1.5">
        <p className="text-sm font-semibold text-white leading-tight line-clamp-1">{listing.title}</p>
        <p className="text-xs text-gray-500">{listing.seller?.name || ""}</p>
        <div className="flex items-center gap-1.5">
          <span className="text-xs text-amber-400">{renderStars(rating)}</span>
          {rating > 0 && <span className="text-[10px] text-gray-600">{rating.toFixed(1)}</span>}
        </div>
        <div className="flex items-center justify-between pt-1">
          <p className="text-sm font-bold text-[#D4AF37]">FLH {listing.priceFlh?.toLocaleString()}</p>
          {listing.deliveryDays ? (
            <span className="flex items-center gap-1 text-[10px] text-gray-500">
              <Clock size={10} /> {listing.deliveryDays} days
            </span>
          ) : null}
        </div>
      </div>
    </button>
  );
}

/* ------------------------------------------------------------------ */
/*  Regular Listing Card                                               */
/* ------------------------------------------------------------------ */

function ListingCard({
  listing,
  router,
}: {
  listing: SouqListing;
  router: ReturnType<typeof useRouter>;
}) {
  const vis = listingVisual(listing.category);
  const rating = listing.rating ?? 0;

  return (
    <button
      onClick={() => router.push(`/souq/${listing.id}`)}
      className="bg-[#111118] border border-gray-800/60 rounded-2xl overflow-hidden text-left active:scale-[0.97] transition"
    >
      <div className={`h-24 bg-gradient-to-br ${vis.bg} flex items-center justify-center`}>
        <span className="text-3xl">{vis.emoji}</span>
      </div>
      <div className="p-3 space-y-1">
        <p className="text-sm font-semibold text-white leading-tight line-clamp-2 min-h-[2.5rem]">{listing.title}</p>
        <p className="text-[11px] text-gray-500 truncate">{listing.seller?.name || ""}</p>
        <div className="flex items-center gap-1">
          <span className="text-[11px] text-amber-400">{renderStars(rating)}</span>
          {rating > 0 && <span className="text-[10px] text-gray-600">{rating.toFixed(1)}</span>}
        </div>
        <div className="flex items-center justify-between pt-0.5">
          <p className="text-sm font-bold text-[#D4AF37]">FLH {listing.priceFlh?.toLocaleString()}</p>
          {listing.deliveryDays ? (
            <span className="flex items-center gap-0.5 text-[10px] text-gray-500">
              <Clock size={9} /> {listing.deliveryDays}d
            </span>
          ) : null}
        </div>
      </div>
    </button>
  );
}
