import { useState, useMemo } from "react";
import { useSearchParams } from "react-router-dom";
import { SlidersHorizontal, Grid, List, X } from "lucide-react";
import ProductCard from "@/components/features/ProductCard";
import { PRODUCTS, CATEGORIES } from "@/constants/data";

type SortOption = "default" | "price-asc" | "price-desc" | "rating" | "newest";

export default function ProductsPage() {
  const [searchParams, setSearchParams] = useSearchParams();
  const [sortBy, setSortBy] = useState<SortOption>("default");
  const [showFilters, setShowFilters] = useState(false);
  const [viewMode, setViewMode] = useState<"grid" | "list">("grid");
  const [priceRange, setPriceRange] = useState<[number, number]>([0, 100000]);

  const searchQuery = searchParams.get("search") || "";
  const categoryFilter = searchParams.get("category") || "";
  const filterType = searchParams.get("filter") || "";

  const activeCategory = CATEGORIES.find((c) => c.id === categoryFilter);

  const filtered = useMemo(() => {
    let results = [...PRODUCTS];

    if (searchQuery) {
      results = results.filter(
        (p) =>
          p.name.includes(searchQuery) ||
          p.description.includes(searchQuery) ||
          p.category.includes(searchQuery)
      );
    }

    if (categoryFilter) {
      results = results.filter((p) => p.categoryId === categoryFilter);
    }

    if (filterType === "offers") {
      results = results.filter((p) => p.originalPrice);
    } else if (filterType === "new") {
      results = results.filter((p) => p.isNew);
    } else if (filterType === "featured") {
      results = results.filter((p) => p.isFeatured);
    }

    results = results.filter(
      (p) => p.price >= priceRange[0] && p.price <= priceRange[1]
    );

    switch (sortBy) {
      case "price-asc":
        results.sort((a, b) => a.price - b.price);
        break;
      case "price-desc":
        results.sort((a, b) => b.price - a.price);
        break;
      case "rating":
        results.sort((a, b) => b.rating - a.rating);
        break;
      case "newest":
        results.sort((a, b) => (b.isNew ? 1 : 0) - (a.isNew ? 1 : 0));
        break;
    }

    return results;
  }, [searchQuery, categoryFilter, filterType, sortBy, priceRange]);

  const clearFilter = (key: string) => {
    const params = new URLSearchParams(searchParams);
    params.delete(key);
    setSearchParams(params);
  };

  return (
    <div className="max-w-7xl mx-auto px-4 py-6">
      {/* Page Header */}
      <div className="mb-6">
        <h1 className="text-2xl font-black text-gray-800">
          {activeCategory
            ? `${activeCategory.icon} ${activeCategory.name}`
            : filterType === "offers"
            ? "🔥 العروض والخصومات"
            : filterType === "new"
            ? "🆕 الوصل حديثاً"
            : filterType === "featured"
            ? "⭐ المنتجات المميزة"
            : searchQuery
            ? `نتائج: "${searchQuery}"`
            : "🛍️ جميع المنتجات"}
        </h1>
        <p className="text-gray-500 text-sm mt-1">{filtered.length} منتج</p>

        {/* Active filters */}
        <div className="flex flex-wrap gap-2 mt-3">
          {searchQuery && (
            <span className="flex items-center gap-1 bg-orange-100 text-orange-700 text-xs font-semibold px-3 py-1.5 rounded-full">
              بحث: {searchQuery}
              <button onClick={() => clearFilter("search")} className="hover:text-red-500">
                <X size={12} />
              </button>
            </span>
          )}
          {categoryFilter && (
            <span className="flex items-center gap-1 bg-orange-100 text-orange-700 text-xs font-semibold px-3 py-1.5 rounded-full">
              التصنيف: {activeCategory?.name}
              <button onClick={() => clearFilter("category")} className="hover:text-red-500">
                <X size={12} />
              </button>
            </span>
          )}
          {filterType && (
            <span className="flex items-center gap-1 bg-orange-100 text-orange-700 text-xs font-semibold px-3 py-1.5 rounded-full">
              {filterType === "offers" ? "عروض" : filterType === "new" ? "جديد" : "مميز"}
              <button onClick={() => clearFilter("filter")} className="hover:text-red-500">
                <X size={12} />
              </button>
            </span>
          )}
        </div>
      </div>

      <div className="flex gap-6">
        {/* Sidebar Filters - Desktop */}
        <aside className={`w-64 shrink-0 hidden lg:block`}>
          <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-5 sticky top-24">
            <h3 className="font-black text-gray-800 mb-4 flex items-center gap-2">
              <SlidersHorizontal size={18} className="text-orange-500" />
              تصفية النتائج
            </h3>

            {/* Categories */}
            <div className="mb-6">
              <h4 className="text-sm font-bold text-gray-600 mb-3">التصنيفات</h4>
              <div className="space-y-1.5">
                <button
                  onClick={() => clearFilter("category")}
                  className={`w-full text-right text-sm px-3 py-2 rounded-xl transition-colors ${
                    !categoryFilter
                      ? "bg-orange-500 text-white font-bold"
                      : "text-gray-600 hover:bg-orange-50 hover:text-orange-500"
                  }`}
                >
                  الكل
                </button>
                {CATEGORIES.map((cat) => (
                  <button
                    key={cat.id}
                    onClick={() => {
                      const params = new URLSearchParams(searchParams);
                      params.set("category", cat.id);
                      setSearchParams(params);
                    }}
                    className={`w-full text-right text-sm px-3 py-2 rounded-xl transition-colors flex justify-between items-center ${
                      categoryFilter === cat.id
                        ? "bg-orange-500 text-white font-bold"
                        : "text-gray-600 hover:bg-orange-50 hover:text-orange-500"
                    }`}
                  >
                    <span>
                      {cat.icon} {cat.name}
                    </span>
                    <span className="text-xs opacity-60">{cat.productCount}</span>
                  </button>
                ))}
              </div>
            </div>

            {/* Filter type */}
            <div className="mb-6">
              <h4 className="text-sm font-bold text-gray-600 mb-3">نوع المنتج</h4>
              <div className="space-y-1.5">
                {[
                  { label: "الكل", value: "" },
                  { label: "🔥 عروض وخصومات", value: "offers" },
                  { label: "🆕 وصل حديثاً", value: "new" },
                  { label: "⭐ مميزة", value: "featured" },
                ].map((opt) => (
                  <button
                    key={opt.value}
                    onClick={() => {
                      const params = new URLSearchParams(searchParams);
                      if (opt.value) {
                        params.set("filter", opt.value);
                      } else {
                        params.delete("filter");
                      }
                      setSearchParams(params);
                    }}
                    className={`w-full text-right text-sm px-3 py-2 rounded-xl transition-colors ${
                      filterType === opt.value
                        ? "bg-orange-500 text-white font-bold"
                        : "text-gray-600 hover:bg-orange-50 hover:text-orange-500"
                    }`}
                  >
                    {opt.label}
                  </button>
                ))}
              </div>
            </div>

            {/* Price range */}
            <div>
              <h4 className="text-sm font-bold text-gray-600 mb-3">نطاق السعر (ر.ي)</h4>
              <div className="space-y-3">
                <input
                  type="range"
                  min={0}
                  max={100000}
                  step={500}
                  value={priceRange[1]}
                  onChange={(e) => setPriceRange([priceRange[0], Number(e.target.value)])}
                  className="w-full accent-orange-500"
                />
                <div className="flex justify-between text-xs text-gray-500">
                  <span>0 ر.ي</span>
                  <span>{priceRange[1].toLocaleString()} ر.ي</span>
                </div>
              </div>
            </div>
          </div>
        </aside>

        {/* Main content */}
        <div className="flex-1">
          {/* Toolbar */}
          <div className="flex items-center justify-between mb-4 bg-white rounded-xl p-3 shadow-sm border border-gray-100">
            <div className="flex items-center gap-2">
              <button
                onClick={() => setShowFilters(!showFilters)}
                className="lg:hidden flex items-center gap-1.5 text-sm font-semibold text-gray-600 hover:text-orange-500 transition-colors bg-gray-50 px-3 py-2 rounded-lg"
              >
                <SlidersHorizontal size={16} />
                فلترة
              </button>
              <div className="flex gap-1">
                <button
                  onClick={() => setViewMode("grid")}
                  className={`p-2 rounded-lg transition-colors ${viewMode === "grid" ? "bg-orange-500 text-white" : "text-gray-400 hover:text-orange-500"}`}
                >
                  <Grid size={16} />
                </button>
                <button
                  onClick={() => setViewMode("list")}
                  className={`p-2 rounded-lg transition-colors ${viewMode === "list" ? "bg-orange-500 text-white" : "text-gray-400 hover:text-orange-500"}`}
                >
                  <List size={16} />
                </button>
              </div>
            </div>

            <select
              value={sortBy}
              onChange={(e) => setSortBy(e.target.value as SortOption)}
              className="text-sm text-gray-600 border border-gray-200 rounded-lg px-3 py-2 outline-none focus:border-orange-400 bg-white"
            >
              <option value="default">الترتيب الافتراضي</option>
              <option value="price-asc">السعر: الأقل أولاً</option>
              <option value="price-desc">السعر: الأعلى أولاً</option>
              <option value="rating">الأعلى تقييماً</option>
              <option value="newest">الأحدث</option>
            </select>
          </div>

          {/* Mobile filters */}
          {showFilters && (
            <div className="lg:hidden bg-white rounded-2xl p-4 mb-4 shadow-sm border border-gray-100 animate-fade-in-up">
              <h4 className="font-bold text-gray-700 mb-3">التصنيفات</h4>
              <div className="flex flex-wrap gap-2">
                <button
                  onClick={() => clearFilter("category")}
                  className={`text-xs font-semibold px-3 py-1.5 rounded-full transition-colors ${!categoryFilter ? "bg-orange-500 text-white" : "bg-gray-100 text-gray-600"}`}
                >
                  الكل
                </button>
                {CATEGORIES.map((cat) => (
                  <button
                    key={cat.id}
                    onClick={() => {
                      const params = new URLSearchParams(searchParams);
                      params.set("category", cat.id);
                      setSearchParams(params);
                      setShowFilters(false);
                    }}
                    className={`text-xs font-semibold px-3 py-1.5 rounded-full transition-colors ${categoryFilter === cat.id ? "bg-orange-500 text-white" : "bg-gray-100 text-gray-600"}`}
                  >
                    {cat.icon} {cat.name}
                  </button>
                ))}
              </div>
            </div>
          )}

          {/* Products grid */}
          {filtered.length === 0 ? (
            <div className="text-center py-20">
              <div className="text-6xl mb-4">🔍</div>
              <h3 className="text-xl font-bold text-gray-700 mb-2">لا توجد نتائج</h3>
              <p className="text-gray-400 text-sm">جرب تغيير معايير البحث أو التصفية</p>
            </div>
          ) : (
            <div className={viewMode === "grid" ? "grid grid-cols-2 md:grid-cols-3 xl:grid-cols-4 gap-4" : "flex flex-col gap-4"}>
              {filtered.map((product) => (
                <ProductCard key={product.id} product={product} />
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
