import { type FC, useEffect, useState } from 'react'
import { useFormik } from 'formik'
import * as Yup from 'yup'
import { useGetSiteSetting, useUpdateSiteSetting, useGetShop } from './hooks/useSettingData'

type DownloadAppDetail = {
    id: string
    pic: string
    url: string
}

type SocialMediaLink = {
    id: string
    icon: string
    url: string
}

type FormValues = {
    siteLogo?: string
    footerPhone: string
    footerEmail: string
    footerAddress: string
    footerDescription: string
    shopPostalCode?: string
    downloadAppDetails: DownloadAppDetail[]
    socialMediaLinks: SocialMediaLink[]
}
import Button from '../../components/Button'
import { TickCircle } from 'iconsax-react'
import MainInfoSection from './components/MainInfoSection'
import FilesSection from './components/FilesSection'
import DownloadAppSection from './components/DownloadAppSection'
import SocialMediaSection from './components/SocialMediaSection'
import { toast } from 'react-toastify'
import { extractErrorMessage } from '../../helpers/utils'
import { useSingleUpload } from '../category/hooks/useCategoryData'

const validationSchema = Yup.object().shape({
    footerPhone: Yup.string().trim().required('تلفن فوتر الزامی است'),
    footerEmail: Yup.string().email('ایمیل معتبر نیست').required('ایمیل فوتر الزامی است'),
    footerAddress: Yup.string().trim().required('آدرس فوتر الزامی است'),
    footerDescription: Yup.string().trim().required('توضیحات فوتر الزامی است'),
    shopPostalCode: Yup.string().trim(),
    siteLogo: Yup.string(),
    downloadAppDetails: Yup.array(),
    socialMediaLinks: Yup.array()
})

const SiteSetting: FC = () => {

    const { data, isLoading } = useGetSiteSetting()
    const { data: shopData } = useGetShop()
    const updateSiteSetting = useUpdateSiteSetting()
    const [isDataLoaded, setIsDataLoaded] = useState(false)
    const [uploadingIndexes, setUploadingIndexes] = useState<Set<number>>(new Set())
    const [pendingFiles, setPendingFiles] = useState<{ [key: string]: File }>({})
    const singleUpload = useSingleUpload()

    const formik = useFormik<FormValues>({
        initialValues: {
            siteLogo: undefined,
            footerPhone: '',
            footerEmail: '',
            footerAddress: '',
            footerDescription: '',
            shopPostalCode: '',
            downloadAppDetails: [],
            socialMediaLinks: [] as SocialMediaLink[]
        },
        validationSchema,
        validateOnChange: false,
        validateOnBlur: false,
        onSubmit: async (values) => {
            let finalDownloadAppDetails = values.downloadAppDetails
            let finalSocialMediaLinks = values.socialMediaLinks

            // اول همه فایل‌های pending رو آپلود کن
            if (Object.keys(pendingFiles).length > 0) {
                const uploadedData = await uploadAllPendingFiles()
                // بروزرسانی downloadAppDetails با URL های واقعی
                finalDownloadAppDetails = values.downloadAppDetails.map(item => {
                    const uploadedUrl = uploadedData[item.id]
                    return uploadedUrl ? { ...item, pic: uploadedUrl } : item
                })
                // بروزرسانی socialMediaLinks با URL های واقعی
                finalSocialMediaLinks = values.socialMediaLinks.map(item => {
                    const uploadedUrl = uploadedData[item.id]
                    return uploadedUrl ? { ...item, icon: uploadedUrl } : item
                })
                // پاک کردن pending files بعد از آپلود موفق
                setPendingFiles({})
            }

            // transform data برای ارسال به API (حذف id)
            const transformedValues = {
                ...values,
                downloadAppDetails: finalDownloadAppDetails.map((item) => ({
                    pic: item.pic,
                    url: item.url
                })),
                socialMediaLinks: finalSocialMediaLinks.map((item) => ({
                    icon: item.icon,
                    url: item.url
                }))
            }

            // حالا فرم رو submit کن
            updateSiteSetting.mutate(transformedValues, {
                onSuccess: () => {
                    toast.success('تنظیمات سایت با موفقیت بروزرسانی شد')
                    // پاک کردن pending files بعد از submit موفق
                    setPendingFiles({})
                },
                onError: (error) => {
                    toast.error(extractErrorMessage(error))
                }
            })
        }
    })

    useEffect(() => {
        if (data?.results?.siteSetting && shopData?.results?.shop) {
            formik.setValues({
                siteLogo: data.results.siteSetting.siteLogo || undefined,
                footerPhone: data.results.siteSetting.footerPhone || '',
                footerEmail: data.results.siteSetting.footerEmail || '',
                footerAddress: data.results.siteSetting.footerAddress || '',
                footerDescription: data.results.siteSetting.footerDescription || '',
                shopPostalCode: shopData.results.shop.shopPostalCode || '',
                downloadAppDetails: (data.results.siteSetting.downloadAppDetails || []).map((item: { _id?: string; pic: string; url: string }, index: number) => ({
                    id: item._id || `existing-${index}-${Date.now()}`,
                    pic: item.pic,
                    url: item.url
                })),
                socialMediaLinks: (data.results.siteSetting.socialMediaLinks || []).map((item: { icon: string; url: string }, index: number) => ({
                    id: `existing-${index}-${Date.now()}`,
                    icon: item.icon,
                    url: item.url
                }))
            }, false)
            setIsDataLoaded(true)
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [data, shopData])


    const uploadAllPendingFiles = async (): Promise<{ [key: string]: string }> => {
        const uploadedUrls: { [key: string]: string } = {}

        for (const [id, file] of Object.entries(pendingFiles)) {
            // پیدا کردن index آیتم در downloadAppDetails
            let index = formik.values.downloadAppDetails?.findIndex(item => item.id === id)
            let isDownloadApp = true

            if (index === undefined || index === -1) {
                // اگر در downloadAppDetails نبود، در socialMediaLinks جستجو کن
                index = formik.values.socialMediaLinks?.findIndex(item => item.id === id)
                isDownloadApp = false
            }

            if (index === undefined || index === -1) continue

            try {
                setUploadingIndexes(prev => new Set(prev).add(index))

                const uploadResponse = await singleUpload.mutateAsync(file)
                const imageUrl = uploadResponse.results.url.url

                uploadedUrls[id] = imageUrl

                // بروزرسانی formik
                if (isDownloadApp) {
                    const currentDetails = formik.values.downloadAppDetails || []
                    const updatedDetails = currentDetails.map((item, i) =>
                        i === index ? { ...item, pic: imageUrl } : item
                    )
                    formik.setFieldValue('downloadAppDetails', updatedDetails)
                } else {
                    const currentLinks = formik.values.socialMediaLinks || []
                    const updatedLinks = currentLinks.map((item, i) =>
                        i === index ? { ...item, icon: imageUrl } : item
                    )
                    formik.setFieldValue('socialMediaLinks', updatedLinks)
                }

            } catch (error) {
                const itemType = isDownloadApp ? 'تصویر دانلود اپ' : 'آیکون رسانه اجتماعی'
                toast.error(`خطا در آپلود ${itemType} آیتم ${index + 1}`)
                throw error
            } finally {
                setUploadingIndexes(prev => {
                    const newSet = new Set(prev)
                    newSet.delete(index)
                    return newSet
                })
            }
        }

        return uploadedUrls
    }


    if (isLoading) {
        return <div className="flex justify-center items-center h-64">در حال بارگذاری...</div>
    }

    return (
        <div className='mt-4'>
            <div className='flex justify-between items-center'>
                <div className='flex items-center gap-3'>
                    <h1>تنظیمات سایت</h1>
                </div>
                <div>
                    <Button
                        className='px-6'
                        onClick={() => formik.handleSubmit()}
                        isLoading={updateSiteSetting.isPending}
                        disabled={(!isDataLoaded || !formik.isValid) || updateSiteSetting.isPending}
                    >
                        <div className='flex gap-2 items-center'>
                            <TickCircle size={16} color='#fff' />
                            <div>بروزرسانی تنظیمات</div>
                        </div>
                    </Button>
                </div>
            </div>

            <div className='flex gap-6 xl:mt-8 mt-6'>
                <MainInfoSection formik={formik} isDataLoaded={isDataLoaded} />
                <FilesSection formik={formik} />
            </div>

            <DownloadAppSection
                formik={formik}
                pendingFiles={pendingFiles}
                setPendingFiles={setPendingFiles}
                uploadingIndexes={uploadingIndexes}
                setUploadingIndexes={setUploadingIndexes}
            />

            <SocialMediaSection
                formik={formik}
                pendingFiles={pendingFiles}
                setPendingFiles={setPendingFiles}
                uploadingIndexes={uploadingIndexes}
                setUploadingIndexes={setUploadingIndexes}
            />
        </div>
    )
}

export default SiteSetting