import { FC, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useGetShops, useHardDeleteShop } from '../hooks/useIconData'
import PageLoading from '../../../components/PageLoading'
import Td from '../../../components/Td'
import { ShopType, ShopsResponse } from '../types/Types'
import moment from 'moment-jalaali'
import { Edit } from 'iconsax-react'
import { toast } from '../../../components/Toast';
import Button from '../../../components/Button'
import ShopAdminsModal from './components/ShopAdminsModal'
import Pagination from '../../../components/Pagination'
import { Link } from 'react-router-dom'
import { Pages } from '../../../config/Pages'
import TrashWithConfrim from '../../../components/TrashWithConfrim'
import { useQueryClient } from '@tanstack/react-query'

const ShopsList: FC = () => {

    const { t } = useTranslation('global')
    const queryClient = useQueryClient()
    const [page, setPage] = useState<number>(1)
    const limit = 10
    const { data: shops, isLoading } = useGetShops(page, limit)
    const [selectedShopId, setSelectedShopId] = useState<string>('')
    const [isAdminsModalOpen, setIsAdminsModalOpen] = useState<boolean>(false)
    const deleteShop = useHardDeleteShop()

    const shopsList = (shops as ShopsResponse | undefined)?.data?.shops || []
    const totalPages = (shops as ShopsResponse | undefined)?.data?.pager?.totalPages || 1

    const handleOpenAdminsModal = (shopId: string) => {
        setSelectedShopId(shopId)
        setIsAdminsModalOpen(true)
    }

    const handleCloseAdminsModal = () => {
        setIsAdminsModalOpen(false)
        setSelectedShopId('')
    }

    const calculateDaysRemaining = (endDate: string): string => {
        const end = moment(endDate)
        const now = moment()
        const diff = end.diff(now, 'days')
        if (diff < 0) {
            return 'منقضی شده'
        }
        return `${diff} روز`
    }

    const formatJalaliDate = (date: string): string => {
        return moment(date).format('jYYYY-jMM-jDD')
    }

    const handleDeleteShop = (shopId: string) => {
        deleteShop.mutate(shopId, {
            onSuccess: () => {
                toast('فروشگاه با موفقیت حذف شد', 'success')
                queryClient.invalidateQueries({ queryKey: ['shops'] })
            },
            onError: () => {
                toast('خطا در حذف فروشگاه', 'error')
            }
        })
    }

    return (
        <div className='mt-4'>
            <div className='flex w-full justify-between items-center'>
                <div>
                    {t('shop.list_shop')}
                </div>
            </div>

            {
                isLoading ?
                    <PageLoading />
                    :
                    <div className='relative overflow-x-auto rounded-3xl mt-9 w-full'>
                        <table className='w-full text-sm '>
                            <thead className='thead'>
                                <tr>
                                    <Td text={t('shop.name')} />
                                    <Td text={t('shop.phone')} />
                                    <Td text={t('shop.slug')} />
                                    <Td text={t('shop.plan')} />
                                    <Td text={t('shop.status')} />
                                    <Td text={t('shop.subscription_start_date')} />
                                    <Td text={t('shop.subscription_end_date')} />
                                    <Td text={t('shop.days_remaining')} />
                                    <Td text={''} />
                                </tr>
                            </thead>
                            <tbody>
                                {
                                    shopsList.map((item: ShopType) => {
                                        return (
                                            <tr key={item.id} className='tr'>
                                                <Td text={item.name} />
                                                <Td text={item.phone || '-'} />
                                                <Td text={item?.slug || '-'} />
                                                <Td text={item.plan || '-'} />
                                                <Td text={''}>
                                                    <div className={`w-fit px-3 py-1 rounded-2xl text-xs ${item.isActive
                                                        ? 'bg-green-100 text-green-700'
                                                        : 'bg-red-100 text-red-700'
                                                        }`}>
                                                        {item.isActive ? t('shop.active') : t('shop.inactive')}
                                                    </div>
                                                </Td>
                                                <Td text={''}>
                                                    <div className='dltr text-right'>
                                                        {formatJalaliDate(item.subscriptionStartDate)}
                                                    </div>
                                                </Td>
                                                <Td text={''}>
                                                    <div className='dltr text-right'>
                                                        {formatJalaliDate(item.subscriptionEndDate)}
                                                    </div>
                                                </Td>
                                                <Td text={''}>
                                                    <div className='dltr text-right'>
                                                        {calculateDaysRemaining(item.subscriptionEndDate)}
                                                    </div>
                                                </Td>
                                                <Td text={''}>
                                                    <div className='flex items-center gap-4'>
                                                        <TrashWithConfrim
                                                            onDelete={() => handleDeleteShop(item.id)}
                                                            isLoading={deleteShop.isPending}
                                                        />
                                                        <Link
                                                            to={Pages.dkala.shops.update + item.id}
                                                        >
                                                            <Edit
                                                                size={20}
                                                                color='#8C90A3'
                                                            />
                                                        </Link>
                                                        <Button
                                                            className='w-fit px-4'
                                                            onClick={() => handleOpenAdminsModal(item.id)}
                                                        >
                                                            {t('shop.admins')}
                                                        </Button>
                                                    </div>
                                                </Td>
                                            </tr>
                                        )
                                    })
                                }
                            </tbody>
                        </table>

                        {totalPages > 1 && (
                            <Pagination
                                currentPage={page}
                                totalPages={totalPages}
                                onPageChange={setPage}
                            />
                        )}
                    </div>
            }

            <ShopAdminsModal
                open={isAdminsModalOpen}
                close={handleCloseAdminsModal}
                shopId={selectedShopId}
            />
        </div>
    )
}

export default ShopsList
