import Button from '@/components/Button'
import Select from '@/components/Select'
import Input from '@/components/Input'
import UploadBoxDraggble from '@/components/UploadBoxDraggble'
import { Add, AlignBottom, AlignHorizontally, AlignLeft, AlignRight, AlignTop, AlignVertically, Edit, Trash } from 'iconsax-react'
import { FC, useState, useEffect } from 'react'
import { useTranslation } from 'react-i18next'
import { usePersonalityStore } from '../store/Store'
import { ImageSize, HorizontalAlignment, VerticalAlignment, ElementType } from '../types/Types'
import { useSingleUpload } from '../hooks/usePersonalityData'

const ImageSideBar: FC = () => {

    const { t } = useTranslation()
    const {
        addImageToActiveItem,
        activeSection,
        activeItemIndex,
        data,
        selectedElement,
        setSelectedElement,
        updateImage,
        deleteImage
    } = usePersonalityStore()

    const [imageSrc, setImageSrc] = useState<string>('')
    const [imageSize, setImageSize] = useState<ImageSize>(ImageSize.COVER)
    const [horizontalAlignment, setHorizontalAlignment] = useState<HorizontalAlignment>(HorizontalAlignment.CENTER)
    const [verticalAlignment, setVerticalAlignment] = useState<VerticalAlignment>(VerticalAlignment.MIDDLE)
    const [imageWidth, setImageWidth] = useState<string>('100%')
    const [imageHeight, setImageHeight] = useState<string>('auto')
    const [isLoading, setIsLoading] = useState<boolean>(false)
    const [isReset, setIsReset] = useState<boolean>(false)
    const [isUploading, setIsUploading] = useState<boolean>(false)

    const { mutateAsync: singleUpload } = useSingleUpload()

    const isEditMode = selectedElement?.type === ElementType.IMAGE;

    // Load selected image data when element is selected
    useEffect(() => {
        if (isEditMode && selectedElement) {
            try {
                const sectionData = data[selectedElement.sectionKey];

                if (!sectionData || !sectionData.items) {
                    console.error('Section data or items not found');
                    return;
                }

                const item = sectionData.items.find(item => item.id === selectedElement.itemId);

                if (!item) {
                    console.error('Item not found');
                    return;
                }

                const image = item.images?.find(img => img.id === selectedElement.elementId);

                if (image) {
                    setImageSrc(image.src);
                    setImageSize(image.size);
                    setHorizontalAlignment(image.alignment || HorizontalAlignment.CENTER);
                    setVerticalAlignment(image.verticalAlignment || VerticalAlignment.MIDDLE);
                    setImageWidth(image.width || '100%');
                    setImageHeight(image.height || 'auto');
                } else {
                    console.error('Image element not found');
                }
            } catch (error) {
                console.error('Error loading image data:', error);
            }
        } else {
            // Reset form when not in edit mode
            setImageSrc('')
            setImageSize(ImageSize.COVER)
            setHorizontalAlignment(HorizontalAlignment.CENTER)
            setVerticalAlignment(VerticalAlignment.MIDDLE)
            setImageWidth('100%')
            setImageHeight('auto')
        }
    }, [selectedElement, isEditMode, data]);

    const sizeOptions = [
        { label: 'کاور ', value: ImageSize.COVER },
        { label: 'در مقیاس', value: ImageSize.CONTAIN },
        { label: 'تکرار', value: ImageSize.REPEAT },
        { label: 'تکرار افقی', value: ImageSize.REPEAT_X },
        { label: 'تکرار عمودی', value: ImageSize.REPEAT_Y },
        { label: 'بدون تکرار', value: ImageSize.NO_REPEAT },
        { label: 'اندازه اصلی', value: ImageSize.AUTO }
    ]

    const handleImageUpload = async (files: File[]) => {
        if (files.length === 0) return

        const file = files[0]
        setIsUploading(true)

        try {
            const uploadResult = await singleUpload(file)
            const imageUrl = uploadResult?.data?.url

            if (imageUrl) {
                setImageSrc(imageUrl)
            }
        } catch (error) {
            console.error('Error uploading image:', error)
            // Fallback to FileReader if upload fails
            const reader = new FileReader()
            reader.onload = (e) => {
                const result = e.target?.result as string
                setImageSrc(result)
            }
            reader.readAsDataURL(file)
        } finally {
            setIsUploading(false)
        }
    }

    const handleAddImage = () => {
        if (!imageSrc) return

        // Validation
        if (!activeSection) {
            console.error('No active section selected')
            return
        }

        const sectionData = data[activeSection as keyof typeof data]
        if (!sectionData?.items || activeItemIndex >= sectionData.items.length) {
            console.error('No active item found or invalid index', {
                activeItemIndex,
                itemsLength: sectionData?.items?.length
            })
            return
        }

        setIsLoading(true)

        try {
            addImageToActiveItem({
                src: imageSrc,
                alt: 'عکس آپلود شده',
                size: imageSize,
                alignment: horizontalAlignment,
                verticalAlignment,
                width: imageWidth,
                height: imageHeight,
            })

            // Reset form after adding
            setImageSrc('')
            setImageSize(ImageSize.COVER)
            setHorizontalAlignment(HorizontalAlignment.CENTER)
            setVerticalAlignment(VerticalAlignment.MIDDLE)
            setImageWidth('100%')
            setImageHeight('auto')
            setIsReset(true)
            setTimeout(() => {
                setIsReset(false)
            }, 1000)
        } catch (error) {
            console.error('Error adding image:', error)
        } finally {
            setIsLoading(false)
        }
    }

    const handleUpdateImage = () => {
        if (selectedElement && imageSrc) {
            setIsLoading(true)

            try {
                updateImage(
                    selectedElement.sectionKey,
                    selectedElement.itemId,
                    selectedElement.elementId,
                    {
                        src: imageSrc,
                        alt: 'عکس آپلود شده',
                        size: imageSize,
                        alignment: horizontalAlignment,
                        verticalAlignment,
                        width: imageWidth,
                        height: imageHeight,
                    }
                );

                // Exit edit mode
                setSelectedElement(null);
            } catch (error) {
                console.error('Error updating image:', error)
            } finally {
                setIsLoading(false)
            }
        }
    }

    const handleDeleteImage = () => {
        if (selectedElement) {
            deleteImage(
                selectedElement.sectionKey,
                selectedElement.itemId,
                selectedElement.elementId
            );

            // Exit edit mode
            setSelectedElement(null);
        }
    }

    const handleCancelEdit = () => {
        setSelectedElement(null);
    }

    return (
        <div>
            <div className='text-lg flex items-center justify-between'>
                {t('setting.image')}
                {isEditMode && (
                    <div className='flex items-center gap-2'>
                        <span className='text-sm text-blue-600'>{t('setting.edit_mode')}</span>
                        <Edit size={16} color='#0038FF' />
                    </div>
                )}
            </div>

            <div className='mt-8'>
                <UploadBoxDraggble
                    label={isUploading ? 'در حال آپلود...' : t('setting.upload_image')}
                    onChange={handleImageUpload}
                    isReset={isReset}
                />
            </div>

            {isEditMode && imageSrc && (
                <div className='mt-5'>
                    <div className='text-sm mb-2'>{t('setting.current_image')}</div>
                    <img src={imageSrc} alt="پیش‌نمایش" className='w-full h-32 object-cover rounded border' />
                </div>
            )}

            <div className='mt-5'>
                <Select
                    items={sizeOptions}
                    label={t('setting.size')}
                    value={imageSize}
                    onChange={(e) => setImageSize(e.target.value as ImageSize)}
                    placeholder={t('setting.size')}
                    disabled={isUploading}
                />
            </div>

            <div className='mt-5'>
                <div className='text-sm mb-3'>اندازه سریع</div>
                <div className='flex gap-2 flex-wrap'>
                    <button
                        type='button'
                        onClick={() => { setImageWidth('100%'); setImageHeight('auto'); }}
                        className='px-3 py-1 text-xs bg-gray-100 hover:bg-gray-200 rounded transition-colors'
                        disabled={isUploading}
                    >
                        تمام عرض
                    </button>
                    <button
                        type='button'
                        onClick={() => { setImageWidth('50%'); setImageHeight('auto'); }}
                        className='px-3 py-1 text-xs bg-gray-100 hover:bg-gray-200 rounded transition-colors'
                        disabled={isUploading}
                    >
                        نصف عرض
                    </button>
                    <button
                        type='button'
                        onClick={() => { setImageWidth('200px'); setImageHeight('150px'); }}
                        className='px-3 py-1 text-xs bg-gray-100 hover:bg-gray-200 rounded transition-colors'
                        disabled={isUploading}
                    >
                        کوچک
                    </button>
                    <button
                        type='button'
                        onClick={() => { setImageWidth('300px'); setImageHeight('200px'); }}
                        className='px-3 py-1 text-xs bg-gray-100 hover:bg-gray-200 rounded transition-colors'
                        disabled={isUploading}
                    >
                        متوسط
                    </button>
                    <button
                        type='button'
                        onClick={() => { setImageWidth('400px'); setImageHeight('300px'); }}
                        className='px-3 py-1 text-xs bg-gray-100 hover:bg-gray-200 rounded transition-colors'
                        disabled={isUploading}
                    >
                        بزرگ
                    </button>
                </div>
            </div>

            <div className='mt-5 grid grid-cols-2 gap-4'>
                <div>
                    <Input
                        label='عرض (Width)'
                        value={imageWidth}
                        onChange={(e) => setImageWidth(e.target.value)}
                        placeholder='مثال: 100%, 200px'
                        disabled={isUploading}
                    />
                </div>
                <div>
                    <Input
                        label='ارتفاع (Height)'
                        value={imageHeight}
                        onChange={(e) => setImageHeight(e.target.value)}
                        placeholder='مثال: auto, 150px'
                        disabled={isUploading}
                    />
                </div>
            </div>

            <div className='mt-5 flex justify-between'>
                <div>
                    <div className='text-sm'>
                        {t('setting.horizontal_position')}
                    </div>
                    <div className='mt-3 flex gap-4'>
                        <div
                            onClick={() => setHorizontalAlignment(HorizontalAlignment.RIGHT)}
                        >
                            <AlignRight size={20} color={horizontalAlignment === HorizontalAlignment.RIGHT ? '#0038FF' : '#000'} />
                        </div>
                        <div
                            onClick={() => setHorizontalAlignment(HorizontalAlignment.CENTER)}
                        >
                            <AlignVertically size={20} color={horizontalAlignment === HorizontalAlignment.CENTER ? '#0038FF' : '#000'} />
                        </div>
                        <div
                            onClick={() => setHorizontalAlignment(HorizontalAlignment.LEFT)}
                        >
                            <AlignLeft size={20} color={horizontalAlignment === HorizontalAlignment.LEFT ? '#0038FF' : '#000'} />
                        </div>
                    </div>
                </div>

                <div>
                    <div className='text-sm'>
                        {t('setting.vertical_position')}
                    </div>
                    <div className='mt-3 flex gap-4'>
                        <div
                            onClick={() => setVerticalAlignment(VerticalAlignment.BOTTOM)}
                        >
                            <AlignBottom size={20} color={verticalAlignment === VerticalAlignment.BOTTOM ? '#0038FF' : '#000'} />
                        </div>
                        <div
                            onClick={() => setVerticalAlignment(VerticalAlignment.MIDDLE)}
                        >
                            <AlignHorizontally size={20} color={verticalAlignment === VerticalAlignment.MIDDLE ? '#0038FF' : '#000'} />
                        </div>
                        <div
                            onClick={() => setVerticalAlignment(VerticalAlignment.TOP)}
                        >
                            <AlignTop size={20} color={verticalAlignment === VerticalAlignment.TOP ? '#0038FF' : '#000'} />
                        </div>
                    </div>
                </div>
            </div>

            <div className='mt-7'>
                {isEditMode ? (
                    <div className='space-y-3'>
                        <Button
                            onClick={handleUpdateImage}
                            className='w-full'
                            disabled={!imageSrc || isUploading}
                            loading={isLoading || isUploading}
                        >
                            <div className='flex justify-center items-center gap-2'>
                                <Edit size={18} color='white' />
                                <span>{t('setting.update_image')}</span>
                            </div>
                        </Button>
                        <div className='flex gap-2'>
                            <Button
                                onClick={handleDeleteImage}
                                className='bg-red-500 text-white flex-1'
                            >
                                <div className='flex justify-center items-center gap-1'>
                                    <Trash size={16} color='white' />
                                    <span className='text-sm'>{t('setting.delete')}</span>
                                </div>
                            </Button>
                            <Button
                                onClick={handleCancelEdit}
                                className='bg-gray-500 text-white flex-1'
                            >
                                <span className='text-sm'>{t('setting.cancel')}</span>
                            </Button>
                        </div>
                    </div>
                ) : (
                    <Button
                        onClick={handleAddImage}
                        className='bg-[#ECEEF5] text-black w-full'
                        disabled={!imageSrc || isUploading}
                        loading={isLoading || isUploading}
                    >
                        <div className='flex justify-center items-center gap-2'>
                            <Add size={24} color='black' />
                            <span>{t('setting.add_image')}</span>
                        </div>
                    </Button>
                )}
            </div>
        </div>
    )
}

export default ImageSideBar