import { FC, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useDeleteSubscription, useGetUserSubscriptions } from './hooks/useSucscriptionData'
import PageLoading from '../../components/PageLoading'
import Td from '../../components/Td'
import Pagination from '../../components/Pagination'
import { UserSubscriptionsResponse, UserSubscription } from './types/SubscriptionTypes'
import moment from 'moment-jalaali'
import Select from '../../components/Select'
import Input from '../../components/Input'
import { useGetAllServices } from '../service/hooks/useServiceData'
import { ServiceItemType } from '../service/types/ServiceTypes'
import TrashWithConfrim from '../../components/TrashWithConfrim'
import { ErrorType } from '../../helpers/types'
import { toast } from '../../components/Toast';

const SubscriptionsList: FC = () => {

    const { t } = useTranslation('global')
    const [page, setPage] = useState<number>(1)
    const [status, setStatus] = useState<string>('')
    const [serviceId, setServiceId] = useState<string>('')
    const [search, setSearch] = useState<string>('')

    const { data: subscriptionsResponse, isLoading, refetch } = useGetUserSubscriptions(page, status, serviceId, search)
    const getServices = useGetAllServices('', 1, '', '', false, 50)
    const { mutate: deleteSubscription, isPending } = useDeleteSubscription()

    const subscriptionsData = (subscriptionsResponse as UserSubscriptionsResponse | undefined)?.data
    const subscriptionsList = subscriptionsData?.userSubscriptions || []
    const totalPages = subscriptionsData?.pager?.totalPages || 1

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

    const calculateDaysRemaining = (endDate: string): string => {
        const end = moment(endDate)
        const now = moment()
        const diff = end.diff(now, 'days')
        if (diff < 0) {
            return t('subscription.expired')
        }
        return `${diff} ${t('subscription.days')}`
    }

    const getStatusBadgeClass = (status: string): string => {
        switch (status) {
            case 'ACTIVE':
                return 'bg-green-100 text-green-700'
            case 'EXPIRED':
                return 'bg-red-100 text-red-700'
            case 'CANCELLED':
            case 'CANCELED':
                return 'bg-gray-100 text-gray-700'
            case 'INACTIVE':
                return 'bg-yellow-100 text-yellow-700'
            default:
                return 'bg-blue-100 text-blue-700'
        }
    }

    const getStatusText = (status: string): string => {
        switch (status) {
            case 'ACTIVE':
                return t('subscription.active')
            case 'EXPIRED':
                return t('subscription.expired')
            case 'CANCELLED':
            case 'CANCELED':
                return t('subscription.cancelled')
            case 'INACTIVE':
                return t('subscription.inactive')
            default:
                return status
        }
    }

    const handleDelete = (id: string) => {
        deleteSubscription(id, {
            onSuccess: () => {
                refetch()
            },
            onError: (error: ErrorType) => {
                toast(error.response?.data?.error.message[0], 'error')
            }
        })
    }

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

            <div className='flex justify-between items-center mt-12 gap-4'>
                <div className='flex gap-4'>
                    <Select
                        className='w-36'
                        items={[
                            { label: t('all'), value: '' },
                            { label: t('subscription.active'), value: 'ACTIVE' },
                            { label: t('subscription.inactive'), value: 'INACTIVE' },
                            { label: t('subscription.cancelled'), value: 'CANCELED' },
                        ]}
                        placeholder={t('status')}
                        value={status}
                        onChange={(e) => {
                            setStatus(e.target.value)
                            setPage(1)
                        }}
                    />
                    <Select
                        className='w-48'
                        items={
                            getServices.data?.data?.services?.map((item: ServiceItemType) => ({
                                label: item.name,
                                value: item.id,
                            })) || []
                        }
                        placeholder={t('subscription.service')}
                        value={serviceId}
                        onChange={(e) => {
                            setServiceId(e.target.value)
                            setPage(1)
                        }}
                    />
                </div>
                <div className='w-64'>
                    <Input
                        variant='search'
                        placeholder={t('header.search')}
                        value={search}
                        className='bg-white'
                        // onChange={(e) => setSearch(e.target.value)}
                        onChangeSearchFinal={(value) => {
                            if (value !== search) {
                                setSearch(value)
                                setPage(1)
                            }
                        }}
                    />
                </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('subscription.id')} />
                                <Td text={t('auth.name')} />
                                <Td text={t('auth.family')} />
                                <Td text={t('auth.phonen_number')} />
                                <Td text='نام کسب‌وکار' />
                                <Td text='تلفن کسب‌وکار' />
                                <Td text={t('subscription.service')} />
                                <Td text={t('subscription.plan')} />
                                <Td text={t('subscription.subscription_start_date')} />
                                <Td text={t('subscription.subscription_end_date')} />
                                <Td text={t('subscription.days_remaining')} />
                                <Td text={t('status')} />
                                <Td text={''} />
                            </tr>
                        </thead>
                        <tbody>
                            {subscriptionsList.map((item: UserSubscription) => (
                                <tr key={item.id} className='tr'>
                                    <Td text={item.id} />
                                    <Td text={item.user.firstName || '-'} />
                                    <Td text={item.user.lastName || '-'} />
                                    <Td text={item.user.phone || '-'} />
                                    <Td text={item.businessName || '-'} />
                                    <Td text={item.businessPhone || '-'} />
                                    <Td text={item.plan.service?.name || item.plan.service?.title || '-'} />
                                    <Td text={item.plan.name || '-'} />
                                    <Td text=''>
                                        <div className='dltr text-right'>
                                            {formatJalaliDate(item.startDate)}
                                        </div>
                                    </Td>
                                    <Td text=''>
                                        <div className='dltr text-right'>
                                            {formatJalaliDate(item.endDate)}
                                        </div>
                                    </Td>
                                    <Td text=''>
                                        <div className='dltr text-right'>
                                            {calculateDaysRemaining(item.endDate)}
                                        </div>
                                    </Td>
                                    <Td text=''>
                                        <div className={`w-fit px-3 py-1 rounded-2xl text-xs ${getStatusBadgeClass(item.status)}`}>
                                            {getStatusText(item.status)}
                                        </div>
                                    </Td>
                                    <Td text=''>
                                        <TrashWithConfrim
                                            onDelete={() => handleDelete(item.id)}
                                            isLoading={isPending}
                                        />
                                    </Td>
                                </tr>
                            ))}
                        </tbody>
                    </table>

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

export default SubscriptionsList