// import { Form, type FormItemProps, Icon, copyToClipboard } from '@lobehub/ui';
import { Button } from 'antd';
import isEqual from 'fast-deep-equal';
// import { CopyIcon } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import { Flexbox } from 'react-layout-kit';

// import { FORM_STYLE } from '@/const/layoutTokens';
import { useIsMobile } from '@/hooks/useIsMobile';
import { useAgentStore } from '@/store/agent';
import { agentSelectors } from '@/store/agent/selectors';
import { useChatStore } from '@/store/chat';
import { chatSelectors, topicSelectors } from '@/store/chat/selectors';
import { FieldType } from './type';
import { LOADING_FLAT } from '@/const/message';
import { stringify as csvStringify } from 'csv-stringify';

const DEFAULT_FIELD_VALUE: FieldType = {
  includeTool: true,
  includeUser: true,
  withRole: true,
  withSystemRole: false,
};

const ShareText = memo(() => {
  // const [fieldValue, setFieldValue] = useState(DEFAULT_FIELD_VALUE);
  const { t } = useTranslation(['chat', 'common']);

  // const { message } = App.useApp();

  const [systemRole] = useAgentStore((s) => [agentSelectors.currentAgentSystemRole(s)]);
  const messages = useChatStore(chatSelectors.currentChats, isEqual);
  const topic = useChatStore(topicSelectors.currentActiveTopic, isEqual);
  console.log(systemRole,messages,'83737373737')
  let messagesNew = messages
    .filter((m) => m.content !== LOADING_FLAT)
    .filter((m) => (!DEFAULT_FIELD_VALUE.includeUser ? m.role !== 'user' : true))
    .filter((m) => (!DEFAULT_FIELD_VALUE.includeTool ? m.role !== 'tool' : true))

  console.log(messagesNew,'111111111111111')
  const topicTitle = topic?.title || t('shareModal.exportTitle');
  console.log(topicTitle,'22222222222222222')
  const isMobile = useIsMobile();
  const downloadCSV = () => {
    const data = [
        ["question", "answer"],
    ];
    let arrItem:string[] = [];
    messagesNew.forEach((chat)=> {
       if (chat.role === 'assistant') {
          arrItem.push(chat.content)
       } else if(chat.role === 'user') {
          arrItem.unshift(chat.content)
       }
       if(arrItem.length >= 2) {
         data.push(arrItem)
         arrItem = [];
       }
    })
    console.log(data,'9999111111')
    // 将数据转换为CSV字符串
    let csvContent = "";
    csvStringify(data, (err, output) => {
      if (err) {
        console.error('Error generating CSV:', err);
        return;
      }

      // 输出 CSV 字符串
      console.log(output,'66666666666666');
      csvContent = output

      // 创建一个Blob对象
      const blob = new Blob([csvContent], { type: 'text/csv' });

      // 创建一个URL并指向Blob对象
      const url = URL.createObjectURL(blob);

      // 创建一个隐藏的<a>标签并点击它以触发下载
      const a = document.createElement('a');
      a.setAttribute('hidden', '');
      a.setAttribute('href', url);
      a.setAttribute('download', topicTitle + '.csv');
      document.body.append(a);
      a.click();

      // 移除<a>标签
      a.remove();

      // 释放URL对象
      URL.revokeObjectURL(url);
    });
  }
  return (
    <Flexbox gap={16} horizontal={!isMobile}>
      <Button onClick={() => downloadCSV()} shape="round" style={{borderColor: '#2E62FF', color: "#2E62FF",fontSize: '13px',height: '30px'}}>会话导出</Button>
    </Flexbox>
  );
});

export default ShareText;
