import { type FC, useEffect, useState } from 'react'
import PageTitle from '../../components/PageTitle'
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(),
    downloadAppDetails: Yup.array(),
    socialMediaLinks: Yup.array()
})

const SiteSetting: FC = () => {

    const { data, isLoading } = useGetSiteSetting()
    const { data: shopData, isLoading: isShopLoading } = useGetShop()
    const updateSiteSetting = useUpdateSiteSetting()
    const [isDataLoaded, setIsDataLoaded] = useState(false)
    const singleUpload = useSingleUpload()
    const [logoFile, setLogoFile] = useState<File[]>([])
    const [postalCodeFile, setPostalCodeFile] = useState<File[]>([])



    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 siteLogo = values.siteLogo
            let shopPostalCode = values.shopPostalCode

            // آپلود لوگو سایت اگر فایل جدید انتخاب شده
            if (logoFile.length > 0) {
                const logoResponse = await singleUpload.mutateAsync(logoFile[0])
                siteLogo = logoResponse.results?.url?.url || undefined
            }

            // آپلود کد پستی فروشگاه اگر فایل جدید انتخاب شده
            if (postalCodeFile.length > 0) {
                const postalResponse = await singleUpload.mutateAsync(postalCodeFile[0])
                shopPostalCode = postalResponse.results?.url?.url || undefined
            }

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

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


    useEffect(() => {
        // وقتی loading تمام شد، داده‌ها را مقداردهی اولیه کن
        if (!isLoading && !isShopLoading) {
            const siteSetting = data?.results?.siteSetting || {}
            const shop = shopData?.results?.shop || {}

            formik.setValues({
                siteLogo: siteSetting.siteLogo || undefined,
                footerPhone: siteSetting.footerPhone || '',
                footerEmail: siteSetting.footerEmail || '',
                footerAddress: siteSetting.footerAddress || '',
                footerDescription: siteSetting.footerDescription || '',
                shopPostalCode: (shop && 'shopPostalCode' in shop ? String(shop.shopPostalCode) : '') || '',
                downloadAppDetails: (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: (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, isLoading, isShopLoading])


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

    return (
        <div className='mt-4'>
            <PageTitle />
            <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}
                    logoFile={logoFile}
                    setLogoFile={setLogoFile}
                    postalCodeFile={postalCodeFile}
                    setPostalCodeFile={setPostalCodeFile}
                />
            </div>

            <DownloadAppSection formik={formik} />

            <SocialMediaSection formik={formik} />
        </div>
    )
}

export default SiteSetting