import { FC, useEffect } 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 '../../components/Toast'
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, useUpdateCompany, useGetCompanyById } 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 updateCompany = useUpdateCompany()
    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, id } = useParams()
    const isEdit = !!id
    const { data: companyResponse, isLoading: isLoadingCompany } = useGetCompanyById(id)
    const companyData = companyResponse?.data?.company || null
    const [isSubmitting, setIsSubmitting] = useState(false)

    const [services, setServices] = useState<{ title: string; image?: File; imageUrl?: string; existingImageUrl?: string }[]>([])
    const [products, setProducts] = useState<{ title: string; image?: File; imageUrl?: string; existingImageUrl?: string }[]>([])
    const [profileImageUrl, setProfileImageUrl] = useState<string>('')
    const [coverImageUrl, setCoverImageUrl] = useState<string>('')

    const formik = useFormik<CreateCompanyType>({
        initialValues: {
            phone: '',
            name: '',
            email: '',
            identificationNumber: '',
            dateOfEstablishment: '',
            address: '',
            mapAddressLink: '',
            description: '',
            websiteUrl: '',
            profileImageUrl: '',
            coverImageUrl: '',
            industryId: '',
            chiefExecutiveOfficer: '',
            metrage: undefined,
            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')),
            metrage: Yup.number().optional(),
        }),
        onSubmit: async (values) => {
            values.dateOfEstablishment = moment(values.dateOfEstablishment, 'jYYYY-jMM-jDD').format('YYYY-MM-DD')
            try {
                setIsSubmitting(true)
                if (!isEdit && (!profileImage || !coverImage)) {
                    toast('لطفا تصاویر را انتخاب کنید', 'error')
                    setIsSubmitting(false)
                    return
                }

                // بررسی مقادیر ضروری برای آپدیت
                if (isEdit && !values.profileImageUrl && !profileImage) {
                    toast('لطفا تصویر پروفایل را انتخاب کنید', 'error')
                    setIsSubmitting(false)
                    return
                }

                if (isEdit && !values.coverImageUrl && !coverImage) {
                    toast('لطفا تصویر کاور را انتخاب کنید', 'error')
                    setIsSubmitting(false)
                    return
                }

                let serviceImages: string[] = []
                if (services.length > 0) {
                    const newServices = services.filter(s => s.image)
                    if (newServices.length > 0) {
                        const formDataServices = new FormData()
                        newServices.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 newProducts = products.filter(p => p.image)
                    if (newProducts.length > 0) {
                        const formDataProducts = new FormData()
                        newProducts.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) => {
                    const newImageIndex = services.filter((item, i) => item.image && i < idx).length
                    return {
                        title: s.title,
                        imageUrl: s.image ? (serviceImages[newImageIndex] || '') : (s.existingImageUrl || '')
                    }
                })

                values.products = products.map((p, idx) => {
                    const newImageIndex = products.filter((item, i) => item.image && i < idx).length
                    return {
                        title: p.title,
                        imageUrl: p.image ? (productImages[newImageIndex] || '') : (p.existingImageUrl || '')
                    }
                })

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

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

                if (isEdit && companyData?.id) {
                    await handleUpdateCompany(companyData.id, values)
                } else {
                    await handleCreateCompany(values)
                }
            } catch (error) {
                setIsSubmitting(false)
                toast('خطا در ثبت اطلاعات', 'error')
                console.error('Submit error:', error)
            }
        }
    })

    const handleUpdateCompany = async (companyId: string, values: CreateCompanyType) => {
        try {
            console.log('Updating company with ID:', companyId);
            console.log('Update data:', values);
            await updateCompany.mutateAsync(
                { id: companyId, data: values }
            )
            toast('اطلاعات شرکت با موفقیت ویرایش شد', 'success')
            navigate(buildPath(Pages.company.my, slug), { replace: true })
        } catch (error: any) {
            console.error('Update error:', error);
            toast(error?.response?.data?.error?.message[0] || 'خطا در ویرایش اطلاعات', 'error')
        } finally {
            setIsSubmitting(false)
        }
    }

    const handleCreateCompany = async (values: CreateCompanyType) => {
        try {
            await createCompany.mutateAsync(values)
            toast('درخواست با موفقیت ثبت شد', 'success')
            navigate(buildPath(Pages.dashboard, slug), { replace: true })
        } catch (error: any) {
            toast(error?.response?.data?.error?.message[0] || 'خطا در ثبت درخواست', 'error')
        } finally {
            setIsSubmitting(false)
        }
    }

    useEffect(() => {
        if (isEdit && companyData) {
            formik.setValues({
                phone: companyData.user?.phone || '',
                name: companyData.name || '',
                email: companyData?.email || '',
                identificationNumber: companyData.identificationNumber || '',
                dateOfEstablishment: moment(companyData.dateOfEstablishment, 'jYYYY-jMM-jDD').format('jYYYY-jMM-jDD') || '',
                address: companyData.address || '',
                mapAddressLink: companyData.mapAddressLink || '',
                description: companyData.description || '',
                websiteUrl: companyData.websiteUrl || '',
                profileImageUrl: companyData.profileImageUrl || '',
                coverImageUrl: companyData.coverImageUrl || '',
                industryId: companyData.industry?.id || '',
                chiefExecutiveOfficer: companyData.user?.fullName || '',
                metrage: companyData.metrage ?? undefined,
                products: [],
                services: [],
            })

            setProfileImageUrl(companyData.profileImageUrl || '')
            setCoverImageUrl(companyData.coverImageUrl || '')

            if (companyData.services?.length) {
                setServices(companyData.services.map((service: any) => ({
                    title: service.title,
                    existingImageUrl: service.imageUrl
                })))
            }

            if (companyData.products?.length) {
                setProducts(companyData.products.map((product: any) => ({
                    title: product.title,
                    existingImageUrl: product.imageUrl
                })))
            }
        }
    }, [isEdit, companyData])

    return (
        <div className='mt-4'>
            {isLoadingCompany && isEdit ? (
                <div className='flex justify-center items-center py-20'>
                    <div className='animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-primary'></div>
                </div>
            ) : (
                <>
                    <div className='flex flex-col md:flex-row justify-between items-start md:items-center gap-4'>
                        <div className='text-base'>
                            {isEdit ? 'ویرایش اطلاعات شرکت' : 'ثبت درخواست'}
                        </div>

                        <div className='flex justify-end w-full'>
                            <Button
                                className='w-fit px-4'
                                onClick={() => formik.handleSubmit()}
                                isLoading={isSubmitting}
                            >
                                <div className='flex items-center gap-2'>
                                    <TickCircle size={20} color='white' />
                                    <div>{isEdit ? 'ذخیره تغییرات' : 'ثبت درخواست'}</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'>{isEdit ? 'اطلاعات شرکت' : 'اطلاعات درخواست'}</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>

                            <Input
                                type='number'
                                label='متراژ'
                                name='metrage'
                                value={formik.values.metrage ?? ''}
                                onChange={(e) => formik.setFieldValue('metrage', e.target.value === '' ? undefined : Number(e.target.value))}
                                error_text={formik.touched.metrage && formik.errors.metrage ? formik.errors.metrage : ''}
                            />

                            <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', date)}
                                    error_text={formik.touched.dateOfEstablishment && formik.errors.dateOfEstablishment ? formik.errors.dateOfEstablishment : ''}
                                    defaulValue={formik.values.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 : ''}
                                placeholder='انتخاب صنعت'
                            />

                            <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)