import { FC, useState } from 'react'
import { useTranslation } from 'react-i18next'
import Button from '../../../../components/Button'
import DefaulModal from '../../../../components/DefaulModal'
import UploadBox from '../../../../components/UploadBox'
import Select from '../../../../components/Select'
import { useFormik } from 'formik'
import * as Yup from 'yup'
import { toast } from '../../../../components/Toast';
import { TickCircle } from 'iconsax-react'
import { useCreateSticker, useGetGroupStickers } from '../../hooks/useStickerData'
import { useSingleUpload } from '../../../service/hooks/useServiceData'
import { CreateStickerType, GroupStickerType } from '../../types/Types'
import { ErrorType } from '../../../../helpers/types'

interface CreateStickerProps {
    open: boolean
    close: () => void
    onSuccess?: () => void
}

const CreateSticker: FC<CreateStickerProps> = ({ open, close, onSuccess }) => {
    const { t } = useTranslation('global')
    const [file, setFile] = useState<File>()
    const createSticker = useCreateSticker()
    const singleUpload = useSingleUpload()
    const { data: groupStickers } = useGetGroupStickers()

    const groups = (groupStickers as unknown as { data?: GroupStickerType[] })?.data || []
    const groupOptions = groups.map((group: GroupStickerType) => ({
        value: group.id,
        label: group.name
    }))

    const handleCreateSticker = (values: CreateStickerType) => {
        createSticker.mutate(values, {
            onSuccess: () => {
                formik.resetForm()
                setFile(undefined)
                close()
                toast(t('success'), 'success')
                onSuccess?.()
            },
            onError: (error: ErrorType) => {
                toast(error.response?.data?.error?.message[0], 'error')
            }
        })
    }

    const formik = useFormik<CreateStickerType>({
        initialValues: {
            url: '',
            groupId: ''
        },
        validationSchema: Yup.object({
            groupId: Yup.string()
                .required(t('errors.required'))
        }),
        onSubmit: async (values) => {
            if (!file) {
                toast(t('errors.required'), 'error')
                return
            }
            const formData = new FormData()
            formData.append('file', file)
            await singleUpload.mutateAsync(formData, {
                onSuccess: (data) => {
                    values.url = data?.data?.url
                    handleCreateSticker(values)
                },
                onError: (error: ErrorType) => {
                    toast(error.response?.data?.error?.message[0], 'error')
                }
            })
        }
    })

    const handleClose = () => {
        formik.resetForm()
        setFile(undefined)
        close()
    }

    return (
        <DefaulModal
            open={open}
            close={handleClose}
            title_header={t('sticker.add_new_sticker')}
            isHeader
        >
            <div className='mt-6'>
                <UploadBox
                    label={t('sticker.url')}
                    onChange={(files) => setFile(files[0])}
                    isReset={!open}
                    accept="image/svg+xml"
                />

                <div className='mt-4'>
                    <Select
                        label={t('sticker.group')}
                        className='bg-white bg-opacity-30'
                        items={groupOptions}
                        placeholder={t('sticker.select_group')}
                        {...formik.getFieldProps('groupId')}
                        error_text={formik.touched.groupId && formik.errors.groupId ? formik.errors.groupId : ''}
                    />
                </div>

                <div className='mt-12 border-t border-border pt-5 flex justify-end'>
                    <div className='flex gap-5 items-center'>
                        <Button
                            className='w-[150px] bg-white bg-opacity-15 text-description'
                            label={t('cancel')}
                            onClick={handleClose}
                        />

                        <Button
                            onClick={() => formik.handleSubmit()}
                            isLoading={createSticker.isPending || singleUpload.isPending}
                        >
                            <div className='flex gap-2'>
                                <TickCircle
                                    size={20}
                                    color='white'
                                />
                                <div>
                                    {t('submit')}
                                </div>
                            </div>
                        </Button>
                    </div>
                </div>
            </div>
        </DefaulModal>
    )
}

export default CreateSticker
