import { FC, useState, useEffect } from 'react'
import { useTranslation } from 'react-i18next'
import UploadBoxDraggble from '@/components/UploadBoxDraggble';
import ColorPicker from '@/components/ColorPicker';
import { usePersonalityStore } from '../store/Store';
import { SectionItemType, BackgroundSize, BackgroundPosition } from '../types/Types';
import Select from '@/components/Select';
import Input from '@/components/Input';
import { Checkbox } from '@/components/ui/checkbox';
import { useSingleUpload } from '../hooks/usePersonalityData';
import { toast } from '@/components/Toast';
import Button from '@/components/Button';
import { Trash } from 'iconsax-react';

const SettingSideBar: FC = () => {
    const { t } = useTranslation()
    const { activeSection, setColumnsCount, updateActiveItem, data, activeItemIndex, removeSection, setSectionPadding, setSectionHeight, setSectionBorder } = usePersonalityStore()
    const [color, setColor] = useState("#aabbcc");
    const [backgroundSize, setBackgroundSize] = useState<BackgroundSize>(BackgroundSize.COVER)
    const [backgroundPosition, setBackgroundPosition] = useState<BackgroundPosition>(BackgroundPosition.CENTER)
    const [isUploading, setIsUploading] = useState<boolean>(false)
    const [backgroundWidth, setBackgroundWidth] = useState<string>('auto')
    const [backgroundHeight, setBackgroundHeight] = useState<string>('auto')
    const [sectionPadding, setSectionPaddingState] = useState<string>('0px')
    const [sectionHeight, setSectionHeightState] = useState<string>('123px')
    const [borderWidth, setBorderWidth] = useState<string>('0px')
    const [borderColor, setBorderColor] = useState<string>('#E5E7EB')
    const [borderStyle, setBorderStyle] = useState<'solid' | 'dashed' | 'dotted' | 'none'>('solid')
    const [borderSides, setBorderSides] = useState<('top' | 'bottom' | 'left' | 'right')[]>(['top', 'bottom', 'left', 'right'])

    const { mutateAsync: singleUpload } = useSingleUpload()

    // تشخیص background size بر اساس style موجود
    const getCurrentBackgroundSizeType = (style?: SectionItemType['style']) => {
        if (!style) return BackgroundSize.COVER

        const bgSize = style.backgroundSize
        const bgRepeat = style.backgroundRepeat

        if (bgSize === 'cover') return BackgroundSize.COVER
        if (bgSize === 'contain') return BackgroundSize.CONTAIN
        if (bgSize === 'auto' || !bgSize) {
            if (bgRepeat === 'round') return BackgroundSize.ROUND
        }
        // اگر مقدار backgroundSize شامل دو مقدار باشد (مثلاً "100px 200px") آن را سفارشی در نظر بگیر
        if (typeof bgSize === 'string' && /\s+/.test(bgSize)) return BackgroundSize.CUSTOM
        // اگر مقدار دارای واحد باشد نیز سفارشی است
        if (typeof bgSize === 'string' && /(px|%|rem|em|vh|vw)/.test(bgSize)) return BackgroundSize.CUSTOM
        return BackgroundSize.COVER
    }

    // تشخیص موقعیت background بر اساس style موجود
    const getCurrentBackgroundPosition = (style?: SectionItemType['style']) => {
        if (!style?.backgroundPosition) return BackgroundPosition.CENTER
        return Object.values(BackgroundPosition).find(pos => pos === style.backgroundPosition) || BackgroundPosition.CENTER
    }

    // به‌روزرسانی state وقتی activeSection یا activeItem تغییر می‌کند
    useEffect(() => {
        if (activeSection && data[activeSection as keyof typeof data]) {
            const currentSection = data[activeSection as keyof typeof data]
            const currentItem = currentSection?.items[activeItemIndex]

            // بروزرسانی background settings
            if (currentItem?.style) {
                const currentType = getCurrentBackgroundSizeType(currentItem.style)
                const currentPosition = getCurrentBackgroundPosition(currentItem.style)
                setBackgroundSize(currentType)
                setBackgroundPosition(currentPosition)

                // تنظیم مقدار اولیه عرض و ارتفاع بک‌گراند در حالت سفارشی
                const bgSize = currentItem.style.backgroundSize
                if (currentType === BackgroundSize.CUSTOM && typeof bgSize === 'string') {
                    const parts = bgSize.split(/\s+/)
                    setBackgroundWidth(parts[0] || 'auto')
                    setBackgroundHeight(parts[1] || 'auto')
                } else {
                    setBackgroundWidth('auto')
                    setBackgroundHeight('auto')
                }
            }

            // بروزرسانی section padding, height و border
            setSectionPaddingState(currentSection?.padding || '0px')

            // مقدار پیش‌فرض height بر اساس نوع سکشن
            const defaultHeight = currentSection?.isContent ? '246px' : '123px'
            setSectionHeightState(currentSection?.height || defaultHeight)

            setBorderWidth(currentSection?.border?.width || '0px')
            setBorderColor(currentSection?.border?.color || '#E5E7EB')
            setBorderStyle(currentSection?.border?.style || 'solid')
            setBorderSides(currentSection?.border?.sides || ['top', 'bottom', 'left', 'right'])
        }
    }, [activeSection, activeItemIndex, data])

    const handleColumnClick = (columns: number) => {
        if (activeSection) {
            if (data[activeSection]?.isContent && columns > 1) {
                toast('این بخش فقط می تواند یک ستون داشته باشد', 'error')
                return
            }
            setColumnsCount(activeSection, columns);
        }
    }



    const handleRemoveSection = () => {
        if (activeSection && !data[activeSection]?.isContent) {
            removeSection(activeSection)
            toast('سکشن با موفقیت حذف شد', 'success')
        } else {
            toast('نمی‌توانید سکشن محتوا را حذف کنید', 'error')
        }
    }

    const handleColorChange = (color: string) => {
        setColor(color)
        updateActiveItem({ backgroundColor: color })
    }

    const handleSectionPaddingChange = (padding: string) => {
        if (activeSection) {
            setSectionPaddingState(padding)
            setSectionPadding(activeSection, padding)
        }
    }

    const handleSectionHeightChange = (height: string) => {
        if (activeSection) {
            setSectionHeightState(height)
            setSectionHeight(activeSection, height)
        }
    }

    const handleBorderWidthChange = (width: string) => {
        if (activeSection) {
            setBorderWidth(width)
            setSectionBorder(activeSection, {
                width,
                color: borderColor,
                style: borderStyle,
                sides: borderSides
            })
        }
    }

    const handleBorderColorChange = (color: string) => {
        if (activeSection) {
            setBorderColor(color)
            setSectionBorder(activeSection, {
                width: borderWidth,
                color,
                style: borderStyle,
                sides: borderSides
            })
        }
    }

    const handleBorderStyleChange = (style: 'solid' | 'dashed' | 'dotted' | 'none') => {
        if (activeSection) {
            setBorderStyle(style)
            setSectionBorder(activeSection, {
                width: borderWidth,
                color: borderColor,
                style,
                sides: borderSides
            })
        }
    }

    const handleBorderSidesChange = (side: 'top' | 'bottom' | 'left' | 'right') => {
        if (activeSection) {
            const newSides = borderSides.includes(side)
                ? borderSides.filter(s => s !== side)
                : [...borderSides, side]

            setBorderSides(newSides)
            setSectionBorder(activeSection, {
                width: borderWidth,
                color: borderColor,
                style: borderStyle,
                sides: newSides
            })
        }
    }

    const handleUploadBackground = async (file: File[]) => {
        if (activeSection && file.length > 0) {
            setIsUploading(true)

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

                if (imageUrl) {
                    const currentItem = data[activeSection as keyof typeof data]?.items[activeItemIndex]
                    const finalBackgroundSize = currentItem?.style?.backgroundSize ?? getBackgroundSize(backgroundSize)
                    const finalBackgroundRepeat = currentItem?.style?.backgroundRepeat ?? getBackgroundRepeat(backgroundSize)
                    const finalBackgroundPosition = currentItem?.style?.backgroundPosition ?? backgroundPosition

                    updateActiveItem({
                        backgroundImage: imageUrl,
                        style: {
                            ...currentItem?.style,
                            backgroundSize: finalBackgroundSize,
                            backgroundRepeat: finalBackgroundRepeat,
                            backgroundPosition: finalBackgroundPosition
                        }
                    })
                    toast('تصویر پس‌زمینه با موفقیت آپلود شد', 'success')
                }
            } catch (error) {
                console.error('Error uploading background image:', error)
                toast('خطا در آپلود تصویر پس‌زمینه، از فایل محلی استفاده شد', 'error')

                // Fallback to object URL if upload fails
                const imageUrl = URL.createObjectURL(file[0])

                const currentItem = data[activeSection as keyof typeof data]?.items[activeItemIndex]
                const finalBackgroundSize = currentItem?.style?.backgroundSize ?? getBackgroundSize(backgroundSize)
                const finalBackgroundRepeat = currentItem?.style?.backgroundRepeat ?? getBackgroundRepeat(backgroundSize)
                const finalBackgroundPosition = currentItem?.style?.backgroundPosition ?? backgroundPosition

                updateActiveItem({
                    backgroundImage: imageUrl,
                    style: {
                        ...currentItem?.style,
                        backgroundSize: finalBackgroundSize,
                        backgroundRepeat: finalBackgroundRepeat,
                        backgroundPosition: finalBackgroundPosition
                    }
                })
            } finally {
                setIsUploading(false)
            }
        }
    }

    const getBackgroundRepeat = (size: BackgroundSize) => {
        switch (size) {
            case BackgroundSize.ROUND:
                return 'round'
            case BackgroundSize.COVER:
            case BackgroundSize.CONTAIN:
            default:
                return 'no-repeat'
        }
    }

    const getBackgroundSize = (size: BackgroundSize) => {
        switch (size) {
            case BackgroundSize.COVER:
                return 'cover'
            case BackgroundSize.CONTAIN:
                return 'contain'
            case BackgroundSize.ROUND:
                return 'auto'
            case BackgroundSize.CUSTOM:
                return `${backgroundWidth || 'auto'} ${backgroundHeight || 'auto'}`
            default:
                return 'cover'
        }
    }

    const sizeOptions = [
        { label: 'کاور', value: BackgroundSize.COVER },
        { label: 'در مقیاس', value: BackgroundSize.CONTAIN },
        { label: 'تکرار گرد', value: BackgroundSize.ROUND },
        { label: 'سفارشی', value: BackgroundSize.CUSTOM }
    ]

    const positionOptions = [
        { label: 'وسط', value: BackgroundPosition.CENTER },
        { label: 'بالا چپ', value: BackgroundPosition.TOP_LEFT },
        { label: 'بالا وسط', value: BackgroundPosition.TOP_CENTER },
        { label: 'بالا راست', value: BackgroundPosition.TOP_RIGHT },
        { label: 'وسط چپ', value: BackgroundPosition.CENTER_LEFT },
        { label: 'وسط راست', value: BackgroundPosition.CENTER_RIGHT },
        { label: 'پایین چپ', value: BackgroundPosition.BOTTOM_LEFT },
        { label: 'پایین وسط', value: BackgroundPosition.BOTTOM_CENTER },
        { label: 'پایین راست', value: BackgroundPosition.BOTTOM_RIGHT }
    ]

    const borderStyleOptions = [
        { label: 'ساده', value: 'solid' },
        { label: 'خط‌چین', value: 'dashed' },
        { label: 'نقطه‌چین', value: 'dotted' },
        { label: 'بدون حاشیه', value: 'none' }
    ]

    if (!activeSection) {
        return (
            <div className='text-center text-gray-500 mt-8'>
                {t('setting.select_section')}
            </div>
        )
    }
    console.log(data[activeSection]);


    return (
        <div>
            <div className='text-lg'>{t('setting.setting')}</div>

            {/* Section Delete */}
            {activeSection && !data[activeSection]?.isContent && (
                <div className='mt-6 border-b border-gray-200 pb-6'>
                    <Button
                        onClick={handleRemoveSection}
                        variant='secondary'
                        className='w-full flex items-center justify-center gap-2 !text-red-600 !border-red-600 hover:!bg-red-50'
                    >
                        <Trash size={16} />
                        حذف سکشن فعلی
                    </Button>
                </div>
            )}

            <div className='flex h-[51px] gap-5 mt-6'>
                <div
                    className={`w-[102px] h-full bg-[#EAECF4] transition-colors ${isUploading ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer hover:bg-[#d1d5db]'}`}
                    onClick={() => !isUploading && handleColumnClick(1)}
                ></div>
                <div
                    className={`w-[102px] h-full flex gap-1 group transition-colors ${isUploading ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer'}`}
                    onClick={() => !isUploading && handleColumnClick(2)}
                >
                    <div className={`flex-1 bg-[#EAECF4] transition-colors ${!isUploading && 'group-hover:bg-[#d1d5db]'}`}></div>
                    <div className={`flex-1 bg-[#EAECF4] transition-colors ${!isUploading && 'group-hover:bg-[#d1d5db]'}`}></div>
                </div>
            </div>

            <div className='flex h-[51px] gap-5 mt-5'>
                <div
                    className={`w-[102px] h-full flex gap-1 group transition-colors ${isUploading ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer'}`}
                    onClick={() => !isUploading && handleColumnClick(3)}
                >
                    <div className={`flex-1 bg-[#EAECF4] transition-colors ${!isUploading && 'group-hover:bg-[#d1d5db]'}`}></div>
                    <div className={`flex-1 bg-[#EAECF4] transition-colors ${!isUploading && 'group-hover:bg-[#d1d5db]'}`}></div>
                    <div className={`flex-1 bg-[#EAECF4] transition-colors ${!isUploading && 'group-hover:bg-[#d1d5db]'}`}></div>
                </div>
                <div
                    className={`w-[102px] h-full flex gap-1 group transition-colors ${isUploading ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer'}`}
                    onClick={() => !isUploading && handleColumnClick(4)}
                >
                    <div className={`flex-1 bg-[#EAECF4] transition-colors ${!isUploading && 'group-hover:bg-[#d1d5db]'}`}></div>
                    <div className={`flex-1 bg-[#EAECF4] transition-colors ${!isUploading && 'group-hover:bg-[#d1d5db]'}`}></div>
                    <div className={`flex-1 bg-[#EAECF4] transition-colors ${!isUploading && 'group-hover:bg-[#d1d5db]'}`}></div>
                    <div className={`flex-1 bg-[#EAECF4] transition-colors ${!isUploading && 'group-hover:bg-[#d1d5db]'}`}></div>
                </div>
            </div>

            <div className='mt-5'>
                <ColorPicker
                    label={t('setting.background')}
                    defaultColor={color}
                    changeColor={handleColorChange}
                />
            </div>

            <div className='mt-5'>
                <UploadBoxDraggble
                    label={isUploading ? 'در حال آپلود...' : t('setting.upload_background')}
                    onChange={handleUploadBackground}
                    preview={data?.[activeSection]?.items?.[activeItemIndex]?.backgroundImage ? [data?.[activeSection]?.items?.[activeItemIndex]?.backgroundImage as string] : undefined}
                    onDelete={() => {
                        updateActiveItem({
                            backgroundImage: undefined
                        })
                    }}
                />
            </div>

            <div className='mt-5'>
                <Select
                    items={sizeOptions}
                    label={t('setting.size')}
                    value={backgroundSize}
                    onChange={(e) => {
                        const newSize = e.target.value as BackgroundSize
                        setBackgroundSize(newSize)

                        const currentItem = activeSection ? data[activeSection as keyof typeof data]?.items[activeItemIndex] : null

                        // اگر سفارشی انتخاب شد و هنوز مقدار width/height تعیین نشده، مقادیر پیش‌فرض را ست کن
                        if (newSize === BackgroundSize.CUSTOM) {
                            const width = backgroundWidth || 'auto'
                            const height = backgroundHeight || 'auto'
                            setBackgroundWidth(width)
                            setBackgroundHeight(height)
                        }

                        updateActiveItem({
                            style: {
                                ...currentItem?.style,
                                backgroundSize: getBackgroundSize(newSize),
                                backgroundRepeat: getBackgroundRepeat(newSize),
                                backgroundPosition: backgroundPosition
                            }
                        })
                    }}
                    placeholder={t('setting.size')}
                    disabled={isUploading}
                />
            </div>

            {backgroundSize === BackgroundSize.CUSTOM && (
                <div className='mt-5 grid grid-cols-2 gap-3'>
                    <Input
                        label="عرض بک‌گراند"
                        value={backgroundWidth}
                        onChange={(e) => {
                            const value = e.target.value
                            setBackgroundWidth(value)
                            const currentItem = activeSection ? data[activeSection as keyof typeof data]?.items[activeItemIndex] : null
                            updateActiveItem({
                                style: {
                                    ...currentItem?.style,
                                    backgroundSize: `${value || 'auto'} ${backgroundHeight || 'auto'}`
                                }
                            })
                        }}
                        placeholder="مثال: 100px یا 50%"
                        disabled={isUploading}
                    />
                    <Input
                        label="ارتفاع بک‌گراند"
                        value={backgroundHeight}
                        onChange={(e) => {
                            const value = e.target.value
                            setBackgroundHeight(value)
                            const currentItem = activeSection ? data[activeSection as keyof typeof data]?.items[activeItemIndex] : null
                            updateActiveItem({
                                style: {
                                    ...currentItem?.style,
                                    backgroundSize: `${backgroundWidth || 'auto'} ${value || 'auto'}`,
                                    backgroundRepeat: getBackgroundRepeat(BackgroundSize.CUSTOM)
                                }
                            })
                        }}
                        placeholder="مثال: 200px یا auto"
                        disabled={isUploading}
                    />
                </div>
            )}

            <div className='mt-5'>
                <Select
                    items={positionOptions}
                    label={t('setting.position')}
                    value={backgroundPosition}
                    onChange={(e) => {
                        const newPosition = e.target.value as BackgroundPosition
                        setBackgroundPosition(newPosition)

                        const currentItem = activeSection ? data[activeSection as keyof typeof data]?.items[activeItemIndex] : null
                        updateActiveItem({
                            style: {
                                ...currentItem?.style,
                                backgroundPosition: newPosition
                            }
                        })
                    }}
                    placeholder={t('setting.position')}
                    disabled={isUploading}
                />
            </div>

            {/* Section Padding Control */}
            <div className='mt-5'>
                <Input
                    label="فاصله داخلی سکشن"
                    value={sectionPadding}
                    onChange={(e) => handleSectionPaddingChange(e.target.value)}
                    placeholder="مثال: 20px"
                    disabled={isUploading}
                />
            </div>

            {/* Section Height Control */}
            <div className='mt-5'>
                <Input
                    label="ارتفاع سکشن"
                    value={sectionHeight}
                    onChange={(e) => handleSectionHeightChange(e.target.value)}
                    placeholder="مثال: 123px"
                    disabled={isUploading}
                />
            </div>

            {/* Border Controls */}
            <div className='mt-5 border-t border-gray-200 pt-5'>
                <div className='text-sm font-medium mb-3'>تنظیمات حاشیه</div>

                <div className='mt-3'>
                    <Input
                        label="ضخامت حاشیه"
                        value={borderWidth}
                        onChange={(e) => handleBorderWidthChange(e.target.value)}
                        placeholder="مثال: 1px"
                        disabled={isUploading}
                    />
                </div>

                <div className='mt-3'>
                    <ColorPicker
                        label="رنگ حاشیه"
                        defaultColor={borderColor}
                        changeColor={handleBorderColorChange}
                    />
                </div>

                <div className='mt-3'>
                    <Select
                        items={borderStyleOptions}
                        label="نوع حاشیه"
                        value={borderStyle}
                        onChange={(e) => handleBorderStyleChange(e.target.value as 'solid' | 'dashed' | 'dotted' | 'none')}
                        placeholder="انتخاب نوع حاشیه"
                        disabled={isUploading}
                    />
                </div>

                <div className='mt-3'>
                    <div className='text-sm font-medium mb-2'>جهات حاشیه</div>
                    <div className='grid grid-cols-2 gap-2'>
                        {[
                            { value: 'top', label: 'بالا' },
                            { value: 'bottom', label: 'پایین' },
                            { value: 'left', label: 'چپ' },
                            { value: 'right', label: 'راست' }
                        ].map(side => (
                            <div key={side.value} className='flex items-center space-x-2 rtl:space-x-reverse'>
                                <Checkbox
                                    id={`border-${side.value}`}
                                    checked={borderSides.includes(side.value as 'top' | 'bottom' | 'left' | 'right')}
                                    onCheckedChange={() => handleBorderSidesChange(side.value as 'top' | 'bottom' | 'left' | 'right')}
                                    disabled={isUploading}
                                />
                                <label htmlFor={`border-${side.value}`} className='text-sm'>{side.label}</label>
                            </div>
                        ))}
                    </div>
                </div>
            </div>
        </div>
    )
}

export default SettingSideBar