import { useEffect, useState } from 'react'
import { ReloadOutlined, ReadOutlined, RightOutlined, LeftOutlined, SearchOutlined, MailOutlined } from '@ant-design/icons'
import { Flex, Button, Tooltip, List, Form, Row, Col, Input, Checkbox, DatePicker, Switch, Breadcrumb, Skeleton } from 'antd'
import dayjs from 'dayjs'
import { useEmailList } from '@/hooks/useEmail'
import { isEmpty } from '@/utils/commons'
import { MailboxDirIcon } from './MailboxDirIcon'
import { AttachmentIcon, MailCheckIcon, MailOpenIcon } from '@/components/Icons'
import NewEmailButton from './NewEmailButton'
import MailOrderSearchModal from './MailOrderSearchModal'

const { RangePicker } = DatePicker

const PAGE_SIZE = 50 // 每页显示条数

const MailBox = ({ mailboxDir, onMailItemClick, ...props }) => {
  const DATE_RANGE_PRESETS = [
    {
      label: '本周',
      value: [dayjs().startOf('w'), dayjs().endOf('w')],
    },
    {
      label: '上周',
      value: [dayjs().startOf('w').subtract(7, 'days'), dayjs().endOf('w').subtract(7, 'days')],
    },
    {
      label: '本月',
      value: [dayjs().startOf('M'), dayjs().endOf('M')],
    },
    {
      label: '上月',
      value: [dayjs().subtract(1, 'M').startOf('M'), dayjs().subtract(1, 'M').endOf('M')],
    },
    {
      label: '前三月',
      value: [dayjs().subtract(2, 'M').startOf('M'), dayjs().endOf('M')],
    },
    {
      label: '本年',
      value: [dayjs().startOf('y'), dayjs().endOf('y')],
    },
  ]
  const [form] = Form.useForm()
  const [selectedItems, setSelectedItems] = useState([])
  const { mailList, loading, error, refresh, markAsRead, markAsProcessed } = useEmailList(mailboxDir)

  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: PAGE_SIZE,
    total: 0,
    pagedList: [],
  })

  useEffect(() => {
    if (mailList) {
      const total = mailList.length
      const pageCount = Math.ceil(total / PAGE_SIZE)

      setPagination((prev) => ({
        ...prev,
        total,
        pageCount,
        current: 1, // 重置到第一页
        pagedList: getPagedData(mailList, 1),
      }))
    }
  }, [mailList])

  const getPagedData = (data, currentPage) => {
    const startIndex = (currentPage - 1) * PAGE_SIZE
    const endIndex = Math.min(startIndex + PAGE_SIZE, data.length)
    return data.slice(startIndex, endIndex)
  }

  const prePage = () => {
    if (pagination.current > 1) {
      const newCurrent = pagination.current - 1
      setPagination((prev) => ({
        ...prev,
        current: newCurrent,
        pagedList: getPagedData(mailList, newCurrent),
      }))
    }
  }

  const nextPage = () => {
    if (pagination.current < Math.ceil(pagination.total / PAGE_SIZE)) {
      const newCurrent = pagination.current + 1
      setPagination((prev) => ({
        ...prev,
        current: newCurrent,
        pagedList: getPagedData(mailList, newCurrent),
      }))
    }
  }

  const mailItemRender = (item) => {
    const isOrderNode = mailboxDir.COLI_SN > 0
    const orderNumber = isEmpty(item.MAI_COLI_ID) || isOrderNode ? '' : item.MAI_COLI_ID + ' - '
    const countryName = isEmpty(item.CountryCN) ? '' : '[' + item.CountryCN + '] '
    const mailStateClass = item.MOI_ReadState === 0 ? 'font-bold' : ''
    const hasAtta = item.MAI_Attachment !== 0 ? <AttachmentIcon className='text-blue-500' /> : null
    return (
      <li className={`flex border border-solid border-t-0 border-x-0 border-gray-200 hover:bg-neutral-50 active:bg-gray-200 p-2 ${props.currentActiveMailItem === item.MAI_SN ? 'bg-neutral-100' : ''}`}>
        <div className=''>
          <Checkbox
            checked={selectedItems.some((i) => i.MAI_SN === item.MAI_SN)}
            onClick={(e) => {
              const isChecked = e.target.checked
              const updatedSelection = isChecked ? [...selectedItems, item] : selectedItems.filter((item) => item.MAI_SN !== item.MAI_SN)
              setSelectedItems(updatedSelection)
            }}></Checkbox>
        </div>
        <div
          className='flex-1 pl-2'
          onClick={() => {
            onMailItemClick(item)
          }}>
          <Flex gap='small' vertical={true} justify='space-between' className='cursor-pointer'>
            <div>
              {orderNumber}
              <span className={mailStateClass}>{item.MAI_Subject}</span>
              {hasAtta}
            </div>
            <span className='text-neutral-500 text-wrap break-words break-all '>{countryName + item.SenderReceiver + ' ' + item.SRDate}</span>
          </Flex>
        </div>
      </li>
    )
  }

  return (
    <>
      <div className='bg-white h-auto px-1 flex gap-1 items-center'>
        <Flex wrap gap='middle' justify={'center'} className='min-w-30 px-1'>
          <Tooltip title='全选'>
            <Checkbox
              indeterminate={selectedItems.length > 0 && selectedItems.length < pagination.pagedList.length}
              checked={pagination.pagedList.length === 0 ? false : pagination.pagedList.every((item) => selectedItems.some((selected) => selected.MAI_SN === item.MAI_SN))}
              onChange={(e) => {
                const isChecked = e.target.checked
                if (isChecked) {
                  setSelectedItems((prev) => [...prev, ...pagination.pagedList])
                } else {
                  setSelectedItems([])
                }
              }}></Checkbox>
          </Tooltip>
          <Tooltip title='刷新'>
            <Button shape='circle' type='text' size='small' icon={<ReloadOutlined />} onClick={refresh} />
          </Tooltip>
        </Flex>

        <NewEmailButton />
            <Button
              size='small'
              icon={<MailOpenIcon />}
              onClick={() => {
              markAsRead(selectedItems.map((item) => item.MAI_SN)).then(() => setSelectedItems([]))
              }}
            >已读</Button>
            <Button
              size='small'
              icon={<MailOutlined />}
              onClick={() => {
              console.info('未读未实现')
              }}
            >未读</Button>
            <Button
              size='small'
              icon={<MailCheckIcon />}
              onClick={() => {
              markAsProcessed(selectedItems.map((item) => item.MAI_SN)).then(() => setSelectedItems([]))
              }}
            >已处理</Button>
        <MailOrderSearchModal />
      </div>
      <div className='bg-white h-auto p-1 flex gap-1 items-center hidden'>
        <Form
          form={form}
          initialValues={{}}
          // onFinish={handleSubmit}
        >
          <Row justify='start' gutter={16}>
            <Col span={10}>
              <Form.Item label='订单号' name='orderNumber'>
                <Input placeholder='订单号' allowClear />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label='日期' name='confirmDateRange'>
                <RangePicker allowClear={true} inputReadOnly={true} presets={DATE_RANGE_PRESETS} />
              </Form.Item>
            </Col>
            <Col span={1} offset={1}>
              <Button type='primary' htmlType='submit'>
                搜索
              </Button>
            </Col>
          </Row>
        </Form>
      </div>

      <div className='bg-white overflow-y-auto px-2' style={{ height: 'calc(100vh - 198px)' }}>
        <Skeleton active loading={loading}>
          <List
            loading={loading}
            header={
              <Flex align='center' justify='space-between'>
                <Breadcrumb
                  items={props.breadcrumb.map((bc) => {
                    return {
                      title: (
                        <>
                          <MailboxDirIcon type={bc?.iconIndex} />
                          <span>{bc.title}</span>
                        </>
                      ),
                    }
                  })}
                />
                <Flex align='center' justify='space-between'>
                  <span>已选: {selectedItems.length} 项；</span>
                  <span>
                    {(pagination.current - 1) * PAGE_SIZE + 1}-{Math.min(pagination.current * PAGE_SIZE, pagination.total)} of {pagination.total}
                  </span>
                  <Button
                    icon={<LeftOutlined />}
                    type='text'
                    onClick={() => {
                      prePage()
                    }}
                    iconPosition={'end'}></Button>
                  <Button
                    icon={<RightOutlined />}
                    type='text'
                    onClick={() => {
                      nextPage()
                    }}
                    iconPosition={'end'}></Button>
                </Flex>
              </Flex>
            }
            itemLayout='vertical'
            pagination={false}
            dataSource={pagination.pagedList}
            renderItem={mailItemRender}
          />
        </Skeleton>
      </div>
    </>
  )
}

export default MailBox
