import { useState, useEffect, useRef } from 'react'
import { App, Button, Divider, Avatar, List, Flex, Typography, Tooltip } from 'antd'
import { LoadingOutlined, ApiOutlined, FilePdfOutlined, FileOutlined, FileWordOutlined, FileExcelOutlined, FileJpgOutlined, FileImageOutlined, FileTextOutlined, FileGifOutlined, GlobalOutlined, FileZipOutlined } from '@ant-design/icons'
import { EditIcon, MailCheckIcon, ReplyAllIcon, ReplyIcon, ResendIcon, ShareForwardIcon, SendPlaneFillIcon, InboxIcon } from '@/components/Icons'
import { isEmpty, TagColorStyle } from '@/utils/commons'
import EmailEditorPopup from '../Input/EmailEditorPopup'
import DnDModal from '@/components/DnDModal'
import useStyleStore from '@/stores/StyleStore'
import { useEmailDetail } from '@/hooks/useEmail'
import { EMAIL_ATTA_HOST, POPUP_FEATURES } from '@/config'
import EmailBindFormModal from './EmailBind'
import EmailContent from './EmailContent'

const extTypeMapped = {
  txt: { icon: FileTextOutlined },
  zip: { icon: FileZipOutlined, color: '#ffe78f' },
  pdf: { icon: FilePdfOutlined, color: '#ad0b00' },
  doc: { icon: FileWordOutlined, color: '#103f91' },
  docx: { icon: FileWordOutlined, color: '#103f91' },
  xls: { icon: FileExcelOutlined, color: '#0c7d0c' },
  xlsx: { icon: FileExcelOutlined, color: '#0c7d0c' },
  jpg: { icon: FileImageOutlined, color: '#1985ff' },
  png: { icon: FileImageOutlined, color: '#1985ff' },
  gif: { icon: FileGifOutlined, color: '#1985ff' },
  html: { icon: GlobalOutlined, color: '#1985ff' },
  htm: { icon: GlobalOutlined, color: '#1985ff' },
  default: { icon: FileOutlined }, // rtf bmp
}

/**
 * @property {*} emailMsg - 邮件数据. { conversationid, actionId, order_opi, coli_sn, msgOrigin: { from, to, id, email: { subject, mai_sn, } } }
 */
const EmailDetailInline = ({ mailID, emailMsg = {}, disabled = false, variant, size, ...props }) => {
  // console.log('emailDetail', emailMsg);
  const componentRef = useRef(null);
  const [compactBtn, setCompactBtn] = useState(size==='small');

  useEffect(() => {
    if (componentRef.current) {
      // console.log(componentRef.current.getBoundingClientRect().width);
      setCompactBtn(componentRef.current.offsetWidth < 769);
    }
    return () => {}
  }, [])


  const { notification, message } = App.useApp()

  const { conversationid, actionId, order_opi, coli_sn } = emailMsg
  const { mai_sn, id } = emailMsg.msgOrigin?.email || emailMsg.msgOrigin || {}
  // const mailID = mai_sn || id

  const [action, setAction] = useState('')

  const [openEmailEditor, setOpenEmailEditor] = useState(false)
  const [fromEmail, setFromEmail] = useState('')
  useEffect(() => {
    setOpenEmailEditor(false)

    return () => {}
  }, [mailID])

  const onOpenEditor = (msgOrigin, action='reply') => {
    window.open(`/email/${action}/${mailID || 0}`, `${action}-${mailID || 0}`,POPUP_FEATURES)
    console.log('first000', emailMsg)
    console.log('first', msgOrigin)
    if (typeof props.onOpenEditor === 'function') {
      props.onOpenEditor(msgOrigin, action);
    } else {
      const { from, to } = msgOrigin
      setOpenEmailEditor(true)
      setFromEmail(action === 'edit' ? from : to)
      setAction(action)
      // // setOpen(false)
    }
  }

  const { loading, mailData, orderDetail, postEmailResend } = useEmailDetail(mailID)
  const [showBindBtn, setShowBindBtn] = useState(false)
  useEffect(() => {
    setShowBindBtn(isEmpty(mailData.info?.MAI_COLI_SN))
    return () => {}
  }, [mailData.info?.MAI_COLI_SN])

  const handleResend = async () => {
    if (isEmpty(mai_sn)) {
      return false
    }
    try {
      await postEmailResend({ mai_sn, conversationid, actionId })
      // setOpen(false)
    } catch (err) {
      notification.error({
        message: '请求失败',
        description: err.message,
        placement: 'top',
        duration: 3,
      })
    }
  }
  const FileTypeIcon = ({fileName}) => {
    const ext = fileName.split('.').pop() || 'default';
    const Com = extTypeMapped[ext]?.icon || FileOutlined;
    const color = extTypeMapped[ext]?.color || 'inherit';
    return <Com style={{ color: color }} size={36} />;
  };

  /**
   * 根据状态, 显示操作
   * * 已保存: []
   * * 已发送: 回复, 转发
   * * 失败: 重发
   * todo: disabled 不显示
   */
  const ActionBtns = ({ className, ...props }) => {
    const { status } = mailData.info

    let btns = []

    if (mailData.info.MAI_Direction !== 1) {
      btns.push(<Button type='text' key={'set-done'} onClick={() => { alert('todo')}} icon={<MailCheckIcon className={'text-yellow-600'} />} size='small'>已处理</Button>)
    }
    // 没有关联订单的邮件`绑定订单`
    if (showBindBtn) {
      btns.push(<EmailBindFormModal key={'bind'} onBoundSuccess={() => setShowBindBtn(false)} {...{ conversationid, mai_sn, showBindBtn }} />)
      btns.push(<Divider key='divider1' type='vertical' className='mx-0' />)
    }

    switch (status) {
      case 'accepted':
        break
      case 'sent':
      case '': // 接收的邮件没有发送状态
        btns.push(
          <Tooltip key='reply-t' title='回复'>
          <Button key={'reply'} onClick={() => onOpenEditor(emailMsg.msgOrigin, 'reply')} size='small' type='text' icon={<ReplyIcon className='text-indigo-500' />}>
            {compactBtn ? '' : '回复'}
          </Button>
          </Tooltip>,
        )
        btns.push(
          <Tooltip key='replyall-t' title='回复全部'>
            <Button key={'replyall'} onClick={() => onOpenEditor(emailMsg.msgOrigin, 'replyall')} size='small' type='text' icon={<ReplyAllIcon className='text-indigo-500' />} >{compactBtn ? '' : '回复全部'}</Button>
          </Tooltip>,
        )
        btns.push(
          <Tooltip key='forward-t' title='转发'>
          <Button key={'forward'} onClick={() => onOpenEditor(emailMsg.msgOrigin, 'forward')} size='small' type='text' icon={<ShareForwardIcon className='text-primary' />}>{compactBtn ? '' : '转发'}</Button></Tooltip>,
        )
        break
      case 'failed':
        btns.push(
          <Tooltip key='resend-t' title='重发'>
          <Button key={'resend'} onClick={() => handleResend()} size='small' type='text' icon={<ResendIcon className='text-orange-500' />}>{compactBtn ? '' : '重发'}</Button></Tooltip>,
        )
        btns.push(
          <Tooltip key='edit-t' title='编辑'>
          <Button
            key={'edit'}
            onClick={() => onOpenEditor({ ...(emailMsg.msgOrigin || {}), content: mailData.content }, 'edit')}
            size='small'
            type='text'
            icon={<EditIcon className='text-indigo-500' />}>{compactBtn ? '' : '编辑'}</Button></Tooltip>,
        )
        break
      default:
        break
    }

    return <div className={`flex justify-end items-center gap-1  ${className || ''}`}>{btns}</div>
  }

  const variantCls = (variant) => {
    switch (variant) {
      case 'outline':
        return 'border-y-0 border-x border-solid border-neutral-200'
    }
  }

  return (
    <>
      <div ref={componentRef} className={`email-container h-full flex flex-col gap-0 divide-y divide-neutral-200 divide-solid *:p-2 *:border-0 bg-white ${variantCls(variant)}`} >
        <div className=''>
          <div className='flex flex-wrap justify-between'>
          <span className=' font-bold '>
            {loading ? <LoadingOutlined className='mr-1' /> : null}
            {mailData.info?.MAI_Subject || emailMsg?.msgOrigin?.subject}
          </span>
          <ActionBtns key='actions' className={'ml-auto'}/>
          </div>
          <Divider className='my-2' />
          <div className={['flex flex-wrap justify-end', window.innerWidth < 600 ? 'flex-col' : 'flex-row '].join(' ')}>
            <div className=' flex-auto basis-0 flex flex-wrap gap-2 mb-2 items-center'>
              <Avatar className='' style={TagColorStyle(mailData.info?.MAI_From, true)}>
                {(mailData.info?.MAI_From || '').substring(0, 1)}
              </Avatar>
              <div className=' flex flex-col '>
                {/* <span className=' font-bold text-base'>{mailData.info?.fromName}</span> */}
                <span className='text-neutral-500 text-wrap break-words break-all '>{mailData.info?.MAI_From}</span>
              </div>
            </div>
            <div className=' ml-auto flex flex-col justify-start gap-1 items-end'>
              {/* <ActionBtns /> */}
              <div className='text-xs '>{mailData.info?.MAI_SendDate || emailMsg.localDate}{mailData.info.MAI_Direction === 1 ? <SendPlaneFillIcon className='text-primary' /> : <InboxIcon className='text-indigo-500' />}</div>
            </div>
          </div>
          <div className='text-sm'>
            <span className='text-neutral-500 pr-2 w-14 inline-block text-justify' style={{ textAlignLast: 'justify' }}>
              收件人
            </span>
            {mailData.info?.MAI_To}
          </div>
          {mailData.info?.MAI_CS && (
            <div className='text-sm'>
              <span className='text-neutral-500 pr-2 w-12 inline-block text-justify' style={{ textAlignLast: 'justify' }}>
                抄送
              </span>
              {mailData.info.MAI_CS}
            </div>
          )}
          {mailData.info?.bcc && (
            <div className='text-sm'>
              <span className='text-neutral-500 pr-2 w-12 inline-block text-justify' style={{ textAlignLast: 'justify' }}>
                密送
              </span>
              {mailData.info.bcc}
            </div>
          )}
        </div>
        <div className='overflow-auto'>
          <Flex className={` divide-gray-200 divide-solid gap-0 ${compactBtn === false ? 'divide-y-0 divide-x' : 'flex-col-reverse divide-x-0 '}`}>
            {mailData.info?.mailType === 'text/html' ? (
              <EmailContent content={mailData.content} id={mailID} key={mailID} />
            ) : (
              <div className='mt-2 whitespace-pre-wrap' dangerouslySetInnerHTML={{ __html: mailData.content }}></div>
            )}
            {mailData.attachments.length > 0 && (
            <div className={`${compactBtn === false ? 'w-48' : 'border-b border-t-0'} overflow-hidden`}>
              <span>&nbsp;附件 ({mailData.attachments.length})</span>
              <List
                dataSource={mailData.attachments || []}
                size='small' className='[&_.ant-list-item]:p-1 [&_.ant-list-item]:justify-start'
                renderItem={(atta) => (
                  <List.Item>
                    <FileTypeIcon fileName={atta.ATI_Name} />
                    <Typography.Text ellipsis={{ tooltip: { title: atta.ATI_Name, placement: 'left' } }} className='text-inherit'>
                      <a href={`${EMAIL_ATTA_HOST}${atta.ATI_ServerFile}`} key={atta.ATI_SN} target='_blank' rel='noreferrer'>
                        {atta.ATI_Name}
                      </a>
                    </Typography.Text>
                  </List.Item>
                )}
              />
            </div>
            )}
          </Flex>
        </div>
      </div>
      {/* <EmailEditorPopup
        open={openEmailEditor}
        setOpen={setOpenEmailEditor}
        fromEmail={fromEmail}
        fromUser={mailData.info?.MAI_OPI_SN || order_opi}
        fromOrder={mailData.info?.MAI_COLI_SN || coli_sn}
        conversationid={conversationid}
        oid={orderDetail.order_no}
        customerDetail={orderDetail.customerDetail}
        // emailMsg={ReferEmailMsg}
        quoteid={mailID}
        // initial={{ ...initialPosition, ...initialSize }}
        mailData={void 0}
        action={action}
        key={`email-detail-inline-${action}_${mailID}`}
      /> */}
    </>
  )
}
export default EmailDetailInline
