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 { useCreateIcon, useGetGroupIcons } from '../../hooks/useIconData'
import { useMultiUpload } from '../../../service/hooks/useServiceData'
import { CreateIconType, GroupIconType } from '../../types/Types'
import { ErrorType } from '../../../../helpers/types'

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

const CreateIcon: FC<CreateIconProps> = ({ open, close, onSuccess }) => {
    const { t } = useTranslation('global')
    const [files, setFiles] = useState<File[]>([])
    const [isSubmitting, setIsSubmitting] = useState(false)
    const createIcon = useCreateIcon()
    const multiUpload = useMultiUpload()
    const { data: groupIcons } = useGetGroupIcons()

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

    const formik = useFormik<CreateIconType>({
        initialValues: {
            url: '',
            groupId: ''
        },
        validationSchema: Yup.object({
            groupId: Yup.string()
                .required(t('errors.required'))
        }),
        onSubmit: async (values) => {
            if (files.length === 0) {
                toast(t('errors.required'), 'error')
                return
            }

            setIsSubmitting(true)
            try {
                const formData = new FormData()
                files.forEach((file) => {
                    formData.append('files', file)
                })
                const uploadResult = await multiUpload.mutateAsync(formData)
                const uploadedUrls: string[] = uploadResult.data.map((item: { url: string }) => item.url)

                for (const url of uploadedUrls) {
                    await createIcon.mutateAsync({
                        url,
                        groupId: values.groupId
                    })
                }

                formik.resetForm()
                setFiles([])
                close()
                toast(t('success'), 'success')
                onSuccess?.()
            } catch (error) {
                const err = error as ErrorType
                toast(err.response?.data?.error?.message?.[0], 'error')
            } finally {
                setIsSubmitting(false)
            }
        }
    })

    const handleClose = () => {
        formik.resetForm()
        setFiles([])
        close()
    }

    return (
        <DefaulModal
            open={open}
            close={handleClose}
            title_header={t('icon.add_new_icon')}
            isHeader
        >
            <div className='mt-6'>
                <UploadBox
                    label={t('icon.url')}
                    onChange={(selectedFiles) => setFiles(selectedFiles)}
                    isReset={!open}
                    isMultiple
                    accept="image/svg+xml,.svg,image/png,.png"
                />

                <div className='mt-4'>
                    <Select
                        label={t('icon.group')}
                        className='bg-white bg-opacity-30'
                        items={groupOptions}
                        placeholder={t('icon.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={isSubmitting}
                        >
                            <div className='flex gap-2'>
                                <TickCircle
                                    size={20}
                                    color='white'
                                />
                                <div>
                                    {t('submit')}
                                </div>
                            </div>
                        </Button>
                    </div>
                </div>
            </div>
        </DefaulModal>
    )
}

export default CreateIcon
