import Button from '@/components/Button'
import ColorPicker from '@/components/ColorPicker'
import Input from '@/components/Input'
import Select from '@/components/Select'
import { Checkbox } from '@/components/ui/checkbox'
import { AlignRight, AlignBottom, AlignHorizontally, AlignLeft, AlignTop, AlignVertically, Link2, Add, Edit, Trash } from 'iconsax-react'
import { FC, useState, useEffect } from 'react'
import { useTranslation } from 'react-i18next'
import { usePersonalityStore } from '../store/Store'
import { ButtonSize, HorizontalAlignment, VerticalAlignment, ElementType } from '../types/Types'

const ButtonSidebar: FC = () => {

    const { t } = useTranslation()
    const {
        addButtonToActiveItem,
        selectedElement,
        setSelectedElement,
        data,
        updateButton,
        deleteButton
    } = usePersonalityStore()

    const [buttonText, setButtonText] = useState<string>('')
    const [buttonLink, setButtonLink] = useState<string>('')
    const [buttonSize, setButtonSize] = useState<ButtonSize>(ButtonSize.MEDIUM)
    const [isBorder, setIsBorder] = useState<boolean>(false)
    const [borderSize, setBorderSize] = useState<number>(1)
    const [textColor, setTextColor] = useState<string>('#fff')
    const [backgroundColor, setBackgroundColor] = useState<string>('#000')
    const [borderColor, setBorderColor] = useState<string>('#fff')
    const [horizontalAlignment, setHorizontalAlignment] = useState<HorizontalAlignment>(HorizontalAlignment.CENTER)
    const [verticalAlignment, setVerticalAlignment] = useState<VerticalAlignment>(VerticalAlignment.MIDDLE)

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

    // Load selected button 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 button = item.buttons?.find(b => b.id === selectedElement.elementId);

                if (button) {
                    setButtonText(button.text);
                    setButtonLink(button.link);
                    setButtonSize(button.size);
                    setIsBorder(button.isBorder);
                    setBorderSize(button.borderSize);
                    setTextColor(button.textColor);
                    setBackgroundColor(button.backgroundColor);
                    setBorderColor(button.borderColor);
                    setHorizontalAlignment(button.alignment || HorizontalAlignment.CENTER);
                    setVerticalAlignment(button.verticalAlignment || VerticalAlignment.MIDDLE);
                } else {
                    console.error('Button element not found');
                }
            } catch (error) {
                console.error('Error loading button data:', error);
            }
        } else {
            // Reset form when not in edit mode
            setButtonText('')
            setButtonLink('')
            setButtonSize(ButtonSize.MEDIUM)
            setIsBorder(false)
            setBorderSize(1)
            setTextColor('#fff')
            setBackgroundColor('#000')
            setBorderColor('#fff')
            setHorizontalAlignment(HorizontalAlignment.CENTER)
            setVerticalAlignment(VerticalAlignment.MIDDLE)
        }
    }, [selectedElement, isEditMode, data]);

    const sizeOptions = [
        { label: 'کوچک', value: ButtonSize.SMALL },
        { label: 'متوسط', value: ButtonSize.MEDIUM },
        { label: 'بزرگ', value: ButtonSize.LARGE }
    ]

    const handleAddButton = () => {
        addButtonToActiveItem({
            text: buttonText,
            link: buttonLink,
            size: buttonSize,
            isBorder,
            borderSize,
            textColor,
            backgroundColor,
            borderColor,
            alignment: horizontalAlignment,
            verticalAlignment,
        })

        // Reset form after adding
        setButtonText('')
        setButtonLink('')
        setButtonSize(ButtonSize.MEDIUM)
        setIsBorder(false)
        setBorderSize(1)
        setTextColor('#fff')
        setBackgroundColor('#000')
        setBorderColor('#fff')
        setHorizontalAlignment(HorizontalAlignment.CENTER)
        setVerticalAlignment(VerticalAlignment.MIDDLE)
    }

    const handleUpdateButton = () => {
        if (selectedElement && buttonText.trim()) {
            updateButton(
                selectedElement.sectionKey,
                selectedElement.itemId,
                selectedElement.elementId,
                {
                    text: buttonText,
                    link: buttonLink,
                    size: buttonSize,
                    isBorder,
                    borderSize,
                    textColor,
                    backgroundColor,
                    borderColor,
                    alignment: horizontalAlignment,
                    verticalAlignment,
                }
            );

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

    const handleDeleteButton = () => {
        if (selectedElement) {
            deleteButton(
                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.button')}
                {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'>
                <Input
                    label={t('setting.button_text')}
                    value={buttonText}
                    onChange={(e) => setButtonText(e.target.value)}
                />
            </div>

            <div className='mt-5'>
                <Input
                    label={t('setting.button_link')}
                    value={buttonLink}
                    onChange={(e) => setButtonLink(e.target.value)}
                    endIcon={<Link2 size={18} color='#888' />}
                />
            </div>

            <div className='mt-5'>
                <Select
                    label={t('setting.size')}
                    items={sizeOptions}
                    value={buttonSize}
                    onChange={(e) => setButtonSize(e.target.value as ButtonSize)}
                    placeholder={t('setting.select')}
                />
            </div>

            <div className='mt-5 flex gap-2 items-center text-sm'>
                <Checkbox
                    checked={isBorder}
                    onCheckedChange={() => setIsBorder(!isBorder)}
                />
                <div>{t('setting.border')}</div>
            </div>

            {
                isBorder &&
                <div className='mt-5'>
                    <Input
                        type='number'
                        label={t('setting.border')}
                        value={borderSize.toString()}
                        onChange={(e) => setBorderSize(Number(e.target.value))}
                    />
                </div>
            }

            <div className='mt-5'>
                <ColorPicker
                    label={t('setting.text_color')}
                    defaultColor={textColor}
                    changeColor={setTextColor}
                />
            </div>

            <div className='mt-5'>
                <ColorPicker
                    label={t('setting.background_color')}
                    defaultColor={backgroundColor}
                    changeColor={setBackgroundColor}
                />
            </div>

            <div className='mt-5'>
                <ColorPicker
                    label={t('setting.border_color')}
                    defaultColor={borderColor}
                    changeColor={setBorderColor}
                />
            </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.TOP)}
                        >
                            <AlignTop size={20} color={verticalAlignment === VerticalAlignment.TOP ? '#0038FF' : '#000'} />
                        </div>
                        <div
                            onClick={() => setVerticalAlignment(VerticalAlignment.MIDDLE)}
                        >
                            <AlignHorizontally size={20} color={verticalAlignment === VerticalAlignment.MIDDLE ? '#0038FF' : '#000'} />
                        </div>
                        <div
                            onClick={() => setVerticalAlignment(VerticalAlignment.BOTTOM)}
                        >
                            <AlignBottom size={20} color={verticalAlignment === VerticalAlignment.BOTTOM ? '#0038FF' : '#000'} />
                        </div>
                    </div>
                </div>
            </div>

            <div className='mt-7'>
                {isEditMode ? (
                    <div className='space-y-3'>
                        <Button
                            onClick={handleUpdateButton}
                            className='bg-[#0038FF] text-white w-full'
                            disabled={!buttonText.trim()}
                        >
                            <div className='flex justify-center items-center gap-2'>
                                <Edit size={18} color='white' />
                                <span>{t('setting.update_button')}</span>
                            </div>
                        </Button>
                        <div className='flex gap-2'>
                            <Button
                                onClick={handleDeleteButton}
                                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={handleAddButton}
                        className='bg-[#ECEEF5] text-black w-full'
                        disabled={!buttonText.trim()}
                    >
                        <div className='flex justify-center items-center gap-2'>
                            <Add size={24} color='black' />
                            <span>{t('setting.add_button')}</span>
                        </div>
                    </Button>
                )}
            </div>

        </div>
    )
}

export default ButtonSidebar