import {
  WhatsAppOutlined,
  FileAddOutlined,
  MailOutlined,
  PhoneOutlined,
  UserOutlined,
  FieldNumberOutlined,
  CompassOutlined,
  CalendarOutlined,
  EditOutlined,
  CheckOutlined,
  ReloadOutlined,
} from '@ant-design/icons'

import { useEffect, useState } from 'react'
import { Link } from 'react-router-dom'
import { App, Flex, Select, Tooltip, Divider, Typography, Skeleton, Checkbox, Drawer, Button, Form, Input } from 'antd'
import { useOrderStore, fetchSetRemindStateAction, OrderLabelDefaultOptions, OrderStatusDefaultOptions, remindStatusOptions } from '@/stores/OrderStore'
import { copy, isEmpty } from '@/utils/commons'
import { useShallow } from 'zustand/react/shallow'
import useConversationStore from '@/stores/ConversationStore'
import useAuthStore from '@/stores/AuthStore'
const OrderProfile = ({ coliSN, ...props }) => {
  const { notification, message } = App.useApp()
  const [formComment] = Form.useForm()
  const [formWhatsApp] = Form.useForm()
  const [formExtra] = Form.useForm()
  const [loading, setLoading] = useState(false)

  const [openOrderCommnet, setOpenOrderCommnet] = useState(false)
  const [openWhatsApp, setOpenWhatsApp] = useState(false)
  const [openExtra, setOpenExtra] = useState(false)

  const orderLabelOptions = copy(OrderLabelDefaultOptions)
  orderLabelOptions.unshift({ value: 0, label: '未设置', disabled: true })

  const orderStatusOptions = copy(OrderStatusDefaultOptions)
  const [orderDetail, customerDetail, fetchOrderDetail, setOrderPropValue, appendOrderComment, updateWhatsapp, updateExtraInfo] = useOrderStore((s) => [
    s.orderDetail,
    s.customerDetail,
    s.fetchOrderDetail,
    s.setOrderPropValue,
    s.appendOrderComment,
    s.updateWhatsapp,
    s.updateExtraInfo,
  ])

  const loginUser = useAuthStore((state) => state.loginUser)
  const currentOrder = useConversationStore(useShallow((state) => state.currentConversation?.coli_sn || ''))
  const orderId = coliSN || currentOrder

  const [orderRemindState, setOrderRemindState] = useState(orderDetail.remindstate)
  useEffect(() => {
    setOrderRemindState(orderDetail.remindstate)
  }, [orderDetail.remindstate])
  useEffect(() => {
    if (orderId) {
      setLoading(true)
      fetchOrderDetail(orderId)
        .finally(() => setLoading(false))
        .catch((reason) => {
          notification.error({
            message: '查询出错',
            description: reason.message,
            placement: 'top',
            duration: 60,
          })
        })
    }
    return () => {}
  }, [orderId])

  const handleSetRemindState = async (checkedValue) => {
    const state = checkedValue.filter((v) => v !== orderRemindState)
    const oldState = orderRemindState

    try {
      if (isEmpty(state)) {
        setOrderRemindState(null)
      } else {
        setOrderRemindState(state[0])
      }
      await fetchSetRemindStateAction({ coli_sn: coliSN, remindstate: state })
      message.success('设置成功')
    } catch (error) {
      notification.warning({ message: '设置失败', description: error.message, placement: 'top', duration: 60 })
      setOrderRemindState(oldState)
    }
  }

  const getCustomerName = () => {
    if (orderDetail.buytime > 0) return customerDetail.name + '(R' + orderDetail.buytime + ')'
    return customerDetail.name
  }

  const getPlanStatus = () => {
    return orderDetail.DidPlan === 0 ? '未做计划' : '已做计划'
  }

  return (
    <>
      <Skeleton active loading={loading}>
        <Flex gap='small' vertical={true} justify='space-between' className='p-2'>
          <Typography.Text>
            <FieldNumberOutlined className='pr-1' />
            {orderDetail.order_no}
          </Typography.Text>
          <Typography.Text>
            <UserOutlined className=' pr-1' />
            {getCustomerName()}
          </Typography.Text>
          <Typography.Text>
            <CompassOutlined className=' pr-1' />
            {orderDetail.MEI_Country}
          </Typography.Text>
          <Typography.Text>
            <PhoneOutlined className=' pr-1' />
            {customerDetail.phone}
          </Typography.Text>
          <Typography.Text>
            <MailOutlined className='pr-1' />
            {customerDetail.email}
          </Typography.Text>
          <Typography.Text>
            <WhatsAppOutlined className='pr-1' />
            {isEmpty(customerDetail.whatsapp_phone_number) ? (
              <Button type='text' onClick={() => setOpenWhatsApp(true)} size='small'>
                设置 WhatsApp
              </Button>
            ) : (
              <Link to={`/order/chat/${coliSN}`} state={orderDetail}>
                {customerDetail.whatsapp_phone_number}
              </Link>
            )}
          </Typography.Text>
          <Typography.Text>
            <Tooltip title='出发日期'>
              <CalendarOutlined className='pr-1' />
              {orderDetail.COLI_OrderStartDate}
            </Tooltip>
          </Typography.Text>
          <Typography.Text>
            <Tooltip title='计划状态'>
              <CheckOutlined className='pr-1' />
              {getPlanStatus()}
            </Tooltip>
          </Typography.Text>
        </Flex>
        <Divider orientation='left'>
          <Typography.Text strong>订单状态</Typography.Text>
        </Divider>
        <Flex gap='small' vertical={false} justify='space-between'>
          <Select
            className={`[&_.ant-select-selection-item]:text-gray-950`}
            key={'orderlabel'}
            size='small'
            style={{
              width: '100%',
            }}
            variant='underlined'
            onSelect={(value) => {
              setOrderPropValue(coliSN, 'orderlabel', value)
                .then(() => {
                  message.success('设置成功')
                })
                .catch((reason) => {
                  notification.error({
                    message: '设置出错',
                    description: reason.message,
                    placement: 'top',
                    duration: 60,
                  })
                })
            }}
            value={orderDetail.tags}
            options={orderLabelOptions}
          />
          <Select
            className={`[&_.ant-select-selection-item]:text-gray-950`}
            key={'orderstatus'}
            size='small'
            style={{
              width: '100%',
            }}
            variant='underlined'
            onSelect={(value) => {
              setOrderPropValue(coliSN, 'orderstatus', value)
                .then(() => {
                  message.success('设置成功')
                })
                .catch((reason) => {
                  notification.error({
                    message: '设置出错',
                    description: reason.message,
                    placement: 'top',
                    duration: 60,
                  })
                })
            }}
            value={orderDetail.states}
            options={orderStatusOptions}
          />
        </Flex>

        <Divider orientation='left'>
          <Typography.Text strong>催信</Typography.Text>
        </Divider>
        <Checkbox.Group key='substatus' className='px-2' value={[orderRemindState]} options={remindStatusOptions} onChange={handleSetRemindState} />

        <Divider orientation='left'>
          <Typography.Text strong>表单信息</Typography.Text>
          <Tooltip title='添加'>
            <FileAddOutlined
              className='pl-1'
              onClick={() => {
                setOpenOrderCommnet(true)
              }}
            />
          </Tooltip>
        </Divider>
        <p className='p-2 overflow-auto m-0 break-words whitespace-pre-wrap' dangerouslySetInnerHTML={{ __html: orderDetail.order_detail }}></p>

        <Divider orientation='left'>
          <Typography.Text strong>特殊要求</Typography.Text>
        </Divider>
        <Typography.Text>{orderDetail.customer_request}</Typography.Text>
        <Divider orientation='left'>
          <Typography.Text strong>外联备注</Typography.Text>
          {/* <Tooltip title='修改'>
            <EditOutlined className='pl-1' />
          </Tooltip> */}
        </Divider>
        <Typography.Text>{orderDetail.wl_memo}</Typography.Text>

        <Divider orientation='left'>
          <Typography.Text strong>附加信息</Typography.Text>
          <Tooltip title='修改'>
            <EditOutlined
              className='pl-1'
              onClick={() => {
                formExtra.setFieldsValue({ extra: orderDetail.COLI_Introduction })
                setOpenExtra(true)
              }}
            />
          </Tooltip>
        </Divider>
        <Typography.Text>{orderDetail.COLI_Introduction}</Typography.Text>
      </Skeleton>
      <Drawer title='添加表单信息' closable={{ 'aria-label': 'Close Button' }} onClose={() => setOpenOrderCommnet(false)} open={openOrderCommnet}>
        <Form
          layout={'vertical'}
          form={formComment}
          initialValues={{ comment: '' }}
          scrollToFirstError
          onFinish={(values) => {
            appendOrderComment(loginUser.userId, orderId, values.comment)
              .then(() => {
                notification.success({
                  message: '温性提示',
                  description: '添加表单信息成功',
                })
                setOpenOrderCommnet(false)
                formComment.setFieldsValue({ comment: '' })
              })
              .catch((reason) => {
                notification.error({
                  message: '添加出错',
                  description: reason.message,
                  placement: 'top',
                  duration: 60,
                })
              })
          }}>
          <Form.Item name='comment' label='表单信息' rules={[{ required: true, message: '请输入表单信息' }]}>
            <Input.TextArea rows={4} />
          </Form.Item>
          <Form.Item>
            <Button type='primary' htmlType='submit'>
              提交
            </Button>
          </Form.Item>
        </Form>
      </Drawer>
      <Drawer title='设置 WhatsApp' closable={{ 'aria-label': 'Close Button' }} onClose={() => setOpenWhatsApp(false)} open={openWhatsApp}>
        <Form
          layout={'vertical'}
          form={formWhatsApp}
          initialValues={{ number: '' }}
          scrollToFirstError
          onFinish={(values) => {
            updateWhatsapp(orderId, values.number)
              .then(() => {
                notification.success({
                  message: '温性提示',
                  description: '设置 WhatsApp 成功',
                })
                setOpenWhatsApp(false)
                formWhatsApp.setFieldsValue({ number: '' })
              })
              .catch((reason) => {
                notification.error({
                  message: '设置出错',
                  description: reason.message,
                  placement: 'top',
                  duration: 60,
                })
              })
          }}>
          <Form.Item name='number' label='WhatsApp' rules={[{ required: true, message: '请输入 WhatsApp 号码' }]}>
            <Input placeholder='国家代码+城市代码+电话号码' />
          </Form.Item>
          <Form.Item>
            <Button type='primary' htmlType='submit'>
              提交
            </Button>
          </Form.Item>
        </Form>
      </Drawer>
      <Drawer title='设置附加信息' closable={{ 'aria-label': 'Close Button' }} onClose={() => setOpenExtra(false)} open={openExtra}>
        <Form
          layout={'vertical'}
          form={formExtra}
          scrollToFirstError
          onFinish={(values) => {
            updateExtraInfo(orderId, values.extra)
              .then(() => {
                notification.success({
                  message: '温性提示',
                  description: '设置附加信息成功',
                })
                setOpenExtra(false)
              })
              .catch((reason) => {
                notification.error({
                  message: '设置出错',
                  description: reason.message,
                  placement: 'top',
                  duration: 60,
                })
              })
          }}>
          <Form.Item name='extra' label='附加信息' rules={[{ required: true, message: '请输入附加信息' }]}>
            <Input />
          </Form.Item>
          <Form.Item>
            <Button type='primary' htmlType='submit'>
              提交
            </Button>
          </Form.Item>
        </Form>
      </Drawer>
    </>
  )
}

export default OrderProfile
