import { FC, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useGetRestaurants } 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 { Copy, Edit } from 'iconsax-react'
import { toast } from 'react-toastify'
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'

const RestaurantsList: FC = () => {

    const { t } = useTranslation('global')
    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 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 handleCopyAddress = async (address: string | null) => {
        if (!address) return

        try {
            await navigator.clipboard.writeText(address)
            toast.success('کپی شد')
        } catch {
            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.address')} />
                                    <Td text={t('restaurant.domain')} />
                                    <Td text={t('restaurant.plan')} />
                                    <Td text={t('restaurant.status')} />
                                    <Td text={t('restaurant.created_at')} />
                                    <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={''}>
                                                    <div className='flex items-center gap-2'>
                                                        <span>{item.address || '-'}</span>
                                                        {item.address && (
                                                            <Copy
                                                                size={18}
                                                                color='#8C90A3'
                                                                className='cursor-pointer hover:text-primary transition-colors'
                                                                onClick={() => handleCopyAddress(item.address)}
                                                            />
                                                        )}
                                                    </div>
                                                </Td>
                                                <Td text={item.domain || '-'} />
                                                <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'>
                                                        {moment(item.createdAt).format('jYYYY-jMM-jDD HH:mm')}
                                                    </div>
                                                </Td>
                                                <Td text={''}>
                                                    <div className='flex items-center gap-4'>
                                                        <Link
                                                            to={Pages.dmenu.restaurants.update + item.id}
                                                        >
                                                            <Edit
                                                                size={18}
                                                                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