import { FC, useState } from 'react'
import { useTranslation } from 'react-i18next'
import Input from '../../components/Input'
import Button from '../../components/Button'
import SwitchComponent from '../../components/Switch'
import { TickCircle, Link2 } from 'iconsax-react'
import DatePickerComponent from '../../components/DatePicker'
import { useFormik } from 'formik'
import { AdsDisplayLocation, CreateAdsType } from './types/AdsTypes'
import * as Yup from 'yup'
import UploadBoxDraggble from '../../components/UploadBoxDraggble'
import CheckBoxComponent from '../../components/CheckBoxComponent'
import { useSingleUpload } from '../service/hooks/useServiceData'
import { useCreateAds } from './hooks/useAdsData'
import { ErrorType } from '../../helpers/types'
import { toast } from 'react-toastify'
import { clx } from '../../helpers/utils'
import { useNavigate } from 'react-router-dom'
import { Pages } from '../../config/Pages'
import moment from 'moment-jalaali'

const CreateAd: FC = () => {

    const navigate = useNavigate()
    const { t } = useTranslation('global')
    const [file, setFile] = useState<File>()
    const singleUpload = useSingleUpload()
    const createAds = useCreateAds()

    const formik = useFormik<CreateAdsType>({
        initialValues: {
            displayLocation: '',
            endDate: '',
            imageUrl: '',
            isActive: true,
            link: '',
            serviceId: undefined,
            startDate: '',
            title: ''
        },
        validationSchema: Yup.object().shape({
            title: Yup.string().required(t('errors.required')),
            displayLocation: Yup.string().required(t('errors.required')),
            endDate: Yup.string().required(t('errors.required')),
            link: Yup.string().required(t('errors.required')),
            startDate: Yup.string().required(t('errors.required'))
        }),
        onSubmit: async (values) => {
            if (file) {
                const formData = new FormData()
                formData.append('file', file)
                await singleUpload.mutateAsync(formData, {
                    onSuccess: (data) => {
                        values.imageUrl = data?.data?.url
                    },
                    onError: (error: ErrorType) => {
                        toast.error(error.response?.data?.error?.message[0])
                    }
                })

                createAds.mutate(values, {
                    onSuccess: () => {
                        toast.success(t('success'))
                        navigate(Pages.ads.list)
                    },
                    onError: (error: ErrorType) => {
                        toast.error(error.response?.data?.error?.message[0])
                    }
                })
            } else {
                toast.error(t('ads.file_error'))
            }
        }
    })

    return (
        <div className='mt-4'>
            <div className='flex justify-between items-center'>
                <div>
                    {t('ads.new_ads')}
                </div>
                <Button
                    className='w-[172px]'
                    onClick={() => formik.handleSubmit()}
                    isLoading={createAds.isPending || singleUpload.isPending}
                >
                    <div className='flex gap-2 items-center'>
                        <TickCircle size={20} color='white' />
                        <div>
                            {t('ads.submit')}
                        </div>
                    </div>
                </Button>
            </div>
            <div className='flex flex-col-reverse xl:flex-row gap-6 xl:mt-8 mt-4'>
                <div className='flex-1 min-h-[calc(100vh-201px)] bg-white py-8 xl:px-10 px-4 rounded-3xl'>
                    <div className='mt-6'>
                        <Input
                            label={t('ads.title')}
                            placeholder={t('ads.enter_your_title')}
                            {...formik.getFieldProps('title')}
                            error_text={formik.touched.title && formik.errors.title ? formik.errors.title : ''}
                        />
                    </div>
                    <div className='mt-6 rowTwoInput'>
                        <DatePickerComponent
                            label={t('ads.startDate')}
                            onChange={(value) => formik.setFieldValue('startDate', moment(value, 'jYYYY-jMM-jDD').format('YYYY-MM-DD'))}
                            placeholder=''
                            error_text={formik.touched.startDate && formik.errors.startDate ? formik.errors.startDate : ''}
                        />
                        <DatePickerComponent
                            label={t('ads.endDate')}
                            onChange={(value) => formik.setFieldValue('endDate', moment(value, 'jYYYY-jMM-jDD').format('YYYY-MM-DD'))}
                            placeholder=''
                            error_text={formik.touched.endDate && formik.errors.endDate ? formik.errors.endDate : ''}
                        />
                    </div>
                    <div className='mt-6 relative'>
                        <Input
                            label={t('ads.link')}
                            placeholder={t('ads.enter_your_link')}
                            {...formik.getFieldProps('link')}
                            error_text={formik.touched.link && formik.errors.link ? formik.errors.link : ''}
                        />
                        <Link2 size={20} color='blue' className={clx(
                            'absolute left-4 bottom-[10px] cursor-pointer',
                            formik.touched.link && formik.errors.link ? 'bottom-[31px]' : ''
                        )} />
                    </div>
                </div>
                <div className='min-h-[calc(100vh-201px)] bg-white w-full xl:w-sidebar  py-10 px-5 h-fit rounded-3xl'>
                    <div className='text-sm flex items-center justify-between'>
                        <p>
                            وضعیت تبلیغ
                        </p>
                        <div className='flex gap-1 text-xs items-center text-description'>
                            <div>
                                {t('ads.deactive')}
                            </div>
                            <SwitchComponent
                                active={formik.values.isActive}
                                onChange={(value) => formik.setFieldValue('isActive', value)}
                            />
                        </div>
                    </div>
                    <p className='mt-6 text-sm'>{t('ads.location')}</p>

                    <div className='p-2 border border-[##D0D0D0] rounded-lg mt-1'>

                        {Object.values(AdsDisplayLocation).map((location) => (
                            <div className='flex items-center py-2' key={location}>
                                <div>
                                    <CheckBoxComponent
                                        checked={formik.values.displayLocation === location}
                                        onChange={() => formik.setFieldValue('displayLocation', location)}
                                    />
                                </div>
                                <div className='text-description text-xs leading-5'>
                                    {t(`ads.${location}`)}
                                </div>
                            </div>
                        ))}


                    </div>
                    <div className='mt-8'>
                        <UploadBoxDraggble
                            label={t('ads.upload_picture')}
                            onChange={(value) => setFile(value[0])}
                        />
                    </div>
                </div>
            </div>

        </div>
    )
}

export default CreateAd