import { FC } from 'react'
import withAuth from '../../hoc/withAuth'
import Button from '../../components/Button'
import { TickCircle } from 'iconsax-react'
import Input from '../../components/Input'
import { useTranslation } from 'react-i18next'
import { useFormik } from 'formik'
import * as Yup from 'yup'
import { useState } from 'react'
import { toast } from 'react-toastify'
import { ErrorType } from '../../helpers/types'
import { Pages } from '../../config/Pages'
import { useNavigate, useParams } from 'react-router-dom'
import DatePickerComponent from '../../components/DatePicker'
import moment from 'moment-jalaali'
import { useCreateCompany, useMultiUpload, useSingleUpload } from './hooks/useRequestData'
import { CreateCompanyType } from './types/Types'
import UploadBox from '../../components/UploadBox'
import CompanyServices from './components/CompanyServices'
import CompanyProducts from './components/CompanyProducts'
import { useGetIndustry } from '../home/hooks/useHomeData'
import Select from '../../components/Select'
import { IndustryItemType } from '../home/types/HomeTypes'
import { buildPath } from '../../helpers/utils'
const Request: FC = () => {

    const createCompany = useCreateCompany()
    const navigate = useNavigate()
    const { t } = useTranslation('global')
    const [profileImage, setProfileImage] = useState<File | null>(null)
    const [coverImage, setCoverImage] = useState<File | null>(null)
    const multiUpload = useMultiUpload()
    const singleUpload = useSingleUpload()
    const { data: industries } = useGetIndustry()
    const { slug } = useParams()

    const [services, setServices] = useState<{ title: string; image?: File }[]>([])
    const [products, setProducts] = useState<{ title: string; image?: File }[]>([])

    const formik = useFormik<CreateCompanyType>({
        initialValues: {
            phone: '',
            name: '',
            email: '',
            identificationNumber: '',
            dateOfEstablishment: '',
            address: '',
            mapAddressLink: '',
            description: '',
            websiteUrl: '',
            profileImageUrl: '',
            coverImageUrl: '',
            industryId: '',
            chiefExecutiveOfficer: '',
            products: [],
            services: [],
        },
        validationSchema: Yup.object({
            phone: Yup.string().required(t('errors.required')),
            name: Yup.string().required(t('errors.required')),
            email: Yup.string().email(t('errors.invalid_email')).required(t('errors.required')),
            identificationNumber: Yup.string().required(t('errors.required')),
            dateOfEstablishment: Yup.string().required(t('errors.required')),
            address: Yup.string().required(t('errors.required')),
            mapAddressLink: Yup.string().url(t('errors.invalid_url')),
            description: Yup.string().required(t('errors.required')),
            websiteUrl: Yup.string().url(t('errors.invalid_url')).required(t('errors.required')),
            industryId: Yup.string().required(t('errors.required')),
        }),
        onSubmit: async (values) => {
            if (!profileImage || !coverImage) {
                toast.error('لطفا تصاویر را انتخاب کنید')
                return
            }

            let serviceImages: string[] = []
            if (services.length > 0) {
                const formDataServices = new FormData()
                services.forEach(s => s.image && formDataServices.append('files', s.image))
                const serviceUploadRes = await multiUpload.mutateAsync(formDataServices)
                serviceImages = serviceUploadRes.data.map((item: { url: string }) => item?.url)
            }

            // آپلود تصاویر محصولات
            let productImages: string[] = []
            if (products.length > 0) {
                const formDataProducts = new FormData()
                products.forEach(p => p.image && formDataProducts.append('files', p.image))
                const productUploadRes = await multiUpload.mutateAsync(formDataProducts)
                productImages = productUploadRes.data.map((item: { url: string }) => item?.url)
            }

            // مقداردهی به values
            values.services = services.map((s, idx) => ({
                title: s.title,
                imageUrl: serviceImages[idx] ? serviceImages[idx] : ''
            }))
            values.products = products.map((p, idx) => ({
                title: p.title,
                imageUrl: productImages[idx] ? productImages[idx] : ''
            }))

            const formDataProfile = new FormData()
            formDataProfile.append('file', profileImage)
            const profileUploadRes = await singleUpload.mutateAsync(formDataProfile)
            values.profileImageUrl = profileUploadRes.data.url

            const formDataCover = new FormData()
            formDataCover.append('file', coverImage)
            const coverUploadRes = await singleUpload.mutateAsync(formDataCover)
            values.coverImageUrl = coverUploadRes.data.url

            createCompany.mutate(values, {
                onSuccess: () => {
                    toast.success('درخواست با موفقیت ثبت شد')
                    navigate(buildPath(Pages.dashboard, slug))
                },
                onError: (error: ErrorType) => {
                    toast.error(error.response?.data?.error.message[0])
                }
            })
            toast.success('درخواست با موفقیت ثبت شد')
            // navigate(Pages.request.list)
        }
    })

    return (
        <div className='mt-4'>
            <div className='flex flex-col md:flex-row justify-between items-start md:items-center gap-4'>
                <div className='text-base'>
                    ثبت درخواست
                </div>

                <div className='flex justify-end w-full'>
                    <Button
                        className='w-fit px-4'
                        onClick={() => formik.handleSubmit()}
                        isLoading={singleUpload.isPending || multiUpload.isPending}
                    >
                        <div className='flex items-center gap-2'>
                            <TickCircle size={20} color='white' />
                            <div>ثبت درخواست</div>
                        </div>
                    </Button>
                </div>
            </div>

            <div className='mt-10 bg-white py-8 px-4 md:px-6 lg:px-10 rounded-3xl'>
                <div className='text-lg font-medium mb-6'>اطلاعات درخواست</div>

                <div className='space-y-6'>
                    <Input
                        label='نام شرکت'
                        name='name'
                        value={formik.values.name}
                        onChange={formik.handleChange}
                        error_text={formik.touched.name && formik.errors.name ? formik.errors.name : ''}
                    />

                    <div className=''>
                        <Input
                            label='نام مدیر عامل'
                            name='chiefExecutiveOfficer'
                            value={formik.values.chiefExecutiveOfficer}
                            onChange={formik.handleChange}
                            error_text={formik.touched.chiefExecutiveOfficer && formik.errors.chiefExecutiveOfficer ? formik.errors.chiefExecutiveOfficer : ''}
                        />
                    </div>


                    <div className='grid grid-cols-1 md:grid-cols-2 gap-6'>
                        <Input
                            label={t('company.phone_number')}
                            name='phone'
                            value={formik.values.phone}
                            onChange={formik.handleChange}
                            error_text={formik.touched.phone && formik.errors.phone ? formik.errors.phone : ''}
                        />
                        <Input
                            label={t('company.email')}
                            name='email'
                            value={formik.values.email}
                            onChange={formik.handleChange}
                            error_text={formik.touched.email && formik.errors.email ? formik.errors.email : ''}
                        />
                    </div>

                    <div className='grid grid-cols-1 md:grid-cols-2 gap-6'>
                        <Input
                            label={t('company.national_id')}
                            name='identificationNumber'
                            value={formik.values.identificationNumber}
                            onChange={formik.handleChange}
                            error_text={formik.touched.identificationNumber && formik.errors.identificationNumber ? formik.errors.identificationNumber : ''}
                        />
                        <DatePickerComponent
                            label={t('company.establishment_date')}
                            placeholder='تاریخ تاسیس'
                            onChange={(date) => formik.setFieldValue('dateOfEstablishment', moment(date).format('YYYY-MM-DD'))}
                            error_text={formik.touched.dateOfEstablishment && formik.errors.dateOfEstablishment ? formik.errors.dateOfEstablishment : ''}
                        />
                    </div>

                    <Select
                        label={t('company.industry')}
                        name='industryId'
                        items={industries?.data?.industries?.map((industry: IndustryItemType) => ({ label: industry.title, value: industry.id })) || []}
                        onChange={formik.handleChange}
                        error_text={formik.touched.industryId && formik.errors.industryId ? formik.errors.industryId : ''}
                    />

                    <Input
                        label={t('company.map_link')}
                        name='mapAddressLink'
                        value={formik.values.mapAddressLink}
                        onChange={formik.handleChange}
                        error_text={formik.touched.mapAddressLink && formik.errors.mapAddressLink ? formik.errors.mapAddressLink : ''}
                    />

                    <Input
                        label={t('company.address')}
                        name='address'
                        value={formik.values.address}
                        onChange={formik.handleChange}
                        error_text={formik.touched.address && formik.errors.address ? formik.errors.address : ''}
                    />

                    <Input
                        label={t('company.short_description')}
                        name='description'
                        value={formik.values.description}
                        onChange={formik.handleChange}
                        error_text={formik.touched.description && formik.errors.description ? formik.errors.description : ''}
                    />

                    <Input
                        label={t('company.website_url')}
                        name='websiteUrl'
                        value={formik.values.websiteUrl}
                        onChange={formik.handleChange}
                        error_text={formik.touched.websiteUrl && formik.errors.websiteUrl ? formik.errors.websiteUrl : ''}
                    />

                    <UploadBox
                        label='تصویر پروفایل شرکت'
                        onChange={(file) => setProfileImage(file[0])}
                    />

                    <UploadBox
                        label='تصویر کاور'
                        onChange={(file) => setCoverImage(file[0])}
                    />


                    <CompanyServices value={services} onChange={setServices} />
                    <CompanyProducts value={products} onChange={setProducts} />
                </div>
            </div>
        </div>
    )
}

export default withAuth(Request)