import Button from '@/components/Button';
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 ColorPicker from '@/components/ColorPicker';
import { HorizontalAlignment, VerticalAlignment, ElementType } from '../types/Types';
import Textarea from '@/components/Textarea';
import Input from '@/components/Input';
import Select from '@/components/Select';

const TextSidebar: FC = () => {

    const { t } = useTranslation()
    const [value, setValue] = useState('');
    const [color, setColor] = useState('#000');
    const [fontSize, setFontSize] = useState(14);
    const [fontWeight, setFontWeight] = useState('400');
    const [horizontalPosition, setHorizontalPosition] = useState<HorizontalAlignment>(HorizontalAlignment.CENTER);
    const [verticalPosition, setVerticalPosition] = useState<VerticalAlignment>(VerticalAlignment.MIDDLE);

    const {
        addTextToActiveItem,
        selectedElement,
        setSelectedElement,
        data,
        updateText,
        deleteText
    } = usePersonalityStore();

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

    // Load selected text 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 text = item.texts?.find(t => t.id === selectedElement.elementId);

                if (text) {
                    setValue(text.text);
                    setColor(text.color || '#000');
                    setFontSize(text.fontSize || 14);
                    setFontWeight((text.fontWeight || 400).toString());
                    setHorizontalPosition(text.alignment || HorizontalAlignment.CENTER);
                    setVerticalPosition(text.verticalAlignment || VerticalAlignment.MIDDLE);
                } else {
                    console.error('Text element not found');
                }
            } catch (error) {
                console.error('Error loading text data:', error);
            }
        } else {
            // Reset form when not in edit mode
            setValue('');
            setColor('#000');
            setFontSize(14);
            setFontWeight('400');
            setHorizontalPosition(HorizontalAlignment.CENTER);
            setVerticalPosition(VerticalAlignment.MIDDLE);
        }
    }, [selectedElement, isEditMode, data]);

    const handleAddText = () => {
        if (value.trim()) {
            addTextToActiveItem({
                text: value,
                color: color,
                fontSize: fontSize,
                fontWeight: parseInt(fontWeight),
                verticalAlignment: verticalPosition,
                alignment: horizontalPosition,
            });

            setValue('');
            setColor('#000');
            setFontSize(14);
            setFontWeight('400');
            setHorizontalPosition(HorizontalAlignment.CENTER);
            setVerticalPosition(VerticalAlignment.MIDDLE);
        }
    }

    const handleUpdateText = () => {
        if (selectedElement && value.trim()) {
            updateText(
                selectedElement.sectionKey,
                selectedElement.itemId,
                selectedElement.elementId,
                {
                    text: value,
                    color: color,
                    fontSize: fontSize,
                    fontWeight: parseInt(fontWeight),
                    alignment: horizontalPosition,
                    verticalAlignment: verticalPosition,
                }
            );

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

    const handleDeleteText = () => {
        if (selectedElement) {
            deleteText(
                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.text')}
                {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'>
                {/* <ReactQuill
                    modules={{
                        toolbar: [
                            [{ header: '1' }, { header: '2' }, { font: [] }],
                            [{ list: 'ordered' }, { list: 'bullet' }],
                            ['bold', 'italic', 'underline'],
                            ['link', 'image'],
                            [{ align: [] }],
                            ['clean']
                        ]
                    }}
                    theme="snow"
                    value={value}
                    onChange={handleChange}
                    style={{ minHeight: '120px' }}
                    className='text-sm'
                /> */}
                <Textarea
                    placeholder={t('setting.text')}
                    value={value}
                    onChange={(e) => setValue(e.target.value)}
                    className='text-sm border border-border'
                />
            </div>

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

            <div className='mt-5 flex gap-4'>
                <div className='flex-1'>
                    <label className='text-sm block mb-2'>
                        {t('setting.font_size')}
                    </label>
                    <Input
                        max="72"
                        value={fontSize.toString()}
                        onChange={(e) => setFontSize(+e.target.value || 0)}
                        onBlur={(e) => {
                            if (fontSize === 0 || e.target.value === '') {
                                setFontSize(14);
                            }
                        }}
                        className='text-sm'
                        placeholder="14"
                    />
                </div>
                <div className='flex-1'>
                    <Select
                        label={t('setting.font_weight')}
                        value={fontWeight}
                        onChange={(e) => setFontWeight(e.target.value)}
                        items={[
                            { value: '300', label: 'کم‌عرض' },
                            { value: '400', label: 'معمولی' },
                            { value: '500', label: 'متوسط' },
                            { value: '600', label: 'نیمه‌ضخیم' },
                            { value: '700', label: 'ضخیم' },
                            { value: '800', label: 'فوق‌ضخیم' },
                        ]}
                        className='text-sm'
                    />
                </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={() => setHorizontalPosition(HorizontalAlignment.RIGHT)}
                            className='cursor-pointer'
                        >
                            <AlignRight size={20} color={horizontalPosition === HorizontalAlignment.RIGHT ? '#0038FF' : '#000'} />
                        </div>
                        <div
                            onClick={() => setHorizontalPosition(HorizontalAlignment.CENTER)}
                            className='cursor-pointer'
                        >
                            <AlignVertically size={20} color={horizontalPosition === HorizontalAlignment.CENTER ? '#0038FF' : '#000'} />
                        </div>
                        <div
                            onClick={() => setHorizontalPosition(HorizontalAlignment.LEFT)}
                            className='cursor-pointer'
                        >
                            <AlignLeft size={20} color={horizontalPosition === 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={() => setVerticalPosition(VerticalAlignment.TOP)}
                            className='cursor-pointer'
                        >
                            <AlignTop size={20} color={verticalPosition === VerticalAlignment.TOP ? '#0038FF' : '#000'} />
                        </div>
                        <div
                            onClick={() => setVerticalPosition(VerticalAlignment.MIDDLE)}
                            className='cursor-pointer'
                        >
                            <AlignHorizontally size={20} color={verticalPosition === VerticalAlignment.MIDDLE ? '#0038FF' : '#000'} />
                        </div>
                        <div
                            onClick={() => setVerticalPosition(VerticalAlignment.BOTTOM)}
                            className='cursor-pointer'
                        >
                            <AlignBottom size={20} color={verticalPosition === VerticalAlignment.BOTTOM ? '#0038FF' : '#000'} />
                        </div>
                    </div>
                </div>
            </div>

            <div className='mt-7'>
                {isEditMode ? (
                    <div className='space-y-3'>
                        <Button
                            onClick={handleUpdateText}
                            disabled={!value.trim()}
                        >
                            <div className='flex justify-center items-center gap-2'>
                                <Edit size={18} color='white' />
                                <span>{t('setting.update_text')}</span>
                            </div>
                        </Button>
                        <div className='flex gap-2'>
                            <Button
                                onClick={handleDeleteText}
                                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={handleAddText}
                        className='bg-[#ECEEF5] text-black w-full'
                        disabled={!value.trim()}
                    >
                        <div className='flex justify-center items-center gap-2'>
                            <Add size={24} color='black' />
                            <span>{t('setting.add_text')}</span>
                        </div>
                    </Button>
                )}
            </div>

        </div>
    )
}

export default TextSidebar