import { FC, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { ArrowDown2, CloseSquare } from 'iconsax-react'
import AvatarImage from '@/assets/images/avatar.svg'
import ForwardIcon from '@/assets/images/forward.svg'
import EmailEditor from './EmailEditor'
import EmailFormActions from './EmailFormActions'
import EmailInput from './EmailInput'
import { MessageDetail } from '@/pages/received/types/Types'
import { useAuthStore } from '@/pages/auth/store/AuthStore'
import { useSendEmail } from '@/pages/received/hooks/useEmailData'
import { SendEmailDto } from '@/pages/received/types/Types'
import { toast } from '@/components/Toast'

interface ForwardProps {
    originalMessage: MessageDetail
    onClose: () => void
    onExpand?: () => void
    className?: string
    showInitialButton?: boolean
}

const Forward: FC<ForwardProps> = ({
    originalMessage,
    onClose,
    onExpand,
    className = '',
    showInitialButton = true
}) => {
    const { t } = useTranslation()
    const { email: userEmail } = useAuthStore()
    const sendEmailMutation = useSendEmail()

    const [isExpanded, setIsExpanded] = useState<boolean>(false)
    const [toEmails, setToEmails] = useState<string[]>([])
    const [content, setContent] = useState<string>('')

    const expandForward = () => {
        setIsExpanded(true)
        // Pre-fill content with original message
        const forwardContent = `
      <br/><br/>
      <div dir="rtl">
      ---------- پیام ارسالی ----------<br/>
      <strong>از:</strong> ${originalMessage.from.name || originalMessage.from.address} &lt;${originalMessage.from.address}&gt;<br/>
      <strong>تاریخ:</strong> ${originalMessage.date}<br/>
      <strong>موضوع:</strong> ${originalMessage.subject}<br/>
      <strong>به:</strong> ${originalMessage.to.map(recipient => recipient.address).join(', ')}<br/>
      <br/>
      ${originalMessage.html ? originalMessage.html.join('') : originalMessage.text}
      </div>
    `
        setContent(forwardContent)
        onExpand?.()
    }

    const handleClose = async () => {
        // اگر محتوا یا ایمیل وارد شده، پیش‌نویس ذخیره کن
        if (content.trim() || toEmails.length > 0) {
            // TODO: Implement save draft functionality
            toast('پیش‌نویس ذخیره شد', 'success')
        }

        // بسته کردن و برگشت به حالت قبل
        collapseForward()
        onClose() // این خط مهمه تا parent component بفهمه
    }

    const collapseForward = () => {
        setIsExpanded(false)
        resetForm()
        onClose()
    }

    const resetForm = () => {
        setToEmails([])
        setContent('')
        setIsExpanded(false)
    }

    const handleSendForward = async () => {
        if (toEmails.length === 0) {
            toast('لطفا حداقل یک گیرنده وارد کنید', 'error')
            return false
        }

        if (!content.trim()) {
            toast('لطفا متن پیام را وارد کنید', 'error')
            return false
        }

        // Format date to Persian
        const originalDate = new Date(originalMessage.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 htmlContent =
            content +
            "<br /><br />" +
            "<div dir='rtl'>---------- پیام ارسالی ----------<br/>" +
            `<strong>از:</strong> ${originalMessage.from.name || originalMessage.from.address} &lt;${originalMessage.from.address}&gt;<br/>` +
            `<strong>تاریخ:</strong> ${persianDate}<br/>` +
            `<strong>موضوع:</strong> ${originalMessage.subject}<br/>` +
            `<strong>به:</strong> ${originalMessage.to.map(recipient => recipient.address).join(', ')}<br/>` +
            "<br/>" +
            (originalMessage?.html?.[0] || originalMessage?.text || '') + "</div>"

        const forwardData: SendEmailDto = {
            from: { address: userEmail || 'sender@example.com' },
            to: toEmails.map(email => ({ address: email })),
            subject: originalMessage.subject.startsWith('Fwd:')
                ? originalMessage.subject
                : `Fwd: ${originalMessage.subject}`,
            html: htmlContent,
            text: content.replace(/<[^>]*>/g, ''),
            isForward: true,
        }

        try {
            await sendEmailMutation.mutateAsync(forwardData)
            toast('پیام با موفقیت ارسال شد', 'success')
            resetForm()
            onClose?.()
            return true
        } catch {
            const errorMessage = 'خطا در ارسال پیام'
            toast(errorMessage, 'error')
            return false
        }
    }



    // اگر showInitialButton true باشه و هنوز expand نشده، فقط دکمه نشون بده
    if (showInitialButton && !isExpanded) {
        return (
            <div className={`flex gap-5 text-sm ${className}`}>
                <div
                    onClick={expandForward}
                    className='flex gap-2 cursor-pointer items-center border-r border-border pr-5 hover:text-primary transition-colors'
                >
                    <img src={ForwardIcon} className='w-[17px]' />
                    <div>{t('mail.forward')}</div>
                </div>
            </div>
        )
    }

    // در غیر این صورت editor رو نشون بده
    // (یا showInitialButton false هست یا isExpanded true هست)

    return (
        <div className={`mt-6 w-full ${className}`}>
            {/* Forward Header */}
            <div className='flex items-center justify-between mb-4 p-3 bg-gray-50 rounded-lg border'>
                <div className='flex items-center gap-2 text-sm text-gray-600'>
                    <img src={ForwardIcon} className='w-4 h-4' />
                    <span>ارسال به دیگران</span>
                </div>
                <div className='flex items-center gap-2'>
                    <button
                        onClick={collapseForward}
                        className='p-1 hover:bg-gray-200 rounded transition-colors'
                        title='بستن'
                    >
                        <ArrowDown2 size={16} />
                    </button>
                    <button
                        onClick={() => {
                            collapseForward()
                            onClose?.()
                        }}
                        className='p-1 hover:bg-gray-200 rounded transition-colors'
                        title='لغو'
                    >
                        <CloseSquare size={16} />
                    </button>
                </div>
            </div>

            {/* Forward Content */}
            <div className='flex gap-4'>
                <img src={AvatarImage} className='size-10 flex-shrink-0' />
                <div className='w-full'>
                    {/* To Field */}
                    <div className='mb-4'>
                        <EmailInput
                            toEmails={toEmails}
                            onAddEmail={(email) => {
                                if (!toEmails.includes(email)) {
                                    setToEmails([...toEmails, email])
                                }
                            }}
                            onRemoveEmail={(email) => {
                                setToEmails(toEmails.filter(e => e !== email))
                            }}
                            suggestions={[]}
                        />
                    </div>

                    {/* Subject Field */}
                    <div className='mb-4 text-sm'>
                        <div className='flex items-center gap-2 p-2 bg-gray-50 rounded border'>
                            <span className='text-gray-600 min-w-fit'>موضوع:</span>
                            <span className='text-gray-800'>
                                {originalMessage.subject.startsWith('Fwd:')
                                    ? originalMessage.subject
                                    : `Fwd: ${originalMessage.subject}`}
                            </span>
                        </div>
                    </div>

                    {/* Editor */}
                    <div className='mb-4'>
                        <EmailEditor
                            value={content}
                            onChange={setContent}
                            placeholder='پیام خود را اضافه کنید...'
                        />
                    </div>

                    {/* Actions */}
                    <EmailFormActions
                        onSend={handleSendForward}
                        isSending={sendEmailMutation.isPending}
                        onClose={handleClose}
                    />
                </div>
            </div>
        </div>
    )
}

export default Forward 