import { FC } from 'react'
import { usePersonalityStore } from '../store/Store'
import { useTranslation } from 'react-i18next'
import { AddCircle } from 'iconsax-react'
import TextRenderer from './TextRenderer'
import ButtonRenderer from './ButtonRenderer'
import ImageRenderer from './ImageRenderer'
import SocialRenderer from './SocialRenderer'
import { SectionName, VerticalAlignment, HorizontalAlignment } from '../types/Types'

const ContentSection: FC = () => {

    const { t } = useTranslation()
    const { activeSection, activeItemIndex, data, setActiveSection, setActiveItemIndex } = usePersonalityStore()

    // Early return if data is not available
    if (!data || !data.content) {
        return (
            <tr>
                <td style={{ height: '246px', textAlign: 'right', verticalAlign: 'middle', paddingTop: '0px' }}>
                    <div>در حال بارگذاری...</div>
                </td>
            </tr>
        )
    }

    const handleSectionClick = (section: SectionName, e: React.MouseEvent) => {

        // اگر کلیک روی فضای خالی باشد (نه روی content elements)
        const target = e.target as HTMLElement;
        const isClickOnContent = target.closest('[data-element-type]') !== null;

        if (!isClickOnContent) {
            setActiveSection(section)
        }
    }

    const handleItemClick = (index: number, e: React.MouseEvent) => {

        // Check if click is on a content element (text, button, image, social)
        const target = e.target as HTMLElement;
        const isClickOnContent = target.closest('[data-element-type]') !== null;

        // Only select column if not clicking on content elements
        if (!isClickOnContent) {


            e.stopPropagation()

            // Only set active section if we're not already in content section
            if (activeSection !== SectionName.CONTENT) {
                setActiveSection(SectionName.CONTENT)
            }

            // Always set the active item index
            setActiveItemIndex(index)
        }
    }

    // تابع‌های helper برای تعیین alignment دکمه‌ها
    const getButtonHorizontalAlign = (button?: { alignment?: HorizontalAlignment }) => {
        if (!button || !button.alignment) return 'center'
        switch (button.alignment) {
            case HorizontalAlignment.LEFT:
                return 'left'
            case HorizontalAlignment.RIGHT:
                return 'right'
            case HorizontalAlignment.CENTER:
            default:
                return 'center'
        }
    }

    const getButtonVerticalAlign = (button?: { verticalAlignment?: VerticalAlignment }) => {
        if (!button || !button.verticalAlignment) return 'middle'
        switch (button.verticalAlignment) {
            case VerticalAlignment.TOP:
                return 'top'
            case VerticalAlignment.BOTTOM:
                return 'bottom'
            case VerticalAlignment.MIDDLE:
            default:
                return 'middle'
        }
    }

    return (
        <tr onClick={(e) => handleSectionClick(SectionName.CONTENT, e)}>
            <td style={{ paddingTop: '0px' }}>
                {
                    data.content.columnsCount > 0 ?
                        <table width="100%" cellPadding="0" cellSpacing="0" border={0}>
                            <tbody>
                                <tr>
                                    <td style={{
                                        padding: '10px',
                                        border: activeSection === SectionName.CONTENT ? '1px dashed #0038FF' : '1px dashed #E5E7EB',
                                        borderRadius: '24px',
                                        cursor: 'pointer'
                                    }}>
                                        <table width="100%" cellPadding="0" cellSpacing="0" border={0} style={{ tableLayout: 'fixed' }}>
                                            <tbody>
                                                <tr>
                                                    {
                                                        Array.from({ length: data.content.columnsCount }, (_, index) => {
                                                            const item = data.content.items[index];
                                                            const isActive = activeSection === SectionName.CONTENT && activeItemIndex === index;

                                                            return (
                                                                <>
                                                                    <td
                                                                        key={index}
                                                                        onClick={(e) => handleItemClick(index, e)}
                                                                        style={{
                                                                            width: `${100 / data.content.columnsCount}%`,
                                                                            height: '246px',
                                                                            border: isActive ? '1px dashed #0038FF' : '1px dashed #EAECF4',
                                                                            backgroundColor: item?.backgroundColor || '#ffffff',
                                                                            backgroundImage: item?.backgroundImage ? `url(${item.backgroundImage})` : 'none',
                                                                            backgroundSize: item?.style?.backgroundSize || 'cover',
                                                                            backgroundRepeat: item?.style?.backgroundRepeat || 'no-repeat',
                                                                            backgroundPosition: item?.style?.backgroundPosition || 'center',
                                                                            cursor: 'pointer',
                                                                            padding: '8px',
                                                                            verticalAlign: 'top',
                                                                            borderRadius: '8px',
                                                                            position: 'relative'
                                                                        }}
                                                                    >
                                                                        <table width="100%" cellPadding="0" cellSpacing="0" border={0} style={{
                                                                            borderCollapse: 'collapse',
                                                                            height: '246px'
                                                                        }}>
                                                                            <tbody>
                                                                                {/* اگر column خالی است */}
                                                                                {(!item?.texts || item.texts.length === 0) &&
                                                                                    (!item?.buttons || item.buttons.length === 0) &&
                                                                                    (!item?.images || item.images.length === 0) &&
                                                                                    (!item?.socials || item.socials.length === 0) ? (
                                                                                    <tr>
                                                                                        <td
                                                                                            width="100%"
                                                                                            height="246"
                                                                                            style={{
                                                                                                padding: '8px',
                                                                                                cursor: 'pointer'
                                                                                            }}
                                                                                            onClick={(e) => handleItemClick(index, e)}
                                                                                        >
                                                                                            {/* محتوای خالی برای columns خالی */}
                                                                                            <div style={{
                                                                                                margin: 0,
                                                                                                textAlign: 'right',
                                                                                                color: '#888',
                                                                                                fontSize: '14px'
                                                                                            }}>
                                                                                                {/* {'{{content}}'} */}
                                                                                            </div>
                                                                                        </td>
                                                                                    </tr>
                                                                                ) : (
                                                                                    <>
                                                                                        {/* اگر فقط دکمه داریم و متن نداریم */}
                                                                                        {(!item?.texts || item.texts.length === 0) && item?.buttons && item.buttons.length > 0 ? (
                                                                                            <tr>
                                                                                                <td
                                                                                                    width="100%"
                                                                                                    height="246"
                                                                                                    align={getButtonHorizontalAlign(item.buttons[0])}
                                                                                                    valign={getButtonVerticalAlign(item.buttons[0])}
                                                                                                    style={{
                                                                                                        padding: '8px'
                                                                                                    }}
                                                                                                >
                                                                                                    <div style={{
                                                                                                        margin: '0 0 10px 0',
                                                                                                        textAlign: 'right',
                                                                                                        color: '#888',
                                                                                                        fontSize: '14px'
                                                                                                    }}>
                                                                                                        {'{{content}}'}
                                                                                                    </div>
                                                                                                    <ButtonRenderer
                                                                                                        buttons={item.buttons}
                                                                                                        itemId={item?.id || ''}
                                                                                                        sectionKey="content"
                                                                                                    />
                                                                                                </td>
                                                                                            </tr>
                                                                                        ) : (
                                                                                            <>
                                                                                                {/* ردیف اصلی برای متن */}
                                                                                                <tr>
                                                                                                    <td
                                                                                                        width="100%"
                                                                                                        height={item?.buttons && item.buttons.length > 0 ? "203" : "230"}
                                                                                                        align={item?.texts?.[0]?.alignment || 'right'}
                                                                                                        valign={item?.texts?.[0]?.verticalAlignment === VerticalAlignment.TOP ? 'top' :
                                                                                                            item?.texts?.[0]?.verticalAlignment === VerticalAlignment.BOTTOM ? 'bottom' : 'middle'}
                                                                                                        style={{
                                                                                                            padding: '8px',
                                                                                                            fontSize: '14px',
                                                                                                            lineHeight: '1.4'
                                                                                                        }}
                                                                                                    >
                                                                                                        <TextRenderer
                                                                                                            texts={item?.texts || []}
                                                                                                            itemId={item?.id || ''}
                                                                                                            sectionKey="content"
                                                                                                        />
                                                                                                        <ImageRenderer
                                                                                                            images={item?.images || []}
                                                                                                            itemId={item?.id || ''}
                                                                                                            sectionKey="content"
                                                                                                        />
                                                                                                        <SocialRenderer
                                                                                                            socials={item?.socials || []}
                                                                                                            itemId={item?.id || ''}
                                                                                                            sectionKey="content"
                                                                                                        />
                                                                                                        {(!item?.texts || item.texts.length === 0) &&
                                                                                                            (!item?.images || item.images.length === 0) &&
                                                                                                            (!item?.socials || item.socials.length === 0) && (
                                                                                                                <div style={{
                                                                                                                    margin: 0,
                                                                                                                    textAlign: 'right',
                                                                                                                    color: '#888',
                                                                                                                    fontSize: '14px'
                                                                                                                }}>
                                                                                                                    {'{{content}}'}
                                                                                                                </div>
                                                                                                            )}
                                                                                                    </td>
                                                                                                </tr>
                                                                                                {/* ردیف دکمه‌ها */}
                                                                                                {item?.buttons && item.buttons.length > 0 && (
                                                                                                    <tr>
                                                                                                        <td
                                                                                                            width="100%"
                                                                                                            height="27"
                                                                                                            align={getButtonHorizontalAlign(item.buttons[0])}
                                                                                                            valign={getButtonVerticalAlign(item.buttons[0])}
                                                                                                            style={{
                                                                                                                padding: '0 8px 8px 8px'
                                                                                                            }}
                                                                                                        >
                                                                                                            <ButtonRenderer
                                                                                                                buttons={item.buttons}
                                                                                                                itemId={item?.id || ''}
                                                                                                                sectionKey="content"
                                                                                                            />
                                                                                                        </td>
                                                                                                    </tr>
                                                                                                )}
                                                                                            </>
                                                                                        )}
                                                                                    </>
                                                                                )}
                                                                            </tbody>
                                                                        </table>
                                                                    </td>
                                                                    {index < data.content.columnsCount - 1 && (
                                                                        <td style={{ width: '16px' }}></td>
                                                                    )}
                                                                </>
                                                            )
                                                        })
                                                    }
                                                </tr>
                                            </tbody>
                                        </table>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                        :
                        <table width="100%" cellPadding="0" cellSpacing="0" border={0}>
                            <tbody>
                                <tr>
                                    <td
                                        onClick={(e) => handleSectionClick(SectionName.CONTENT, e)}
                                        style={{
                                            height: '286px',
                                            border: activeSection === SectionName.CONTENT ? '1px dashed #0038FF' : '1px dashed #E5E7EB',
                                            borderRadius: '24px',
                                            textAlign: 'right',
                                            verticalAlign: 'middle',
                                            padding: '10px',
                                            cursor: 'pointer'
                                        }}
                                    >
                                        <div style={{ color: '#888', fontSize: '14px', marginBottom: '8px' }}>
                                            {t('setting.content_email')}
                                        </div>
                                        <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
                                            <AddCircle size={24} color='#888' />
                                        </div>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                }
            </td>
        </tr>
    )
}

export default ContentSection 