import { type FC } 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'

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[]
}

type Props = {
    formik: FormikProps<FormValues>
    pendingFiles: { [key: string]: File }
    setPendingFiles: React.Dispatch<React.SetStateAction<{ [key: string]: File }>>
    uploadingIndexes: Set<number>
    setUploadingIndexes: React.Dispatch<React.SetStateAction<Set<number>>>
}

const DownloadAppSection: FC<Props> = ({
    formik,
    setPendingFiles,
    uploadingIndexes,
}) => {
    const addDownloadAppDetail = () => {
        const currentDetails = formik.values.downloadAppDetails || []
        const newId = Date.now().toString()
        formik.setFieldValue('downloadAppDetails', [...currentDetails, { id: newId, pic: '', url: '' }])
    }

    const removeDownloadAppDetail = (index: number) => {
        const currentDetails = formik.values.downloadAppDetails || []
        const itemToRemove = currentDetails[index]

        formik.setFieldValue('downloadAppDetails', currentDetails.filter((_, i) => i !== index))

        // پاک کردن pending file مربوطه
        if (itemToRemove) {
            setPendingFiles(prev => {
                const newPending = { ...prev }
                delete newPending[itemToRemove.id]
                return newPending
            })
        }
    }

    const updateDownloadAppDetail = (index: number, field: 'pic' | 'url', value: string) => {
        const currentDetails = formik.values.downloadAppDetails || []
        const updatedDetails = currentDetails.map((item, i) =>
            i === index ? { ...item, [field]: value } : item
        )
        formik.setFieldValue('downloadAppDetails', updatedDetails)
    }

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

        const item = formik.values.downloadAppDetails?.[index]
        if (!item) return

        // ذخیره فایل برای آپلود بعدی
        setPendingFiles(prev => ({
            ...prev,
            [item.id]: files[0]
        }))

        // نمایش preview
        updateDownloadAppDetail(index, 'pic', URL.createObjectURL(files[0]))
    }

    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={addDownloadAppDetail}
                    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.downloadAppDetails?.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={() => removeDownloadAppDetail(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) => handleDownloadAppImageUpload(index, files)}
                                    isReset={false}
                                />
                                {item.pic && (
                                    <img src={item.pic} alt={`تصویر ${index + 1}`} className="mt-2 w-20 h-20 object-contain rounded" />
                                )}
                                {uploadingIndexes.has(index) && (
                                    <div className="mt-2 text-sm text-blue-600">در حال آپلود...</div>
                                )}
                            </div>
                            <Input
                                label="لینک"
                                value={item.url}
                                onChange={(e) => updateDownloadAppDetail(index, 'url', e.target.value)}
                                placeholder="URL دانلود"
                            />
                        </div>
                    </div>
                ))}
            </div>
        </div>
    )
}

export default DownloadAppSection
