import { FC, useMemo } from 'react'
import { Calendar } from 'iconsax-react'
import moment from 'moment-jalaali'
import Button from '@/components/Button'
import { useWorkspaces } from '@/pages/home/hooks/useHomeData'
import { workspaceItem } from '@/pages/home/types/HomeTypes'

const PlanRemaining: FC = () => {
    const getWorkspaces = useWorkspaces()

    const currentWorkspace = useMemo(() => {
        if (getWorkspaces.data?.data?.workspaces) {
            const workspaceId = localStorage.getItem(import.meta.env.VITE_WORKSPACE_ID)
            return getWorkspaces.data?.data?.workspaces.find((item: workspaceItem) => item.id === workspaceId)
        }
        return null
    }, [getWorkspaces.data])

    const remainingDays = useMemo(() => {
        if (currentWorkspace?.endDate) {
            const endDate = moment(currentWorkspace.endDate)
            const now = moment()
            const days = endDate.diff(now, 'days')
            return days > 0 ? days : 0
        }
        return null
    }, [currentWorkspace])

    if (!currentWorkspace || remainingDays === null) {
        return null
    }

    return (
        <div className='px-10 pb-5 mb-5 border-b border-[#ECEEF5]'>
            <div className='flex gap-2 items-center'>
                <Calendar size={20} color='#8C90A3' />
                <div className='text-xs text-description'>
                    زمان باقی‌مانده پلن
                </div>
            </div>
            <div className='mt-3 text-xs text-[#8C90A3]'>
                {remainingDays > 0 ? (
                    <span className='text-[#F59E0B] font-medium'>
                        {remainingDays} روز تا پایان پلن
                    </span>
                ) : (
                    <span className='text-red-500 font-medium'>
                        پلن شما منقضی شده است
                    </span>
                )}
            </div>
            {currentWorkspace.endDate && (
                <div className='mt-2 text-xs text-[#8C90A3]'>
                    تاریخ پایان: {moment(currentWorkspace.endDate).format('jYYYY/jMM/jDD')}
                </div>
            )}
            <div className='mt-4'>
                <Button
                    variant='primary'
                    label='تمدید پلن'
                    onClick={() => {
                        window.open(`${import.meta.env.VITE_CONSOLE_URL}/services/detail/${currentWorkspace?.plan?.service?.slug}?id=${currentWorkspace?.id}`, '_blank')
                    }}
                />
            </div>
        </div>
    )
}

export default PlanRemaining

