import { FC, useEffect } from 'react'
import HeaderSection from './components/HeaderSection'
import ContentSection from './components/ContentSection'
import FooterSection from './components/FooterSection'
import GenericSection from './components/GenericSection'
import { useParams } from 'react-router-dom'
import { usePersonalityStore } from './store/Store'
import { useGetTemplate } from './hooks/usePersonalityData'
import { Add } from 'iconsax-react'
import { toast } from '@/components/Toast'

const Personality: FC = () => {
    const { id } = useParams()
    const { setData, addSection, getSortedSectionKeys } = usePersonalityStore()
    const { data: template } = useGetTemplate(id || '')

    useEffect(() => {
        if (id && template?.data?.template?.structure) {
            setData(template.data.template.structure)
        }
    }, [id, template, setData])

    const handleAddSection = (afterSectionKey: string) => {
        addSection(afterSectionKey)
        toast('سکشن جدید با موفقیت اضافه شد', 'success')
    }

    const renderSection = (sectionKey: string) => {
        if (sectionKey === 'header') {
            return <HeaderSection key={sectionKey} />
        } else if (sectionKey === 'content') {
            return <ContentSection key={sectionKey} />
        } else if (sectionKey === 'footer') {
            return <FooterSection key={sectionKey} />
        }

        return <GenericSection key={sectionKey} sectionKey={sectionKey} />
    }

    const renderPlusButton = (afterSectionKey: string) => {
        return (
            <tr key={`plus-${afterSectionKey}`} style={{ position: 'relative', height: '0px' }}>
                <td style={{ position: 'relative', height: '0px' }}>
                    <div
                        className="absolute left-1/2 transform -translate-x-1/2 -translate-y-1/2"
                        style={{ top: '0px', zIndex: 9999 }}
                    >
                        <button
                            onClick={() => handleAddSection(afterSectionKey)}
                            className="group flex items-center justify-center w-10 h-10 rounded-full border-2 border-dashed border-gray-300 hover:border-blue-500 hover:bg-blue-50 bg-white transition-all duration-200 shadow-sm hover:shadow-md"
                            title="اضافه کردن سکشن جدید"
                            style={{ position: 'relative', zIndex: 9999 }}
                        >
                            <Add
                                size={20}
                                color='gray'
                                className="text-gray-400 group-hover:text-blue-500 transition-colors"
                            />
                        </button>
                    </div>
                </td>
            </tr>
        )
    }


    const sortedSectionKeys = getSortedSectionKeys();

    return (
        <div className='flex-1 bg-white rounded-4xl p-8 personality-template'>
            <table width="100%" cellPadding="0" cellSpacing="0" border={0} style={{ borderCollapse: 'collapse' }}>
                <tbody>
                    {sortedSectionKeys.map((sectionKey, index) => {
                        const elements = [];

                        // Add the section
                        elements.push(renderSection(sectionKey));

                        // Add plus button after each section except the last one
                        if (index < sortedSectionKeys.length - 1) {
                            elements.push(renderPlusButton(sectionKey));
                        }

                        return elements;
                    }).flat()}

                    {/* Plus button at the end */}
                    {sortedSectionKeys.length > 0 && renderPlusButton(sortedSectionKeys[sortedSectionKeys.length - 1])}
                </tbody>
            </table>
        </div>
    )
}

export default Personality