'use client'
import { FC, useState } from 'react'
import { ArrowLeft2 } from 'iconsax-react'
import { useRouter } from 'next/navigation'
import Image from 'next/image'
import { useGetCategories } from '@/share/hooks/useShareData'
import { Category } from '@/share/types/SharedTypes'

type Props = {
    isOpen: boolean
    onClose: () => void
}

const CategoryModal: FC<Props> = ({ isOpen, onClose }) => {
    const router = useRouter()
    const { data, isLoading } = useGetCategories()
    const [selectedMainCategory, setSelectedMainCategory] = useState<string | null>(null)
    const [expandedSubcategory, setExpandedSubcategory] = useState<string | null>(null)

    const parentCategories = data?.results?.data?.filter(cat => !cat.parent) || []

    const handleMainCategoryClick = (categoryId: string) => {
        setSelectedMainCategory(categoryId)
        setExpandedSubcategory(null)
    }

    const handleSubcategoryClick = (category: Category) => {
        if (category.children && category.children.length > 0) {
            setExpandedSubcategory(expandedSubcategory === category._id ? null : category._id)
        } else {
            router.push(`/products/${category.title_en}`)
            onClose()
        }
    }

    const handleCategoryNavigate = (category: Category) => {
        router.push(`/products/${category.title_en}`)
        onClose()
    }

    if (!isOpen) return null

    const currentMainCategoryData = selectedMainCategory
        ? parentCategories.find(cat => cat._id === selectedMainCategory)
        : parentCategories[0]

    const currentSubcategories = currentMainCategoryData?.children || []

    return (
        <div className="fixed top-[120px] left-0 right-0 bottom-0 bg-white z-40 md:hidden">
            <div className="flex h-full overflow-hidden">
                {/* Left Column - Main Categories */}
                <div className="w-28 bg-gray-100 overflow-y-auto">
                    {isLoading ? (
                        <div className="flex items-center justify-center h-40">
                            <div className="text-gray-500 text-xs">در حال بارگذاری...</div>
                        </div>
                    ) : (
                        <div className="p-2 space-y-2">
                            {parentCategories.map((category, index) => (
                                <div key={category._id}>
                                    <div
                                        className={`flex flex-col items-center text-center p-2 cursor-pointer rounded-lg transition-colors ${(selectedMainCategory || parentCategories[0]?._id) === category._id
                                            ? 'bg-white shadow-sm'
                                            : 'hover:bg-gray-200'
                                            }`}
                                        onClick={() => handleMainCategoryClick(category._id)}
                                    >
                                        <div className="w-12 h-12 bg-white rounded-full flex items-center justify-center mb-1 shadow-sm">
                                            {category.icon && category.icon.trim() !== '' && (category.icon.startsWith('http://') || category.icon.startsWith('https://') || category.icon.startsWith('/')) ? (
                                                <Image
                                                    src={category.icon}
                                                    alt={category.title_fa}
                                                    width={24}
                                                    height={24}
                                                    className="w-6 h-6 object-contain"
                                                />
                                            ) : (
                                                <span className="text-lg">📦</span>
                                            )}
                                        </div>
                                        <span className="text-xs text-gray-800 leading-tight text-center">
                                            {category.title_fa}
                                        </span>
                                    </div>
                                    {index < parentCategories.length - 1 && (
                                        <div className="border-b border-gray-200 mx-1" />
                                    )}
                                </div>
                            ))}
                        </div>
                    )}
                </div>

                {/* Right Column - Subcategories */}
                <div className="flex-1 bg-white overflow-y-auto">
                    <div className="px-4 py-4">
                        {isLoading ? (
                            <div className="flex items-center justify-center h-40">
                                <div className="text-gray-500">در حال بارگذاری...</div>
                            </div>
                        ) : (
                            <>
                                {/* Main Category Link */}
                                {currentMainCategoryData && (
                                    <div className="space-y-1 mb-4">
                                        <div
                                            className="py-3 cursor-pointer hover:bg-gray-50 transition-colors"
                                            onClick={() => handleCategoryNavigate(currentMainCategoryData)}
                                        >
                                            <span className="text-primary font-medium text-sm">
                                                همه محصولات {currentMainCategoryData.title_fa}
                                            </span>
                                        </div>
                                    </div>
                                )}

                                {/* Subcategories List */}
                                <div>
                                    {currentSubcategories.length > 0 ? (
                                        currentSubcategories.map((subcategory, index) => (
                                            <div key={subcategory._id}>
                                                <div
                                                    className="flex items-center justify-between py-3 cursor-pointer hover:bg-gray-50 transition-colors"
                                                    onClick={() => handleSubcategoryClick(subcategory)}
                                                >
                                                    <span className="text-gray-800 text-sm">{subcategory.title_fa}</span>
                                                    {subcategory.children && subcategory.children.length > 0 && (
                                                        <ArrowLeft2 size={16} color="#666" />
                                                    )}
                                                </div>

                                                {/* Expanded third level categories */}
                                                {expandedSubcategory === subcategory._id && subcategory.children && subcategory.children.length > 0 && (
                                                    <div className="mt-2 mb-4 p-4 bg-gray-50 rounded-lg">
                                                        <div
                                                            className="text-sm text-primary mb-3 font-medium cursor-pointer"
                                                            onClick={() => handleCategoryNavigate(subcategory)}
                                                        >
                                                            همه محصولات {subcategory.title_fa}
                                                        </div>
                                                        <div className="grid grid-cols-2 gap-4">
                                                            {subcategory.children.map((item) => (
                                                                <div
                                                                    key={item._id}
                                                                    className="flex flex-col items-center p-4 bg-white rounded-lg cursor-pointer hover:bg-gray-100 transition-colors"
                                                                    onClick={() => handleCategoryNavigate(item)}
                                                                >
                                                                    <div className="w-14 h-14 bg-white rounded-full flex items-center justify-center mb-3 border border-gray-200">
                                                                        {item.icon && item.icon.trim() !== '' && (item.icon.startsWith('http://') || item.icon.startsWith('https://') || item.icon.startsWith('/')) ? (
                                                                            <Image
                                                                                src={item.icon}
                                                                                alt={item.title_fa}
                                                                                width={28}
                                                                                height={28}
                                                                                className="w-7 h-7 object-contain"
                                                                            />
                                                                        ) : (
                                                                            <span className="text-xl">📦</span>
                                                                        )}
                                                                    </div>
                                                                    <span className="text-sm text-gray-800 text-center leading-tight font-medium">
                                                                        {item.title_fa}
                                                                    </span>
                                                                </div>
                                                            ))}
                                                        </div>
                                                    </div>
                                                )}

                                                {index < currentSubcategories.length - 1 && (
                                                    <div className="border-b border-gray-100" />
                                                )}
                                            </div>
                                        ))
                                    ) : (
                                        <div className="text-center text-gray-500 py-8">
                                            زیردسته‌ای یافت نشد
                                        </div>
                                    )}
                                </div>
                            </>
                        )}
                    </div>
                </div>
            </div>
        </div>
    )
}

export default CategoryModal