import { type FC, useState } from 'react'
import type { FormikProps } from 'formik'
import { Add, Trash } from 'iconsax-react'
import Button from '../../../components/Button'
import Input from '../../../components/Input'
import UploadBox from '../../../components/UploadBox'
import { useSingleUpload } from '../../category/hooks/useCategoryData'
import { toast } from 'react-toastify'

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

type FormValues = {
    siteLogo?: string
    footerPhone: string
    footerEmail: string
    footerAddress: string
    footerDescription: string
    shopPostalCode?: string
    downloadAppDetails: { id: string; pic: string; url: string }[]
    socialMediaLinks: SocialMediaLink[]
}

type Props = {
    formik: FormikProps<FormValues>
}

const SocialMediaSection: FC<Props> = ({
    formik,
}) => {
    const singleUpload = useSingleUpload()
    const [uploadingIndexes, setUploadingIndexes] = useState<Set<number>>(new Set())
    const addSocialMediaLink = () => {
        const currentLinks = formik.values.socialMediaLinks || []
        const newId = Date.now().toString()
        formik.setFieldValue('socialMediaLinks', [...currentLinks, { id: newId, icon: '', url: '' }])
    }

    const removeSocialMediaLink = (index: number) => {
        const currentLinks = formik.values.socialMediaLinks || []
        formik.setFieldValue('socialMediaLinks', currentLinks.filter((_, i) => i !== index))
    }

    const updateSocialMediaLink = (index: number, field: 'url', value: string) => {
        const currentLinks = formik.values.socialMediaLinks || []
        const updatedLinks = currentLinks.map((item, i) =>
            i === index ? { ...item, [field]: value } : item
        )
        formik.setFieldValue('socialMediaLinks', updatedLinks)
    }

    const handleSocialMediaIconUpload = async (index: number, files: File[]) => {
        if (files.length === 0) return

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

            const uploadResponse = await singleUpload.mutateAsync(files[0])
            const imageUrl = uploadResponse.results.url.url

            updateSocialMediaLinkIcon(index, imageUrl)
            toast.success('آیکون با موفقیت آپلود شد')
        } catch {
            toast.error('خطا در آپلود آیکون')
        } finally {
            setUploadingIndexes(prev => {
                const newSet = new Set(prev)
                newSet.delete(index)
                return newSet
            })
        }
    }

    const updateSocialMediaLinkIcon = (index: number, iconUrl: string) => {
        const currentLinks = formik.values.socialMediaLinks || []
        const updatedLinks = currentLinks.map((item, i) =>
            i === index ? { ...item, icon: iconUrl } : item
        )
        formik.setFieldValue('socialMediaLinks', updatedLinks)
    }

    return (
        <div className='mt-6 bg-white py-8 xl:px-10 px-6 rounded-3xl'>
            <div className='flex justify-between items-center mb-6'>
                <h2 className='text-lg font-medium'>لینک‌های رسانه‌های اجتماعی</h2>
                <Button
                    size="sm"
                    variant="outline"
                    onClick={addSocialMediaLink}
                    className="flex items-center gap-2 w-fit"
                >
                    <Add size={16} color='#6B7280' />
                    افزودن
                </Button>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                {formik.values.socialMediaLinks?.map((item, index) => (
                    <div key={index} className="border border-gray-200 rounded-lg p-4">
                        <div className="flex justify-between items-center mb-4">
                            <span className="text-sm font-medium">لینک {index + 1}</span>
                            <Button className='w-fit' size="sm" variant="danger" onClick={() => removeSocialMediaLink(index)}>
                                <Trash size={16} color='white' />
                            </Button>
                        </div>
                        <div className="space-y-4">
                            <div>
                                <label className="block text-sm font-medium mb-2">آیکون</label>
                                <UploadBox
                                    label=""
                                    isMultiple={false}
                                    onChange={(files) => handleSocialMediaIconUpload(index, files)}
                                    isReset={false}
                                />
                                {item.icon && (
                                    <img src={item.icon} alt={`آیکون ${index + 1}`} className="mt-2 w-10 h-10 object-contain rounded" />
                                )}
                                {uploadingIndexes.has(index) && (
                                    <div className="mt-2 text-sm text-blue-600">در حال آپلود...</div>
                                )}
                            </div>
                            <Input
                                label="لینک"
                                value={item.url}
                                onChange={(e) => updateSocialMediaLink(index, 'url', e.target.value)}
                                placeholder="URL صفحه"
                            />
                        </div>
                    </div>
                ))}
            </div>
        </div>
    )
}

export default SocialMediaSection
