"use client";

import React, { useEffect, useState } from "react";
import { ChevronLeft, ChevronRight, Search, X } from "lucide-react";
import { Swiper, SwiperSlide } from "swiper/react";
import { Navigation } from "swiper/modules";
import "swiper/css";
import "swiper/css/navigation";
import "swiper/css/pagination";
import apis from "@/utils/apis";
import { getValidImage } from "@/lib/utils";

interface CategoriesSectionProps {
    categoryType?: string;
    selectedCategoryId?: string | null;
    onSelectCategory?: (id: string | null) => void;
    title?: string;
}

export default function CategoriesSection({
    categoryType = "food",
    selectedCategoryId = null,
    onSelectCategory,
    title = "Categories",
}: CategoriesSectionProps) {
    const [categories, setCategories] = useState<any[]>([]);
    const [allCategories, setAllCategories] = useState<any[]>([]);
    const [loading, setLoading] = useState<boolean>(true);
    const [modalLoading, setModalLoading] = useState<boolean>(false);
    const [showModal, setShowModal] = useState<boolean>(false);
    const [searchQuery, setSearchQuery] = useState<string>("");

    const fetchCategories = async () => {
        try {
            setLoading(true);
            const res = await apis.category.getCustomerCategories(
                `type=${categoryType}&page=1&limit=10`
            );
            const list = Array.isArray(res?.data)
                ? res.data
                : Array.isArray(res)
                ? res
                : [];
            setCategories(list);
        } catch (error) {
            console.error("Fetch categories error:", error);
        } finally {
            setLoading(false);
        }
    };

    const fetchAllCategories = async () => {
        try {
            setModalLoading(true);
            const res = await apis.category.getCustomerCategories(
                `type=${categoryType}&page=1&limit=100`
            );
            const list = Array.isArray(res?.data)
                ? res.data
                : Array.isArray(res)
                ? res
                : [];
            setAllCategories(list);
        } catch (error) {
            console.error("Fetch all categories error:", error);
        } finally {
            setModalLoading(false);
        }
    };

    useEffect(() => {
        if (categoryType) {
            fetchCategories();
            setAllCategories([]);
        }
    }, [categoryType]);

    const handleOpenModal = () => {
        setShowModal(true);
        if (allCategories.length === 0) {
            fetchAllCategories();
        }
    };

    const handleSelect = (cat: any) => {
        const isAll = cat._id === "all" || cat?.category_name?.toLowerCase() === "all";
        const selectedId = isAll ? null : cat._id;
        if (onSelectCategory) {
            onSelectCategory(selectedId);
        }
    };

    const navPrevClass = `cat-prev-${categoryType.replace(/[^a-zA-Z0-9]/g, "")}`;
    const navNextClass = `cat-next-${categoryType.replace(/[^a-zA-Z0-9]/g, "")}`;

    return (
        <div className="max-w-7xl mx-auto mb-8 bg-white p-6 rounded-2xl border border-gray-100 shadow-sm">
            {/* Header */}
            <div className="flex items-center justify-between mb-6">
                <h3 className="text-xl sm:text-2xl font-bold text-gray-900 tracking-tight">
                    {title}
                </h3>
                <div className="flex items-center gap-3">
                    <button
                        onClick={handleOpenModal}
                        className="text-sm sm:text-base font-semibold text-primary hover:text-primary/80 transition-colors cursor-pointer"
                    >
                        See All
                    </button>
                    <div className="flex items-center gap-2">
                        <button
                            className={`${navPrevClass} w-9 h-9 rounded-full bg-white border border-gray-200 flex items-center justify-center text-gray-600 hover:bg-gray-100 transition-all disabled:opacity-30 shadow-sm cursor-pointer`}
                            aria-label="Previous category"
                        >
                            <ChevronLeft className="w-5 h-5 text-gray-700" />
                        </button>
                        <button
                            className={`${navNextClass} w-9 h-9 rounded-full bg-primary flex items-center justify-center text-white hover:bg-primary/90 transition-all disabled:opacity-30 shadow-sm cursor-pointer`}
                            aria-label="Next category"
                        >
                            <ChevronRight className="w-5 h-5 text-white" />
                        </button>
                    </div>
                </div>
            </div>

            {/* Slider */}
            {loading ? (
                <div className="flex gap-6 overflow-hidden py-2">
                    {Array.from({ length: 10 }).map((_, i) => (
                        <div key={i} className="flex flex-col items-center gap-2 animate-pulse flex-1">
                            <div className="w-18 h-18 sm:w-20 sm:h-20 rounded-full bg-gray-200" />
                            <div className="h-4 w-12 bg-gray-200 rounded" />
                        </div>
                    ))}
                </div>
            ) : (
                <Swiper
                    modules={[Navigation]}
                    spaceBetween={16}
                    slidesPerView={4}
                    breakpoints={{
                        320: { slidesPerView: 3.5, spaceBetween: 12 },
                        480: { slidesPerView: 4.5, spaceBetween: 16 },
                        640: { slidesPerView: 6, spaceBetween: 16 },
                        768: { slidesPerView: 8, spaceBetween: 18 },
                        1024: { slidesPerView: 10, spaceBetween: 16 },
                    }}
                    navigation={{
                        prevEl: `.${navPrevClass}`,
                        nextEl: `.${navNextClass}`,
                    }}
                    className="py-4 px-1"
                >
                    {categories?.map((cat) => {
                        const isAll =
                            cat._id === "all" ||
                            cat?.category_name?.toLowerCase() === "all";

                        const isSelected = isAll
                            ? selectedCategoryId === null ||
                              selectedCategoryId === "all" ||
                              selectedCategoryId === cat._id
                            : selectedCategoryId === cat._id ||
                              selectedCategoryId === cat.category_name;

                        const imgSrc =
                            isAll && (!cat?.category_image || cat.category_image.trim() === "")
                                ? "https://images.unsplash.com/photo-1542838132-92c53300491e?auto=format&fit=crop&w=300&q=80"
                                : getValidImage(cat?.category_image || cat?.image);

                        return (
                            <SwiperSlide key={cat._id}>
                                <div
                                    className="flex flex-col items-center cursor-pointer group select-none w-full py-1.5"
                                    onClick={() => handleSelect(cat)}
                                >
                                    <div
                                        className={`w-18 h-18 sm:w-20 sm:h-20 rounded-full flex items-center justify-center transition-all duration-300 ${
                                            isSelected
                                                ? "p-[3px] border-2 border-primary shadow-md scale-105"
                                                : "border border-gray-200 group-hover:border-primary/50 group-hover:scale-105"
                                        }`}
                                    >
                                        <div className="w-full h-full rounded-full overflow-hidden">
                                            <img
                                                src={imgSrc}
                                                alt={cat?.category_name || cat?.name}
                                                className="w-full h-full object-cover"
                                            />
                                        </div>
                                    </div>
                                    <span
                                        className={`text-xs sm:text-sm mt-2 font-medium transition-colors text-center line-clamp-1 w-full ${
                                            isSelected
                                                ? "text-primary font-bold"
                                                : "text-gray-700 group-hover:text-primary"
                                        }`}
                                    >
                                        {cat?.category_name || cat?.name}
                                    </span>
                                </div>
                            </SwiperSlide>
                        );
                    })}
                </Swiper>
            )}

            {/* Modal */}
            {showModal && (
                <div className="fixed inset-0 bg-black/60 backdrop-blur-sm z-50 flex items-center justify-center p-4">
                    <div className="bg-white rounded-3xl shadow-2xl max-w-4xl w-full max-h-[85vh] overflow-hidden flex flex-col animate-in fade-in zoom-in-95 duration-200">
                        {/* Header */}
                        <div className="p-5 sm:p-6 border-b border-gray-100 flex items-center justify-between gap-4">
                            <div>
                                <h3 className="text-xl sm:text-2xl font-bold text-gray-900">All Categories</h3>
                                <p className="text-xs sm:text-sm text-gray-500 mt-0.5">Explore all available categories</p>
                            </div>
                            <div className="flex items-center gap-3">
                                <div className="relative hidden sm:block w-64">
                                    <Search className="w-4 h-4 text-gray-400 absolute left-3 top-1/2 -translate-y-1/2" />
                                    <input
                                        type="text"
                                        placeholder="Search category..."
                                        value={searchQuery}
                                        onChange={(e) => setSearchQuery(e.target.value)}
                                        className="w-full pl-9 pr-4 py-2 bg-gray-100/80 rounded-full text-sm outline-none focus:ring-2 focus:ring-primary/20 text-gray-900"
                                    />
                                </div>
                                <button
                                    onClick={() => {
                                        setShowModal(false);
                                        setSearchQuery("");
                                    }}
                                    className="w-9 h-9 rounded-full bg-gray-100 hover:bg-gray-200 flex items-center justify-center text-gray-600 transition-colors cursor-pointer"
                                >
                                    <X className="w-5 h-5" />
                                </button>
                            </div>
                        </div>

                        {/* Search on mobile */}
                        <div className="px-5 pt-3 sm:hidden">
                            <div className="relative w-full">
                                <Search className="w-4 h-4 text-gray-400 absolute left-3 top-1/2 -translate-y-1/2" />
                                <input
                                    type="text"
                                    placeholder="Search category..."
                                    value={searchQuery}
                                    onChange={(e) => setSearchQuery(e.target.value)}
                                    className="w-full pl-9 pr-4 py-2 bg-gray-100/80 rounded-full text-sm outline-none focus:ring-2 focus:ring-primary/20 text-gray-900"
                                />
                            </div>
                        </div>

                        {/* Content / Grid */}
                        <div className="p-5 sm:p-6 overflow-y-auto flex-grow">
                            {modalLoading ? (
                                <div className="grid grid-cols-3 sm:grid-cols-4 md:grid-cols-6 lg:grid-cols-8 gap-4 sm:gap-6">
                                    {Array.from({ length: 16 }).map((_, i) => (
                                        <div key={i} className="flex flex-col items-center gap-2 animate-pulse">
                                            <div className="w-18 h-18 sm:w-20 sm:h-20 rounded-full bg-gray-200" />
                                            <div className="h-4 w-12 bg-gray-200 rounded" />
                                        </div>
                                    ))}
                                </div>
                            ) : (
                                <div className="grid grid-cols-3 sm:grid-cols-4 md:grid-cols-6 lg:grid-cols-8 gap-4 sm:gap-6">
                                    {allCategories
                                        .filter((cat) =>
                                            (cat.category_name || cat.name || "")
                                                ?.toLowerCase()
                                                .includes(searchQuery.toLowerCase())
                                        )
                                        .map((cat) => {
                                            const isAll =
                                                cat._id === "all" ||
                                                cat?.category_name?.toLowerCase() === "all";

                                            const isSelected = isAll
                                                ? selectedCategoryId === null ||
                                                  selectedCategoryId === "all" ||
                                                  selectedCategoryId === cat._id
                                                : selectedCategoryId === cat._id ||
                                                  selectedCategoryId === cat.category_name;

                                            const imgSrc =
                                                isAll && (!cat?.category_image || cat.category_image.trim() === "")
                                                    ? "https://images.unsplash.com/photo-1542838132-92c53300491e?auto=format&fit=crop&w=300&q=80"
                                                    : getValidImage(cat?.category_image || cat?.image);

                                            return (
                                                <div
                                                    key={cat._id}
                                                    className="flex flex-col items-center cursor-pointer group select-none w-full py-1.5"
                                                    onClick={() => {
                                                        handleSelect(cat);
                                                        setShowModal(false);
                                                        setSearchQuery("");
                                                    }}
                                                >
                                                    <div
                                                        className={`w-18 h-18 sm:w-20 sm:h-20 rounded-full flex items-center justify-center transition-all duration-300 ${
                                                            isSelected
                                                                ? "p-[3px] border-2 border-primary shadow-md scale-105"
                                                                : "border border-gray-200 group-hover:border-primary/50 group-hover:scale-105"
                                                        }`}
                                                    >
                                                        <div className="w-full h-full rounded-full overflow-hidden">
                                                            <img
                                                                src={imgSrc}
                                                                alt={cat?.category_name || cat?.name}
                                                                className="w-full h-full object-cover"
                                                            />
                                                        </div>
                                                    </div>
                                                    <span
                                                        className={`text-xs sm:text-sm mt-2 font-medium transition-colors text-center line-clamp-1 w-full ${
                                                            isSelected
                                                                ? "text-primary font-bold"
                                                                : "text-gray-700 group-hover:text-primary"
                                                        }`}
                                                    >
                                                        {cat?.category_name || cat?.name}
                                                    </span>
                                                </div>
                                            );
                                        })}
                                </div>
                            )}
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
}
