import {forwardRef, memo, useState} from 'react';
import {request} from "../../../../utils/request";
import {Button, Modal} from 'antd';
import {ProChat} from '@ant-design/pro-chat'
import {styled} from 'styled-components'
import {useNavigate} from 'react-router-dom'
import {useAppDispatch} from '../../../../redux/configureStore.js'
import {appActions} from '../../../slice'
import {mainActions} from "../slice";
import useI18NPrefix from "../../../hooks/useI18NPrefix";

const component = forwardRef(({children},ref)=>{
  const t = useI18NPrefix('global');
  const [isModalOpen, setIsModalOpen] = useState(false);
  const navigate = useNavigate();
  const dispatch = useAppDispatch();

  const handleCancel = () => {
    setIsModalOpen(false);
  };
  const startTour = (path)=>{
    setIsModalOpen(false)
    dispatch(appActions.setupTour(path))
    dispatch(appActions.startTour(true))
    dispatch(mainActions.updatePathname(path))
    navigate(path)
  }

  return (
    <>
      <div ref={ref} onClick={()=>{setIsModalOpen(true)}}>
        {children}
      </div>
      <Modal
        width="100vh"
        title={t("title.intelligentWizard")}
        open={isModalOpen}
        footer={null}
        maskClosable={false}
        onCancel={handleCancel}
      >
        <Container>
          <ProChat
            style={{height:'60vh'}}
            chatItemRenderConfig={{
              contentRender: (info, defaultContent) => {
                try {
                  const {originData} = info;
                  //const {msg,path} = JSON.parse(defaultContent.props.message)
                  // const newContent = {
                  //   ...defaultContent,
                  //   props:{
                  //     ...defaultContent.props,
                  //     message:msg,
                  //   }
                  // }
                  const list = JSON.parse(defaultContent.props.message)
                  const toolRes = list.find(item=>item.type==="tool_response")
                  if (toolRes) {
                    const {output} = JSON.parse(toolRes.content)
                    const {text,route} = output;
                    const newContent = {
                      ...defaultContent,
                      props:{
                        ...defaultContent.props,
                        message:text,
                      }
                    }
                    return (
                      <div>
                        <Content >{newContent}</Content>
                        {originData.role==="assistant" && route && <Button onClick={()=>startTour(route[1])}>前往</Button>}
                      </div>
                    )
                  }
                  return defaultContent
                }catch (e) {
                  return defaultContent
                }

              }
            }}
            helloMessage="欢迎使用智能向导 ，我是你的专属机器人，这是我们的系统主页：[Index System](http://localhost:5173/main) ，如果您有系统操作上的不解你可以对我进行提问。"
            // request={async (messages) => {
            //   const {content} = messages[messages.length-1]
            //   const mockedData = mockMessages[content];
            //   if (mockedData){
            //     return new Response(JSON.stringify(mockedData))
            //   }
            //   return new Response('对不起，我目前只能回答系统操作相关的问题！')
            // }}
            request={async (params) =>{
              const {content} = params[params.length-1]

              const {messages} = await request({
                url: 'https://api.coze.cn/open_api/v2/chat',
                data: {
                  "conversation_id": "123456778",
                  "bot_id": "7399597820698722367",
                  "user": "29032201862555",
                  "query": content,
                  "stream": false
                },
                headers:{
                  'Authorization': 'Bearer pat_7poEb4ujIp1vCNHZIOVwljTnES2puEqWXR7hoOTvYH2OlsxRHm7Y3mIECRHlnzd4',
                  'Content-Type': 'application/json',
                  'Accept': '*/*',
                  'Host': 'api.coze.cn',
                  'Connection': 'keep-alive',
                },
                method: "POST",
              })
              return JSON.stringify(messages)
            }}
          />
        </Container>
      </Modal>
    </>

  )
})

const Container = styled.div`
  background: ${p=>p.theme.colorBgTextHover};
`
const Content = styled.div`
  .ant-pro-chat-list-item-message-content{
    background-color: ${p=>p.theme.colorBgTextHover};
    p {
      color: ${p=>p.theme.colorText};
    }
  }
`
export const ChatPanel = memo(component)
