import { FC } from 'react'
import { MessageDetail } from '../types/Types'
import { MailboxEnum } from '../enum/Enum'

interface BccRecipientsProps {
    messageDetail: MessageDetail
    userEmail: string | null
    mailboxName: MailboxEnum
}

const BccRecipients: FC<BccRecipientsProps> = ({ messageDetail, userEmail, mailboxName }) => {
    // If userEmail is not available, we can't determine BCC status
    if (!userEmail || userEmail.trim() === '') {
        return null
    }

    // Check if current user was BCC recipient (for received messages)
    const isInTo = messageDetail.to?.some(recipient =>
        recipient.address.toLowerCase().trim() === userEmail.toLowerCase().trim()
    ) || false
    const isInCc = messageDetail.cc?.some(recipient =>
        recipient.address.toLowerCase().trim() === userEmail.toLowerCase().trim()
    ) || false

    // Check if user is explicitly in BCC field OR implicitly (not in to/cc but received)
    const isExplicitlyInBcc = messageDetail.bcc?.some(recipient =>
        recipient.address.toLowerCase().trim() === userEmail.toLowerCase().trim()
    ) || false
    const isInBcc = isExplicitlyInBcc || (!isInTo && !isInCc && mailboxName !== MailboxEnum.SENT)

    // Show BCC notice for received messages
    if (isInBcc) {
        return (
            <div className='mt-4 mr-14'>
                <div className='bg-accent border border-border rounded-lg px-4 py-2 text-xs text-muted-foreground'>
                    شما به عنوان رونوشت مخفی (BCC) این پیام را دریافت کرده‌اید
                </div>
            </div>
        )
    }

    // Show BCC recipients for sent messages
    if (mailboxName === MailboxEnum.SENT && messageDetail.envelope?.rcpt) {
        const toAddresses = messageDetail.to?.map(r => r.address.toLowerCase()) || []
        const ccAddresses = messageDetail.cc?.map(r => r.address.toLowerCase()) || []

        const bccRecipients = messageDetail.envelope.rcpt.filter(rcpt => {
            const address = rcpt.value.toLowerCase()
            return !toAddresses.includes(address) && !ccAddresses.includes(address)
        })

        if (bccRecipients.length === 0) {
            return null
        }

        return (
            <div className='mt-4 mr-14'>
                <div className='text-xs text-description mb-2'>رونوشت مخفی (BCC):</div>
                <div className='flex flex-wrap gap-2'>
                    {bccRecipients.map((recipient, index) => (
                        <div key={index} className='bg-secondary rounded-full px-3 py-1 text-xs'>
                            {recipient.formatted || recipient.value}
                        </div>
                    ))}
                </div>
            </div>
        )
    }

    return null
}

export default BccRecipients

