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 FooterSection: FC = () => {

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

    // Early return if data is not available
    if (!data || !data.footer) {
        return (
            <tr>
                <td style={{ height: '123px', textAlign: 'center', 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 footer section
            if (activeSection !== SectionName.FOOTER) {
                setActiveSection(SectionName.FOOTER)
            }

            // 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.FOOTER, e)}>
            <td style={{ paddingTop: '0px' }}>
                {
                    data.footer.columnsCount > 0 ?
                        <table width="100%" cellPadding="0" cellSpacing="0" border={0}>
                            <tbody>
                                <tr>
                                    <td style={{
                                        padding: '10px',
                                        border: activeSection === SectionName.FOOTER ? '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.footer.columnsCount }, (_, index) => {
                                                            const item = data.footer.items[index];
                                                            const isActive = activeSection === SectionName.FOOTER && activeItemIndex === index;

                                                            return (
                                                                <>
                                                                    <td
                                                                        key={index}
                                                                        onClick={(e) => handleItemClick(index, e)}
                                                                        style={{
                                                                            width: `${100 / data.footer.columnsCount}%`,
                                                                            height: '123px',
                                                                            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: '123px'
                                                                        }}>
                                                                            <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="123"
                                                                                            style={{
                                                                                                padding: '8px',
                                                                                                cursor: 'pointer'
                                                                                            }}
                                                                                            onClick={(e) => handleItemClick(index, e)}
                                                                                        >
                                                                                            {/* محتوای خالی برای columns خالی */}
                                                                                        </td>
                                                                                    </tr>
                                                                                ) : (
                                                                                    <>
                                                                                        {/* اگر فقط دکمه داریم و متن نداریم */}
                                                                                        {(!item?.texts || item.texts.length === 0) && item?.buttons && item.buttons.length > 0 ? (
                                                                                            <tr>
                                                                                                <td
                                                                                                    width="100%"
                                                                                                    height="123"
                                                                                                    align={getButtonHorizontalAlign(item.buttons[0])}
                                                                                                    valign={getButtonVerticalAlign(item.buttons[0])}
                                                                                                    style={{
                                                                                                        padding: '8px'
                                                                                                    }}
                                                                                                >
                                                                                                    <ButtonRenderer
                                                                                                        buttons={item.buttons}
                                                                                                        itemId={item?.id || ''}
                                                                                                        sectionKey="footer"
                                                                                                    />
                                                                                                </td>
                                                                                            </tr>
                                                                                        ) : (
                                                                                            <>
                                                                                                {/* ردیف اصلی برای متن */}
                                                                                                <tr>
                                                                                                    <td
                                                                                                        width="100%"
                                                                                                        height={item?.buttons && item.buttons.length > 0 ? "40" : "67"}
                                                                                                        align={item?.texts?.[0]?.alignment || 'center'}
                                                                                                        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="footer"
                                                                                                        />
                                                                                                        <ImageRenderer
                                                                                                            images={item?.images || []}
                                                                                                            itemId={item?.id || ''}
                                                                                                            sectionKey="footer"
                                                                                                        />
                                                                                                        <SocialRenderer
                                                                                                            socials={item?.socials || []}
                                                                                                            itemId={item?.id || ''}
                                                                                                            sectionKey="footer"
                                                                                                        />
                                                                                                    </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="footer"
                                                                                                            />
                                                                                                        </td>
                                                                                                    </tr>
                                                                                                )}
                                                                                            </>
                                                                                        )}
                                                                                    </>
                                                                                )}
                                                                            </tbody>
                                                                        </table>
                                                                    </td>
                                                                    {index < data.footer.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.FOOTER, e)}
                                        style={{
                                            height: '123px',
                                            border: activeSection === SectionName.FOOTER ? '1px dashed #0038FF' : '1px dashed #E5E7EB',
                                            borderRadius: '24px',
                                            textAlign: 'center',
                                            verticalAlign: 'middle',
                                            padding: '10px',
                                            cursor: 'pointer'
                                        }}
                                    >
                                        <div style={{ color: '#888', fontSize: '14px', marginBottom: '8px' }}>
                                            {t('setting.footer_email')}
                                        </div>
                                        <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
                                            <AddCircle size={24} color='#888' />
                                        </div>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                }
            </td>
        </tr>
    )
}

export default FooterSection 