import { useEffect, useState, useCallback } from 'react';
import Header from '../components/Header';
import { useStore } from '../hooks/useStore';
import { useParams } from 'react-router-dom';
import { requestGetProductByCategory } from '../config/product';
import CardBody from '../components/CardBody';
import { Search, X, Filter, ArrowUpDown, ChevronLeft, ChevronRight } from 'lucide-react';
import Footer from '../components/Footer';

import { Helmet } from 'react-helmet';

function CategoryAccount() {
    const { dataCategory, dataWebsite } = useStore();
    const { slug } = useParams();

    const [products, setProducts] = useState([]);
    const [categoryId, setCategoryId] = useState(null);
    const [categoryName, setCategoryName] = useState('');
    const [loading, setLoading] = useState(true);
    const [pagination, setPagination] = useState({
        page: 1,
        limit: 12,
        total: 0,
        totalPages: 0,
    });

    // Filter states
    const [priceFilter, setPriceFilter] = useState('all');
    const [sortOrder, setSortOrder] = useState('default');
    const [searchTerm, setSearchTerm] = useState('');

    // Fetch products with filters
    const fetchProducts = useCallback(
        async (page = 1) => {
            if (!categoryId) return;

            setLoading(true);
            try {
                // Parse price filter
                let minPrice, maxPrice;
                if (priceFilter !== 'all') {
                    const parts = priceFilter.split('-');
                    minPrice = parts[0] || undefined;
                    maxPrice = parts[1] || undefined;
                }

                const res = await requestGetProductByCategory(categoryId, {
                    minPrice,
                    maxPrice,
                    sortBy: sortOrder !== 'default' ? sortOrder : undefined,
                    search: searchTerm || undefined,
                    page,
                    limit: pagination.limit,
                });

                if (res.metadata) {
                    setProducts(res.metadata);
                }
                if (res.pagination) {
                    setPagination(res.pagination);
                }
            } catch (error) {
                console.log(error);
            }
            setLoading(false);
        },
        [categoryId, priceFilter, sortOrder, searchTerm, pagination.limit],
    );

    // Find category by slug
    useEffect(() => {
        const category = dataCategory.find((item) => item.slug === slug);
        if (category) {
            setCategoryName(category.nameCategory);
            setCategoryId(category._id);
        }
    }, [dataCategory, slug]);

    // Fetch on mount and when categoryId changes
    useEffect(() => {
        if (categoryId) {
            fetchProducts(1);
        }
    }, [categoryId]);

    // Handle filter button click
    const handleSearch = () => {
        fetchProducts(1);
    };

    // Handle clear filters
    const handleClearFilters = () => {
        setPriceFilter('all');
        setSortOrder('default');
        setSearchTerm('');
        // Refetch with cleared filters
        setTimeout(() => fetchProducts(1), 0);
    };

    // Handle page change
    const handlePageChange = (newPage) => {
        if (newPage >= 1 && newPage <= pagination.totalPages) {
            fetchProducts(newPage);
            window.scrollTo({ top: 0, behavior: 'smooth' });
        }
    };

    // Generate page numbers
    const getPageNumbers = () => {
        const pages = [];
        const { page, totalPages } = pagination;

        if (totalPages <= 7) {
            for (let i = 1; i <= totalPages; i++) pages.push(i);
        } else {
            if (page <= 3) {
                pages.push(1, 2, 3, 4, '...', totalPages);
            } else if (page >= totalPages - 2) {
                pages.push(1, '...', totalPages - 3, totalPages - 2, totalPages - 1, totalPages);
            } else {
                pages.push(1, '...', page - 1, page, page + 1, '...', totalPages);
            }
        }
        return pages;
    };

    return (
        <div className="min-h-screen bg-gradient-to-br from-slate-50 via-white to-orange-50">
            <Helmet>
                <title>
                    {categoryName
                        ? `${categoryName} | ${dataWebsite?.nameWebsite || 'Website'}`
                        : dataWebsite?.nameWebsite || 'Website'}
                </title>
            </Helmet>
            <header className="pb-16">
                <Header />
            </header>

            <main className="container mx-auto px-4 py-8">
                {/* Page Title */}
                <div className="text-center mb-8">
                    <h1 className="inline-block text-3xl font-bold bg-gradient-to-r from-orange-600 via-red-500 to-pink-500 bg-clip-text text-transparent">
                        {categoryName || 'Tài Khoản Game'}
                    </h1>
                    <div className="mt-2 w-32 h-1 bg-gradient-to-r from-orange-500 to-red-500 mx-auto rounded-full"></div>
                </div>

                {/* Filter Section */}
                <div className="bg-white/80 backdrop-blur-sm rounded-2xl shadow-xl border border-gray-100 p-6 mb-8">
                    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
                        {/* Price Filter */}
                        <div className="space-y-2">
                            <label className="flex items-center gap-2 text-sm font-semibold text-gray-700">
                                <Filter size={16} className="text-orange-500" />
                                MỨC GIÁ
                            </label>
                            <select
                                value={priceFilter}
                                onChange={(e) => setPriceFilter(e.target.value)}
                                className="w-full bg-gray-50 border border-gray-200 rounded-xl px-4 py-3 text-gray-700 focus:outline-none focus:ring-2 focus:ring-orange-400 focus:border-transparent transition-all duration-200 cursor-pointer"
                            >
                                <option value="all">Tất cả mức giá</option>
                                <option value="0-500000">Dưới 500K</option>
                                <option value="500000-1000000">500K - 1M</option>
                                <option value="1000000-2000000">1M - 2M</option>
                                <option value="2000000-5000000">2M - 5M</option>
                                <option value="5000000-">Trên 5M</option>
                            </select>
                        </div>

                        {/* Sort */}
                        <div className="space-y-2">
                            <label className="flex items-center gap-2 text-sm font-semibold text-gray-700">
                                <ArrowUpDown size={16} className="text-orange-500" />
                                SẮP XẾP
                            </label>
                            <select
                                value={sortOrder}
                                onChange={(e) => setSortOrder(e.target.value)}
                                className="w-full bg-gray-50 border border-gray-200 rounded-xl px-4 py-3 text-gray-700 focus:outline-none focus:ring-2 focus:ring-orange-400 focus:border-transparent transition-all duration-200 cursor-pointer"
                            >
                                <option value="default">Mặc định</option>
                                <option value="price-asc">Giá thấp → cao</option>
                                <option value="price-desc">Giá cao → thấp</option>
                                <option value="newest">Mới nhất</option>
                            </select>
                        </div>

                        {/* Search */}
                        <div className="space-y-2">
                            <label className="flex items-center gap-2 text-sm font-semibold text-gray-700">
                                <Search size={16} className="text-orange-500" />
                                TÌM KIẾM
                            </label>
                            <div className="relative">
                                <input
                                    type="text"
                                    value={searchTerm}
                                    onChange={(e) => setSearchTerm(e.target.value)}
                                    onKeyDown={(e) => e.key === 'Enter' && handleSearch()}
                                    placeholder="Nhập mã SP..."
                                    className="w-full bg-gray-50 border border-gray-200 rounded-xl pl-4 pr-10 py-3 text-gray-700 focus:outline-none focus:ring-2 focus:ring-orange-400 focus:border-transparent transition-all duration-200"
                                />
                                <Search className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400" size={18} />
                            </div>
                        </div>

                        {/* Action Buttons */}
                        <div className="space-y-2">
                            <label className="text-sm font-semibold text-transparent">Action</label>
                            <div className="flex gap-3">
                                <button
                                    onClick={handleSearch}
                                    className="flex-1 bg-gradient-to-r from-yellow-400 to-orange-400 hover:from-yellow-500 hover:to-orange-500 text-white font-semibold py-3 px-4 rounded-xl flex items-center justify-center gap-2 shadow-lg hover:shadow-xl transition-all duration-300 transform hover:-translate-y-0.5"
                                >
                                    <Search size={18} /> Tìm
                                </button>
                                <button
                                    onClick={handleClearFilters}
                                    className="flex-1 bg-gray-100 hover:bg-gray-200 text-gray-600 font-semibold py-3 px-4 rounded-xl flex items-center justify-center gap-2 transition-all duration-300"
                                >
                                    <X size={18} /> Xóa
                                </button>
                            </div>
                        </div>
                    </div>
                </div>

                {/* Results Info */}
                <div className="flex items-center justify-between mb-6">
                    <p className="text-gray-600">
                        Tìm thấy <span className="font-bold text-orange-600">{pagination.total}</span> sản phẩm
                        {pagination.totalPages > 1 && (
                            <span className="text-gray-400 ml-2">
                                (Trang {pagination.page}/{pagination.totalPages})
                            </span>
                        )}
                    </p>
                    {(priceFilter !== 'all' || sortOrder !== 'default' || searchTerm) && (
                        <button
                            onClick={handleClearFilters}
                            className="text-sm text-orange-600 hover:text-orange-700 font-medium flex items-center gap-1"
                        >
                            <X size={14} /> Xóa bộ lọc
                        </button>
                    )}
                </div>

                {/* Products Grid */}
                {loading ? (
                    <div className="flex flex-col items-center justify-center py-20">
                        <div className="relative">
                            <div className="w-16 h-16 border-4 border-orange-200 rounded-full animate-spin border-t-orange-500"></div>
                        </div>
                        <p className="mt-4 text-gray-500 font-medium">Đang tải sản phẩm...</p>
                    </div>
                ) : products.length === 0 ? (
                    <div className="flex flex-col items-center justify-center py-20 bg-white/50 rounded-2xl">
                        <div className="text-6xl mb-4">🔍</div>
                        <p className="text-xl font-semibold text-gray-700">Không tìm thấy sản phẩm</p>
                        <p className="text-gray-500 mt-2">Thử thay đổi bộ lọc hoặc từ khóa tìm kiếm</p>
                        <button
                            onClick={handleClearFilters}
                            className="mt-4 bg-orange-500 hover:bg-orange-600 text-white font-medium px-6 py-2 rounded-full transition-colors"
                        >
                            Xóa bộ lọc
                        </button>
                    </div>
                ) : (
                    <>
                        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
                            {products.map((product) => (
                                <CardBody key={product._id} product={product} />
                            ))}
                        </div>

                        {/* Pagination */}
                        {pagination.totalPages > 1 && (
                            <div className="flex justify-center items-center gap-2 mt-10">
                                {/* Previous Button */}
                                <button
                                    onClick={() => handlePageChange(pagination.page - 1)}
                                    disabled={pagination.page === 1}
                                    className={`p-2 rounded-lg border transition-all ${
                                        pagination.page === 1
                                            ? 'border-gray-200 text-gray-300 cursor-not-allowed'
                                            : 'border-gray-300 text-gray-600 hover:bg-orange-50 hover:border-orange-400 hover:text-orange-600'
                                    }`}
                                >
                                    <ChevronLeft size={20} />
                                </button>

                                {/* Page Numbers */}
                                {getPageNumbers().map((pageNum, idx) => (
                                    <button
                                        key={idx}
                                        onClick={() => pageNum !== '...' && handlePageChange(pageNum)}
                                        disabled={pageNum === '...'}
                                        className={`min-w-[40px] h-10 rounded-lg font-medium transition-all ${
                                            pageNum === pagination.page
                                                ? 'bg-gradient-to-r from-orange-500 to-red-500 text-white shadow-lg'
                                                : pageNum === '...'
                                                  ? 'text-gray-400 cursor-default'
                                                  : 'border border-gray-300 text-gray-600 hover:bg-orange-50 hover:border-orange-400 hover:text-orange-600'
                                        }`}
                                    >
                                        {pageNum}
                                    </button>
                                ))}

                                {/* Next Button */}
                                <button
                                    onClick={() => handlePageChange(pagination.page + 1)}
                                    disabled={pagination.page === pagination.totalPages}
                                    className={`p-2 rounded-lg border transition-all ${
                                        pagination.page === pagination.totalPages
                                            ? 'border-gray-200 text-gray-300 cursor-not-allowed'
                                            : 'border-gray-300 text-gray-600 hover:bg-orange-50 hover:border-orange-400 hover:text-orange-600'
                                    }`}
                                >
                                    <ChevronRight size={20} />
                                </button>
                            </div>
                        )}
                    </>
                )}
            </main>
            <Footer />
        </div>
    );
}

export default CategoryAccount;
