import { type FC, type JSX, useState } from 'react'
import Td from '../../components/Td'
import { ArrowDown2, ArrowLeft2, Edit, Lock } from 'iconsax-react'
import { Link } from 'react-router-dom'
import { useGetCategories, useDeleteCategory } from './hooks/useCategoryData'
import { type CategoryTreeNode } from './types/Types'
import { Pages } from '../../config/Pages'
import Button from '../../components/Button'
import TrashWithConfrim from '../../components/TrashWithConfrim'

const CategoryList: FC = () => {

    const { data, isLoading, refetch } = useGetCategories();
    const deleteCategoryMutation = useDeleteCategory();
    const [expandedCategories, setExpandedCategories] = useState<Set<string>>(new Set());

    const handleDeleteCategory = async (categoryId: string) => {
        await deleteCategoryMutation.mutateAsync(categoryId);
        refetch()
    };

    const toggleExpanded = (categoryId: string) => {
        setExpandedCategories(prev => {
            const newSet = new Set(prev);
            if (newSet.has(categoryId)) {
                newSet.delete(categoryId);
            } else {
                newSet.add(categoryId);
            }
            return newSet;
        });
    };

    const renderCategoryRow = (category: CategoryTreeNode, level: number = 0) => {
        return (
            <tr key={category._id} className='tr'>
                <Td text="">
                    <div className="flex items-center gap-2">
                        <div className="w-8 h-8 rounded-full overflow-hidden">
                            <img
                                src={category.icon}
                                alt={category.title_fa}
                                className="w-full h-full object-cover"
                            />
                        </div>
                    </div>
                </Td>
                <Td text="">
                    <div className="flex items-center gap-2">
                        <span style={{ marginLeft: `${level * 20}px` }}>
                            {category.title_fa}
                        </span>
                    </div>
                </Td>
                <Td text={category.title_en} />
                <Td text="">
                    <div className="w-12 h-12 rounded-lg overflow-hidden">
                        <img
                            src={category.imageUrl}
                            alt={category.title_fa}
                            className="w-full h-full object-cover"
                        />
                    </div>
                </Td>
                <Td text={category.description} />
                <Td text=''>
                    {category.leaf ? <Link to={`${Pages.category.variant}${category._id}`}>
                        <Button className='h-7 text-xs w-fit px-4' label='افزودن تنوع' />
                    </Link> : <Lock size={20} color='#8C90A3' />}
                </Td>
                <Td text="">
                    <div className="flex items-center gap-2">
                        {category.leaf ? <Link to={`${Pages.category.attributes}${category._id}`}>
                            <Button className='h-7 text-xs w-fit px-4' label='ویژگی‌ها' variant='outline' />
                        </Link> : <Lock size={20} color='#8C90A3' />}
                    </div>
                </Td>
                <Td text="">
                    <div className="flex items-center gap-2">
                        <Link to={`${Pages.category.update}${category._id}`} state={{ from: 'list' }}>
                            <Edit size={20} color='#8C90A3' />
                        </Link>
                        <TrashWithConfrim
                            onDelete={() => handleDeleteCategory(category._id)}
                            isLoading={deleteCategoryMutation.isPending}
                        />
                        {category.children && category.children.length > 0 && (
                            <button
                                onClick={() => toggleExpanded(category._id)}
                                className="flex items-center justify-center w-6 h-6 hover:bg-gray-100 rounded transition-colors"
                            >
                                {expandedCategories.has(category._id) ? (
                                    <ArrowDown2 size={16} color="#6B7280" />
                                ) : (
                                    <ArrowLeft2 size={16} color="#6B7280" />
                                )}
                            </button>
                        )}
                    </div>
                </Td>
            </tr>
        );
    };

    const renderCategories = (categories: CategoryTreeNode[], level: number = 0): JSX.Element[] => {
        const result: JSX.Element[] = [];

        categories.forEach(category => {
            // اضافه کردن خود دسته‌بندی
            result.push(renderCategoryRow(category, level));

            // اگر دسته‌بندی expand شده باشد، فرزندانش را به صورت بازگشتی اضافه کن
            if (expandedCategories.has(category._id) && category.children && category.children.length > 0) {
                result.push(...renderCategories(category.children, level + 1));
            }
        });

        return result;
    };

    if (isLoading) {
        return <div className="flex justify-center items-center h-64">در حال بارگذاری...</div>;
    }

    return (
        <div>
            <div className='relative overflow-x-auto rounded-3xl mt-9 w-full'>
                <table className='w-full text-sm '>
                    <thead className='thead'>
                        <tr>
                            <Td text={'آیکون'} />
                            <Td text={'عنوان فارسی'} />
                            <Td text={'عنوان انگلیسی'} />
                            <Td text={'تصویر'} />
                            <Td text={'توضیحات'} />
                            <Td text={'تنوع'} />
                            <Td text={'ویژگی‌ها'} />
                            <Td text={'عملیات'} />
                        </tr>
                    </thead>
                    <tbody>
                        {data?.results?.data ? renderCategories(data.results.data, 0) : null}
                    </tbody>
                </table>
            </div>
        </div>
    )
}

export default CategoryList