"use client";

import React, { useState, useEffect } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { motion } from "framer-motion";
import { Filter, X } from "lucide-react";
import Image from "next/image";
import useAxios from "@/hooks/useAxios";

interface AcademyFilterProps {
  onFilterChange?: (filters: any) => void;
}

interface IAcademyCategory {
  _id: string;
  title: string;
  slug: string;
  description?: string;
  icon?: string;
  color?: string;
  parent?: string | null;
  level: number;
  order: number;
  course_count: number;
  status: string;
  is_featured: boolean;
}

interface CategoryOption {
  value: string;
  label: string;
  icon?: string;
  color?: string;
}

const sortOptions = [
  { value: "createdAt_desc", label: "جدیدترین" },
  { value: "createdAt_asc", label: "قدیمی‌ترین" },
  { value: "likes_desc", label: "محبوب‌ترین" },
  { value: "price_asc", label: "ارزان‌ترین" },
  { value: "price_desc", label: "گران‌ترین" },
];

const courseTypes = [
  { value: "", label: "همه دوره‌ها" },
  { value: "normal", label: "معمولی" },
  { value: "pro", label: "پرو" },
];

export default function AcademyFilter({ onFilterChange }: AcademyFilterProps) {
  const router = useRouter();
  const searchParams = useSearchParams();
  
  const [isOpen, setIsOpen] = useState(false);
  const [filters, setFilters] = useState({
    search: "",
    category: "",
    minPrice: "",
    maxPrice: "",
    hasOffer: false,
    type: "",
    sortBy: "createdAt_desc",
  });

  const [categories, setCategories] = useState<CategoryOption[]>([
    { value: "", label: "همه دسته‌ها" }
  ]);
  const [categoriesLoading, setCategoriesLoading] = useState(false);
  const { request } = useAxios();

  // ==========================================
  // دریافت دسته‌بندی‌های آکادمی از API جدید
  // ==========================================
  useEffect(() => {
    const fetchAcademyCategories = async () => {
      setCategoriesLoading(true);
      try {
        const response = await request<{ data: { docs: IAcademyCategory[] } }>(
          "GET",
          "/academy/categories?status=active&limit=100"
        );
        
        let categoriesList: IAcademyCategory[] = [];
        
        if (response?.data?.docs) {
          categoriesList = response.data.docs;
        } else if (response?.data && Array.isArray(response.data)) {
          categoriesList = response.data;
        } else if (Array.isArray(response)) {
          categoriesList = response;
        }
        
        console.log("دسته‌بندی‌های آکادمی:", categoriesList);
        
        // ==========================================
        // ✅ تغییر مهم: استفاده از title به عنوان value
        // ==========================================
        const formattedCategories: CategoryOption[] = [
          { value: "", label: "همه دسته‌ها" },
          ...categoriesList.map((cat) => ({
            value: cat.title,  // استفاده از عنوان دسته‌بندی
            label: cat.title,
            icon: cat.icon,
            color: cat.color,
          }))
        ];
        
        setCategories(formattedCategories);
        console.log("دسته‌بندی فرمت شده:", formattedCategories);
      } catch (err) {
        console.log("خطا در دریافت دسته‌بندی آکادمی:", err);
      } finally {
        setCategoriesLoading(false);
      }
    };
    
    fetchAcademyCategories();
  }, []);

  // خواندن فیلترها از URL
  useEffect(() => {
    setFilters({
      search: searchParams.get("search") || "",
      category: searchParams.get("category") || "",
      minPrice: searchParams.get("minPrice") || "",
      maxPrice: searchParams.get("maxPrice") || "",
      hasOffer: searchParams.get("hasOffer") === "true",
      type: searchParams.get("type") || "",
      sortBy: searchParams.get("sortBy") || "createdAt_desc",
    });
  }, []);

  const updateURL = (newFilters: any) => {
    const params = new URLSearchParams();
    
    if (newFilters.search) params.set("search", newFilters.search);
    if (newFilters.category) params.set("category", newFilters.category);
    if (newFilters.minPrice) params.set("minPrice", newFilters.minPrice);
    if (newFilters.maxPrice) params.set("maxPrice", newFilters.maxPrice);
    if (newFilters.hasOffer) params.set("hasOffer", "true");
    if (newFilters.type) params.set("type", newFilters.type);
    if (newFilters.sortBy && newFilters.sortBy !== "createdAt_desc") {
      params.set("sortBy", newFilters.sortBy);
    }
    
    const queryString = params.toString();
    const newUrl = queryString ? `/academy?${queryString}` : "/academy";
    router.push(newUrl, { scroll: false });
  };

  const handleInputChange = (name: string, value: any) => {
    const newFilters = { ...filters, [name]: value };
    setFilters(newFilters);
    
    let sortBy = "createdAt";
    let sortOrder = "desc";
    if (newFilters.sortBy === "createdAt_asc") {
      sortBy = "createdAt";
      sortOrder = "asc";
    } else if (newFilters.sortBy === "price_asc") {
      sortBy = "price";
      sortOrder = "asc";
    } else if (newFilters.sortBy === "price_desc") {
      sortBy = "price";
      sortOrder = "desc";
    } else if (newFilters.sortBy === "likes_desc") {
      sortBy = "likes";
      sortOrder = "desc";
    }
    
    const finalFilters = {
      search: newFilters.search,
      category: newFilters.category,
      minPrice: newFilters.minPrice ? Number(newFilters.minPrice) : undefined,
      maxPrice: newFilters.maxPrice ? Number(newFilters.maxPrice) : undefined,
      hasOffer: newFilters.hasOffer,
      type: newFilters.type,
      sortBy,
      sortOrder,
    };
    
    updateURL(newFilters);
    if (onFilterChange) onFilterChange(finalFilters);
  };

  const handleSearch = (e: React.FormEvent) => {
    e.preventDefault();
    handleInputChange("search", filters.search);
  };

  const clearFilters = () => {
    const emptyFilters = {
      search: "",
      category: "",
      minPrice: "",
      maxPrice: "",
      hasOffer: false,
      type: "",
      sortBy: "createdAt_desc",
    };
    setFilters(emptyFilters);
    router.push("/academy", { scroll: false });
    if (onFilterChange) onFilterChange({});
  };

  const activeFiltersCount = Object.values(filters).filter(v => 
    v !== "" && v !== false && v !== "createdAt_desc"
  ).length;

  const selectedCategory = categories.find(cat => cat.value === filters.category);

  return (
    <div className="z-30 backdrop-blur-lg border-b border-gray-200 dark:border-gray-700">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-4">
        {/* نوار جستجو و فیلتر */}
        <div className="flex flex-col md:flex-row gap-4">
          <form onSubmit={handleSearch} className="flex-1">
            <div className="relative">
              <input
                type="text"
                value={filters.search}
                onChange={(e) => setFilters({ ...filters, search: e.target.value })}
                placeholder="جستجوی دوره، مدرس، ..."
                className="w-full px-4 py-2 pr-10 border border-gray-300 dark:border-gray-600 rounded-xl bg-gray-50 dark:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-pink-500 focus:border-transparent"
              />
              <Image
                src="/images/icons/search-normal.svg"
                alt=""
                width={20}
                height={20}
                className="absolute left-3 top-2.5 opacity-60 dark:invert"
              />
            </div>
          </form>

          <button
            onClick={() => setIsOpen(!isOpen)}
            className={`flex items-center gap-2 px-4 py-2 rounded-xl transition-all duration-200 ${
              isOpen || activeFiltersCount > 0
                ? "bg-pink-500 text-white"
                : "bg-gray-100 dark:bg-gray-800 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-700"
            }`}
          >
            <Filter className="w-5 h-5" />
            <span>فیلترها</span>
            {activeFiltersCount > 0 && (
              <span className="bg-white text-pink-500 text-xs rounded-full px-2 py-0.5">
                {activeFiltersCount}
              </span>
            )}
          </button>
        </div>

        <motion.div
          initial={false}
          animate={{ height: isOpen ? "auto" : 0, opacity: isOpen ? 1 : 0 }}
          transition={{ duration: 0.3 }}
          className="overflow-hidden"
        >
          <div className="pt-4 pb-2 space-y-4">
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
              {/* دسته بندی آکادمی */}
              <div>
                <label className="block text-sm font-medium mb-1">دسته بندی</label>
                <select
                  value={filters.category}
                  onChange={(e) => handleInputChange("category", e.target.value)}
                  className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-gray-50 dark:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-pink-500"
                  disabled={categoriesLoading}
                >
                  {categoriesLoading ? (
                    <option value="" disabled>در حال بارگذاری...</option>
                  ) : (
                    categories.map((cat) => (
                      <option key={cat.value} value={cat.value}>
                        {cat.icon && `${cat.icon} `} {cat.label}
                      </option>
                    ))
                  )}
                </select>
                
                {selectedCategory && selectedCategory.value !== "" && (
                  <div className="mt-1 text-xs text-gray-500 flex items-center gap-1">
                    <span>انتخاب شده:</span>
                    {selectedCategory.icon && <span>{selectedCategory.icon}</span>}
                    <span style={{ color: selectedCategory.color }}>
                      {selectedCategory.label}
                    </span>
                  </div>
                )}
              </div>

              {/* نوع دوره */}
              <div>
                <label className="block text-sm font-medium mb-1">نوع دوره</label>
                <select
                  value={filters.type}
                  onChange={(e) => handleInputChange("type", e.target.value)}
                  className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-gray-50 dark:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-pink-500"
                >
                  {courseTypes.map((type) => (
                    <option key={type.value} value={type.value}>{type.label}</option>
                  ))}
                </select>
              </div>

              {/* محدوده قیمت */}
              <div>
                <label className="block text-sm font-medium mb-1">محدوده قیمت (تومان)</label>
                <div className="flex gap-2">
                  <input
                    type="number"
                    placeholder="از"
                    value={filters.minPrice}
                    onChange={(e) => handleInputChange("minPrice", e.target.value)}
                    className="w-1/2 px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-gray-50 dark:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-pink-500"
                  />
                  <input
                    type="number"
                    placeholder="تا"
                    value={filters.maxPrice}
                    onChange={(e) => handleInputChange("maxPrice", e.target.value)}
                    className="w-1/2 px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-gray-50 dark:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-pink-500"
                  />
                </div>
              </div>

              {/* مرتب سازی */}
              <div>
                <label className="block text-sm font-medium mb-1">مرتب سازی</label>
                <select
                  value={filters.sortBy}
                  onChange={(e) => handleInputChange("sortBy", e.target.value)}
                  className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-gray-50 dark:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-pink-500"
                >
                  {sortOptions.map((opt) => (
                    <option key={opt.value} value={opt.value}>{opt.label}</option>
                  ))}
                </select>
              </div>
            </div>

            <div className="flex items-center gap-2">
              <input
                type="checkbox"
                id="hasOffer"
                checked={filters.hasOffer}
                onChange={(e) => handleInputChange("hasOffer", e.target.checked)}
                className="w-4 h-4 text-pink-500 rounded focus:ring-pink-500"
              />
              <label htmlFor="hasOffer" className="text-sm">فقط دوره‌های دارای تخفیف</label>
            </div>

            {activeFiltersCount > 0 && (
              <button
                onClick={clearFilters}
                className="flex items-center gap-1 text-sm text-pink-500 hover:text-pink-600 transition"
              >
                <X className="w-4 h-4" />
                پاک کردن همه فیلترها
              </button>
            )}
          </div>
        </motion.div>
      </div>
    </div>
  );
}