import { useEffect, useState, useRef } from 'react';
import { useParams, useNavigate, useLocation } from 'react-router-dom';
import { Dropdown, Input } from 'antd';
import { fetchOrderConversationsList, fetchConversationItemClose, fetchMessages, MESSAGE_PAGE_SIZE, } from '@/actions/ConversationActions';
import { ChatItem } from 'react-chat-elements';
import { isEmpty } from '@/utils/utils';
import useConversationStore from '@/stores/ConversationStore';
import useAuthStore from '@/stores/AuthStore';

/**
 * []
 */
const Conversations = ({ mobile }) => {
  const routerReplace = mobile === undefined ? true : false; // : true;
  const routePrefix = mobile === undefined ? `/order/chat` : `/m/chat`;
  const { state: orderRow } = useLocation();
  const { coli_guest_WhatsApp } = orderRow || {};
  const { order_sn } = useParams();
  const navigate = useNavigate();
  const userId = useAuthStore((state) => state.loginUser.userId);
  const initialState = useConversationStore((state) => state.initialState);
  const [currentConversation, setCurrentConversation] = useConversationStore((state) => [state.currentConversation, state.setCurrentConversation]);
  const conversationsList = useConversationStore((state) => state.conversationsList);
  const addToConversationList = useConversationStore((state) => state.addToConversationList);
  const delConversationitem = useConversationStore((state) => state.delConversationitem);

  const [tabSelectedConversation, setTabSelectedConversation] = useState({});
  const [tabCnt, setTabCnt] = useState(-1);

  useEffect(() => {
    if (mobile !== undefined) {
      setCurrentConversation({});
    }

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


  const [dataSource, setDataSource] = useState(conversationsList);
  useEffect(() => {
    setDataSource(conversationsList);
    return () => {};
  }, [conversationsList]);

  const [switchToC, setSwitchToC] = useState({});
  const [shouldFetchCList, setShouldFetchCList] = useState(true);
  useEffect(() => {
    if (order_sn && shouldFetchCList && initialState) {
      getOrderConversationList(order_sn);
    }

    return () => {};
  }, [order_sn, shouldFetchCList, initialState]);

  const getOrderConversationList = async (colisn) => {
    const { whatsapp_phone_number } = switchToC;
    const whatsappID = coli_guest_WhatsApp || whatsapp_phone_number || '';
    let findCurrentOrderChats = conversationsList.filter((item) => `${item.coli_sn}` === `${colisn}`);
    let findCurrentIndex = isEmpty(findCurrentOrderChats) ? -1 : 0; // findCurrentOrderChats.length-1;
    let findCurrent = findCurrentOrderChats[findCurrentIndex];
    if (findCurrentIndex !== -1) {
      addToConversationList(findCurrentOrderChats);
    } else if (!isEmpty(whatsappID)) {
      const data = await fetchOrderConversationsList({ opisn: userId, colisn: colisn, whatsappid: whatsappID });
      if (!isEmpty(data)) {
        addToConversationList(data);
        findCurrentIndex = 0; // data.length-1; // data.lastIndexOf((item) => item.coli_sn === Number(colisn));
        findCurrent = data[findCurrentIndex];
      } else {
        // findCurrentIndex = conversationsList.findIndex((item) => item.coli_sn === Number(colisn)); // data.findIndex((item) => item.sn === currentConversation.sn);
      }
    }
    if (findCurrentIndex >= 0) {
      setCurrentConversation(findCurrent);
    } else {
      // reset chat window
      setCurrentConversation({ sn: '', customer_name: '', coli_sn: order_sn });
      return false;
    }
  };

  const onSwitchConversation = async (item) => {
    setCurrentConversation(item);
    if (isEmpty(item.coli_sn)) {
      navigate(routePrefix, { replace: true });
    } else {
      setSwitchToC(item);
      setShouldFetchCList(false);
      navigate(`${routePrefix}/${item.coli_sn}`, { replace: routerReplace });
    }
    // if (!isEmpty(item.coli_sn)) {
    //   setSwitchToC(item);
    //   setShouldFetchCList(false);
    //   navigate(`/order/chat/${item.coli_sn}`, { replace: true });
    // } else {
    //   navigate(`/order/chat`, { replace: true });
    // }
    // switchConversation(item);
  };

  const handleConversationItemClose = async (item) => {
    await fetchConversationItemClose({ conversationid: item.sn, opisn: item.opi_sn });
    delConversationitem(item);
    if (String(order_sn) === String(item.coli_sn)) {
      navigate(routePrefix, { replace: routerReplace });
    }
  };

  const searchInputRef = useRef(null);
  const [searchContent, setSearchContent] = useState('');
  const handleSearchConversations = (val) => {
    if (val.toLowerCase().trim() !== '') {
      const res = conversationsList.filter(
        (item) => (item.whatsapp_name.toLowerCase()).includes(val.toLowerCase().trim())
          || (item.whatsapp_phone_number.toLowerCase()).includes(val.toLowerCase().trim())
          || (item.coli_id.toLowerCase()).includes(val.toLowerCase().trim())
      );
      setDataSource(res);
      return false;
    }
    setDataSource(conversationsList);
  };

  return (
    <div className='flex flex-col h-inherit'>
      <div className=''>
        <Input.Search
          className=''
          ref={searchInputRef}
          onSearch={handleSearchConversations}
          allowClear
          value={searchContent}
          onChange={(e) => {
            setSearchContent(e.target.value);
            handleSearchConversations(e.target.value);
            setTabCnt(-1);
            setTabSelectedConversation({});
          }}
          onKeyDown={e => {
            if (e.key === 'Tab') {
              e.preventDefault();
              const _this = tabCnt >= dataSource.length-1 ? 0 : tabCnt + 1
              setTabCnt(_this);
              setTabSelectedConversation(dataSource[_this]);
            }
          }}
          onPressEnter={(e) => {
            handleSearchConversations(e.target.value);
            searchInputRef.current.blur();
            onSwitchConversation(dataSource[(tabCnt < 0 ? 0 : tabCnt)]);
            setTabCnt(-1);
            setTabSelectedConversation({});
            return false;
          }}
          placeholder='搜索名称'
        />
      </div>
      <div className='flex-1 overflow-x-hidden overflow-y-auto relative'>
        {dataSource.map((item) => (
          <Dropdown
            key={item.sn}
            menu={{
              items: [{ label: '关闭会话', key: 'close', danger: true }],
              onClick: ({ key, domEvent }) => {
                domEvent.stopPropagation();
                switch (key) {
                  case 'close':
                    return handleConversationItemClose(item);

                  default:
                    return;
                }
              },
            }}
            trigger={['contextMenu']}>
            <ChatItem
              {...item}
              key={item.sn}
              id={item.sn}
              letterItem={{ id: item.whatsapp_name || item.whatsapp_phone_number, letter: (item.whatsapp_name || item.whatsapp_phone_number).slice(0, 5) }}
              alt={item.whatsapp_name}
              title={item.whatsapp_name || item.whatsapp_phone_number}
              subtitle={item.coli_id}
              date={item.last_received_time}
              unread={item.unread_msg_count}
              className={
                [String(item.sn) === String(currentConversation.sn) ? '__active text-primary  bg-whatsapp-bg' : '',
                String(item.sn) === String(tabSelectedConversation?.sn) ? ' bg-neutral-200' : ''
              ].join(' ')
              }
              onClick={() => onSwitchConversation(item)}
            />
          </Dropdown>
        ))}
      </div>
    </div>
  );
};
export default Conversations;
