import { FC, useState, useEffect } from 'react'
import { useTranslation } from 'react-i18next'
import { useLocation, useParams } from 'react-router-dom'
import { SettingTabEnum } from './enum/SettingEnum'
import Personality from './personality/Personality'
import Domain from './domain/Domain'
import MailServer from './mail-server/MailServer'
import Address from './address/Address'
import PersonalitySidebar from './personality/SideBar'
import Signture from './signture/Signture'
import { Paths } from '@/utils/Paths'
import Button from '@/components/Button'
import { TickCircle } from 'iconsax-react'
import { usePersonalityStore } from './personality/store/Store'
import { exportPersonalityToHTML } from './personality/utils/ExportHTML'
import { capturePersonalityScreenshot } from './personality/utils/screenshotHelper'
import Input from '@/components/Input'
import { useSaveTemplate, useUpdateTemplate, useGetTemplate, useSingleUpload } from './personality/hooks/usePersonalityData'
import { toast } from '@/components/Toast'

const Setting: FC = () => {
    const { t } = useTranslation()
    const { id } = useParams()
    const { data } = usePersonalityStore()
    const location = useLocation()
    const [activeTab, setActiveTab] = useState<SettingTabEnum>(SettingTabEnum.SETTING_DOMAIN)
    const [templateName, setTemplateName] = useState('')
    const [isCapturingScreenshot, setIsCapturingScreenshot] = useState(false)
    const [isSaveProcessing, setIsSaveProcessing] = useState(false)

    const { mutate: saveTemplate, isPending: isSaving } = useSaveTemplate()
    const { mutate: updateTemplate, isPending: isUpdating } = useUpdateTemplate()
    const { data: template } = useGetTemplate(id || '')
    const { mutateAsync: singleUpload, isPending: isUploading } = useSingleUpload()

    const isEditMode = !!id
    const isLoading = isSaving || isUpdating || isUploading || isCapturingScreenshot || isSaveProcessing

    useEffect(() => {
        if (isEditMode && template?.data?.template?.name) {
            setTemplateName(template.data.template.name)
        }
    }, [isEditMode, template])

    const getTabFromPath = (pathname: string): SettingTabEnum => {
        switch (pathname) {
            case Paths.settingMailServer:
                return SettingTabEnum.SETTING_MAIL_SERVER
            case Paths.settingDomain:
                return SettingTabEnum.SETTING_DOMAIN
            case Paths.settingAddress:
                return SettingTabEnum.SETTING_ADDRESS
            case Paths.settingPersonality:
                return SettingTabEnum.SETTING_PERSONALITY
            case Paths.settingSignature:
                return SettingTabEnum.SETTING_SIGNATURE
            default:
                if (pathname.startsWith(Paths.settingPersonality + '/')) {
                    return SettingTabEnum.SETTING_PERSONALITY
                }
                return SettingTabEnum.SETTING_DOMAIN
        }
    }

    useEffect(() => {
        const tabFromPath = getTabFromPath(location.pathname)
        setActiveTab(tabFromPath)
    }, [location.pathname])

    const renderActiveTab = () => {
        switch (activeTab) {
            case SettingTabEnum.SETTING_MAIL_SERVER:
                return <MailServer />;
            case SettingTabEnum.SETTING_DOMAIN:
                return <Domain />;
            case SettingTabEnum.SETTING_ADDRESS:
                return <Address />;
            case SettingTabEnum.SETTING_SIGNATURE:
                return <Signture />;
            case SettingTabEnum.SETTING_PERSONALITY:
                return (
                    <div className='flex xl:flex-row-reverse gap-2 md:gap-6 mt-6 md:mt-8'>
                        <div className="xl:w-auto">
                            <PersonalitySidebar />
                        </div>
                        <div className="flex-1">
                            <Personality />
                        </div>
                    </div>
                );
            default:
                return null;
        }
    };

    const handleSave = async () => {
        if (!templateName) {
            toast('نام قالب را وارد کنید', 'error')
            return
        }

        if (activeTab !== SettingTabEnum.SETTING_PERSONALITY) {
            return
        }

        setIsSaveProcessing(true)

        try {
            const html = await exportPersonalityToHTML(data)

            setIsCapturingScreenshot(true)
            const screenshotFile = await capturePersonalityScreenshot(templateName)
            setIsCapturingScreenshot(false)


            const thumbnailUrl = screenshotFile ? await singleUpload(screenshotFile) : undefined

            if (isEditMode) {
                updateTemplate({
                    id: id!,
                    params: {
                        name: templateName,
                        rawHtml: html,
                        structure: data,
                        thumbnailUrl: thumbnailUrl?.data?.url || undefined
                    }
                }, {
                    onSuccess: (data) => {
                        toast(data?.data?.message || 'قالب با موفقیت بروزرسانی شد', 'success')
                        window.location.href = Paths.settingPersonalityList
                    },
                    onError: () => {
                        toast('خطا در بروزرسانی قالب', 'error')
                    }
                })
            } else {
                saveTemplate({
                    name: templateName,
                    rawHtml: html,
                    structure: data,
                    thumbnailUrl: thumbnailUrl?.data?.url || undefined
                }, {
                    onSuccess: (data) => {
                        toast(data?.data?.message || 'قالب با موفقیت ایجاد شد', 'success')
                        window.location.href = Paths.settingPersonalityList
                    },
                    onError: () => {
                        toast('خطا در ایجاد قالب', 'error')
                    }
                })
            }
        } finally {
            setIsSaveProcessing(false)
        }
    }

    return (
        <div className='mt-2 md:mt-4 px-2 md:px-0'>
            <div className='flex flex-col md:flex-row justify-between md:items-center'>
                <h1 className='text-lg mb-4 md:mb-0'>{t('setting.title')}</h1>
                {
                    activeTab === SettingTabEnum.SETTING_PERSONALITY &&
                    <div className='flex gap-2'>
                        <Input
                            placeholder='نام قالب'
                            value={templateName}
                            onChange={(e) => setTemplateName(e.target.value)}
                        />
                        <Button
                            variant='secondary'
                            className='border border-black w-fit px-7'
                            onClick={handleSave}
                            loading={isLoading}
                        >
                            <div className='flex items-center gap-2'>
                                <TickCircle size={18} color='black' />
                                {isEditMode ? 'بروزرسانی' : t('save')}
                            </div>
                        </Button>
                    </div>
                }
            </div>

            <div>
                {renderActiveTab()}
            </div>
        </div>
    )
}

export default Setting