import { type FC, useState } from 'react'
import { useGetProducts } from './hooks/useProductData';
import { type ProductListType } from './types/Types';
import { ProductStatus } from './enum/ProductEnum';
import PageLoading from '../../components/PageLoading';
import Error from '../../components/Error';
import PaginationUi from '../../components/PaginationUi';
import StatusWithText from '../../components/StatusWithText';
import Td from '../../components/Td';
import TrashWithConfrim from '../../components/TrashWithConfrim';
import { Edit } from 'iconsax-react';
import Button from '@/components/Button';
import { Link } from 'react-router-dom';
import { Pages } from '@/config/Pages';
import { useNavigate } from 'react-router-dom';

const List: FC = () => {

    const navigate = useNavigate();
    const [currentPage, setCurrentPage] = useState(1);
    const { data: productsData, isLoading, error } = useGetProducts(currentPage);

    if (isLoading) {
        return (
            <div className="flex justify-center items-center min-h-[400px]">
                <PageLoading />
            </div>
        );
    }

    if (error) {
        return (
            <div className="flex justify-center items-center min-h-[400px]">
                <Error errorText="خطا در بارگذاری محصولات" />
            </div>
        );
    }

    const products = productsData?.results?.products || [];
    const pager = productsData?.results?.pager;

    const getStatusVariant = (status: ProductStatus) => {
        switch (status) {
            case ProductStatus.Approved: return 'success';
            case ProductStatus.Rejected: return 'error';
            case ProductStatus.Pending: return 'warning';
            case ProductStatus.Draft: return 'warning';
            default: return 'warning';
        }
    };

    const getStatusText = (status: ProductStatus) => {
        switch (status) {
            case ProductStatus.Approved: return 'تایید شده';
            case ProductStatus.Rejected: return 'رد شده';
            case ProductStatus.Pending: return 'در انتظار';
            case ProductStatus.Draft: return 'پیش‌نویس';
            default: return status;
        }
    };


    return (
        <div>
            <div className='flex justify-end mt-5'>
                <Button
                    label='افزودن محصول'
                    onClick={() => navigate(`${Pages.products.create}`)}
                    className='w-fit'
                />
            </div>
            <div className='relative overflow-x-auto rounded-3xl mt-5 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={'موجودی'} />
                            <Td text={'عملیات'} />
                        </tr>
                    </thead>
                    <tbody>
                        {products.length === 0 ? (
                            <tr className='tr'>
                                <td colSpan={8} className="text-center py-8 text-gray-500">
                                    هیچ محصولی یافت نشد
                                </td>
                            </tr>
                        ) : (
                            products.map((product: ProductListType) => (
                                <tr key={product._id} className='tr'>
                                    <Td text="">
                                        <div className="w-12 h-12 rounded-lg overflow-hidden">
                                            <img
                                                src={product.imagesUrl?.cover || '/placeholder-image.png'}
                                                alt={product.title_fa}
                                                className="w-full h-full object-cover"
                                            />
                                        </div>
                                    </Td>
                                    <Td text="">
                                        <div>
                                            <div className="font-medium text-gray-900">
                                                {product.title_fa}
                                            </div>
                                            <div className="text-gray-500 text-xs">
                                                {product.title_en}
                                            </div>
                                        </div>
                                    </Td>
                                    <Td text={product.brand_title_fa} />
                                    <Td text={product.category_title_fa} />
                                    <Td text=''>
                                        <Link
                                            to={`${Pages.products.variants}${product._id}`}
                                        >
                                            <Button
                                                className='h-8 text-xs'
                                            >
                                                مدیریت تنوع
                                            </Button>
                                        </Link>
                                    </Td>
                                    <Td text="">
                                        <StatusWithText
                                            variant={getStatusVariant(product.status)}
                                            text={getStatusText(product.status)}
                                        />
                                    </Td>
                                    <Td text={`${product.default_variant?.price?.selling_price?.toLocaleString('fa-IR') || 0} تومان`} />
                                    <Td text={String(product.default_variant?.stock || 0)} />
                                    <Td text="">
                                        <div className="flex items-center gap-2">
                                            {product.status === ProductStatus.Draft && (
                                                <Link to={`${Pages.products.update}${product._id}`}>
                                                    <Edit color='#8C90A3' size={16} className="cursor-pointer hover:text-blue-500" />
                                                </Link>
                                            )}

                                            <TrashWithConfrim
                                                onDelete={() => {
                                                    // TODO: Implement delete product
                                                    console.log('Delete product:', product._id);
                                                }}
                                            />
                                        </div>
                                    </Td>
                                </tr>
                            ))
                        )}
                    </tbody>
                </table>
            </div>

            <PaginationUi
                pager={pager}
                onPageChange={(page) => {
                    setCurrentPage(page);
                }}
            />
        </div>
    )
}

export default List