import Button from '@/components/Button'
import { FC, useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useParams } from 'react-router-dom'
import AvatarImage from '@/assets/images/avatar.svg'
import { DocumentDownload } from 'iconsax-react'
import Header from './Components/Header'
import { useGetMessageDetail, useDownloadAttachment, useSendEmail } from './hooks/useEmailData'
import { toast } from '@/components/Toast'
import { formatDate, sanitizeEmailHTML, detectTextDirection } from '@/config/func'
import SkeletonDetail from './Components/SkeletonDetail'
import { useEmailActions } from '@/hooks/useEmailActions'
import { MailboxEnum } from './enum/Enum'
import Reply from '@/components/newMessage/Reply'
import Forward from '@/components/newMessage/Forward'
import EmojiReaction from '@/components/EmojiReaction'
import { useAuthStore } from '@/pages/auth/store/AuthStore'
import { SendEmailDto } from './types/Types'

const DetailEmail: FC = () => {

    const { t } = useTranslation()
    const emailActions = useEmailActions()
    const { email: userEmail } = useAuthStore()
    const { id, mailbox } = useParams<{ id: string, mailbox: string }>()
    const [activeAction, setActiveAction] = useState<'reply' | 'forward' | null>(null)

    // API hooks
    const { data: messageDetail, isLoading, error } = useGetMessageDetail(id || '', mailbox || '')
    const downloadAttachmentMutation = useDownloadAttachment()
    const sendEmailMutation = useSendEmail()

    const handleDownloadAttachment = async (attachmentId: string, filename: string) => {
        if (!id) {
            toast('شناسه پیام یافت نشد', 'error')
            return
        }

        try {
            const blob = await downloadAttachmentMutation.mutateAsync({
                messageId: id,
                attachmentId: attachmentId,
                mailbox: mailbox || ''
            })

            // Create download link
            const url = window.URL.createObjectURL(blob)
            const link = document.createElement('a')
            link.href = url
            link.download = filename || `attachment-${attachmentId}`
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)
            window.URL.revokeObjectURL(url)

            toast('فایل با موفقیت دانلود شد', 'success')
        } catch (error) {
            console.error('Download error:', error)
            toast('خطا در دانلود فایل', 'error')
        }
    }

    const handleEmojiSelect = async (emoji: string) => {
        if (!messageDetail) {
            toast('اطلاعات پیام یافت نشد', 'error')
            return
        }

        // Format date to Persian for reply context
        const originalDate = new Date(messageDetail.date)
        const persianDate = new Intl.DateTimeFormat('fa-IR', {
            weekday: 'long',
            year: 'numeric',
            month: 'long',
            day: 'numeric',
            hour: '2-digit',
            minute: '2-digit',
        }).format(originalDate)

        const reactionHtml = `
            <div style="font-size: 24px; text-align: center; margin: 20px 0;">
                ${emoji}
            </div>
            <br />
            <div dir="rtl" style="color: #666; font-size: 12px; border-top: 1px solid #ddd; padding-top: 10px;">
                در پاسخ به پیام ${persianDate} از ${messageDetail.from.name} &lt;${messageDetail.from.address}&gt;
            </div>
        `

        const replyData: SendEmailDto = {
            from: { address: userEmail || 'sender@example.com' },
            to: [
                {
                    address: messageDetail.from.address,
                    name: messageDetail.from.name,
                },
            ],
            replyTo: {
                name: messageDetail.from.name,
                address: messageDetail.from.address,
            },
            subject: messageDetail.subject.startsWith('Re:')
                ? messageDetail.subject
                : `Re: ${messageDetail.subject}`,
            html: reactionHtml,
            text: `واکنش: ${emoji}\n\nدر پاسخ به پیام ${persianDate} از ${messageDetail.from.name}`,
        }

        try {
            await sendEmailMutation.mutateAsync(replyData)
            toast('واکنش نشان داد', 'success')
        } catch (error) {
            console.error('Send error:', error)
            toast('خطا در نشان دادن واکنش', 'error')
        }
    }

    // Mark message as seen when it's loaded and not already seen
    useEffect(() => {
        if (messageDetail && !messageDetail.seen && id) {
            console.log('Marking message as seen:', id, 'Current seen status:', messageDetail.seen)
            emailActions.markAsSeen({ messageId: Number(id), mailbox: mailbox || '' })
        }
    }, [messageDetail, emailActions, id])

    if (isLoading) {
        return (
            <SkeletonDetail />
        )
    }

    if (error || !messageDetail) {
        return (
            <div className='bg-white rounded-4xl p-8'>
                <div className='text-center text-red-500'>
                    خطا در بارگذاری پیام
                </div>
            </div>
        )
    }

    return (
        <div className='bg-white rounded-4xl p-8'>
            <Header
                flagged={messageDetail?.flagged || false}
                mailBoxName={messageDetail?.mailboxName as MailboxEnum}
                messageDetail={messageDetail}
            />

            <div className='mt-6 flex xl:flex-row flex-col justify-between xl:items-center'>
                <div className='flex xl:flex-row flex-col-reverse gap-4 xl:items-center'>
                    <div className='flex gap-1 items-center'>
                        <div className='font-extralight hidden xl:block'>{t('mail.subject')}</div>
                        <div className='leading-7 text-sm'>{messageDetail.subject || 'بدون موضوع'}</div>
                    </div>
                    <div className='flex gap-2'>
                        <Button
                            label={t(`mail.${messageDetail?.mailboxName}`)}
                            className='bg-[#ECEFF6] text-description w-fit px-6 rounded-full h-6 xl:h-10 text-[10px] xl:text-sm'
                        />
                        {/* <Button
                            label='الویت زیاد'
                            className='bg-[#FFE9E9] text-[#CD0000] w-fit px-6 rounded-full h-6 xl:h-10 text-[10px] xl:text-sm'
                        /> */}
                    </div>
                </div>

                <div className='flex justify-end text-description xl:text-sm text-[10px]'>
                    {formatDate(messageDetail.date)}
                </div>
            </div>

            <div>
                <div className='mt-6 flex gap-4 items-center'>
                    <img src={AvatarImage} className='size-10' />
                    <div>
                        <div className='text-sm'>{messageDetail.from.name || messageDetail.from.address}</div>
                        <div className='text-xs text-description mt-0.5'>{messageDetail.from?.address}</div>
                    </div>
                </div>
            </div>

            <div className='xl:mt-8 mt-3 text-[13px] leading-7 font-light'>
                {messageDetail.html && messageDetail.html.length > 0 ? (
                    <div
                        className='email-content-container border border-gray-200 rounded-lg p-4 overflow-x-auto overflow-y-hidden'
                        style={{
                            direction: detectTextDirection(messageDetail.html.join(''))
                        }}
                        dangerouslySetInnerHTML={{ __html: sanitizeEmailHTML(messageDetail.html.join('')) }}
                    />
                ) : (
                    <p style={{
                        direction: detectTextDirection(messageDetail.text || '')
                    }}>{messageDetail.text || 'محتوای پیام'}</p>
                )}
            </div>

            <div className='mt-10 text-sm font-bold'>
                {t('mail.attachments')}
            </div>

            <div className='flex border-b border-border pb-10 mt-4 flex-wrap gap-2.5 items-center'>
                {messageDetail.attachments && messageDetail.attachments.length > 0 ? (
                    messageDetail.attachments.map((attachment, index) => (
                        <div key={index} className='bg-[#EBEDF5] text-sm flex gap-2 h-10 rounded-full items-center px-4'>
                            <span>{attachment.filename || `attachment-${index + 1}`}</span>
                            <DocumentDownload
                                size={20}
                                color='#0038FF'
                                className='cursor-pointer hover:opacity-70 transition-opacity'
                                onClick={() => handleDownloadAttachment(
                                    attachment.id || `ATT${String(index + 1).padStart(5, '0')}`,
                                    attachment.filename || `attachment-${index + 1}`
                                )}
                            />
                        </div>
                    ))
                ) : (
                    <div className='bg-[#EBEDF5] text-sm flex gap-2 h-10 rounded-full items-center px-4'>
                        <span>فایل ضمیمه‌ای وجود ندارد</span>
                    </div>
                )}
            </div>

            {/* Email Actions */}
            {activeAction === null && (
                <div className='flex mt-9 justify-end'>
                    <div className='flex gap-5 text-sm'>
                        <EmojiReaction onEmojiSelect={handleEmojiSelect} />

                        <Reply
                            originalMessage={messageDetail}
                            className='border-r border-border pr-5'
                            showInitialButton={true}
                            onClose={() => setActiveAction(null)}
                            onExpand={() => setActiveAction('reply')}
                        />

                        <Forward
                            originalMessage={messageDetail}
                            showInitialButton={true}
                            onClose={() => setActiveAction(null)}
                            onExpand={() => setActiveAction('forward')}
                        />
                    </div>
                </div>
            )}

            {/* Full width Reply */}
            {activeAction === 'reply' && (
                <Reply
                    originalMessage={messageDetail}
                    showInitialButton={false}
                    onClose={() => setActiveAction(null)}
                />
            )}

            {/* Full width Forward */}
            {activeAction === 'forward' && (
                <Forward
                    originalMessage={messageDetail}
                    showInitialButton={false}
                    onClose={() => setActiveAction(null)}
                />
            )}
        </div>
    )
}

export default DetailEmail