import { FC, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useGetRestaurants, useHardDeleteRestaurant } from '../hooks/useIconData'
import PageLoading from '../../../components/PageLoading'
import Td from '../../../components/Td'
import { RestaurantType, RestaurantsResponse } from '../types/Types'
import moment from 'moment-jalaali'
import { Edit } from 'iconsax-react'
import { toast } from '../../../components/Toast';
import Button from '../../../components/Button'
import RestaurantAdminsModal from './components/RestaurantAdminsModal'
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 RestaurantsList: FC = () => {

    const { t } = useTranslation('global')
    const queryClient = useQueryClient()
    const [page, setPage] = useState<number>(1)
    const limit = 10
    const { data: restaurants, isLoading } = useGetRestaurants(page, limit)
    const [selectedRestaurantId, setSelectedRestaurantId] = useState<string>('')
    const [isAdminsModalOpen, setIsAdminsModalOpen] = useState<boolean>(false)
    const deleteRestaurant = useHardDeleteRestaurant()

    const restaurantsList = (restaurants as RestaurantsResponse | undefined)?.data?.restaurants || []
    const totalPages = (restaurants as RestaurantsResponse | undefined)?.data?.pager?.totalPages || 1

    const handleOpenAdminsModal = (restaurantId: string) => {
        setSelectedRestaurantId(restaurantId)
        setIsAdminsModalOpen(true)
    }

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

    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 handleDeleteRestaurant = (restaurantId: string) => {
        deleteRestaurant.mutate(restaurantId, {
            onSuccess: () => {
                toast('رستوران با موفقیت حذف شد', 'success')
                queryClient.invalidateQueries({ queryKey: ['restaurants'] })
            },
            onError: () => {
                toast('خطا در حذف رستوران', 'error')
            }
        })
    }

    return (
        <div className='mt-4'>
            <div className='flex w-full justify-between items-center'>
                <div>
                    {t('restaurant.list_restaurant')}
                </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('restaurant.name')} />
                                    <Td text={t('restaurant.phone')} />
                                    <Td text={t('restaurant.slug')} />
                                    <Td text={t('restaurant.plan')} />
                                    <Td text={t('restaurant.status')} />
                                    <Td text={t('restaurant.subscription_start_date')} />
                                    <Td text={t('restaurant.subscription_end_date')} />
                                    <Td text={t('restaurant.days_remaining')} />
                                    <Td text={''} />
                                </tr>
                            </thead>
                            <tbody>
                                {
                                    restaurantsList.map((item: RestaurantType) => {
                                        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('restaurant.active') : t('restaurant.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={() => handleDeleteRestaurant(item.id)}
                                                            isLoading={deleteRestaurant.isPending}
                                                        />
                                                        <Link
                                                            to={Pages.dmenu.restaurants.update + item.id}
                                                        >
                                                            <Edit
                                                                size={20}
                                                                color='#8C90A3'
                                                            />
                                                        </Link>
                                                        <Button
                                                            className='w-fit px-4'
                                                            onClick={() => handleOpenAdminsModal(item.id)}
                                                        >
                                                            {t('restaurant.admins')}
                                                        </Button>
                                                    </div>
                                                </Td>
                                            </tr>
                                        )
                                    })
                                }
                            </tbody>
                        </table>

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

            <RestaurantAdminsModal
                open={isAdminsModalOpen}
                close={handleCloseAdminsModal}
                restaurantId={selectedRestaurantId}
            />
        </div>
    )
}

export default RestaurantsList