'use client';

import { ActionIcon } from '@lobehub/ui';
import { Share2 } from 'lucide-react';
import dynamic from 'next/dynamic';
import { memo } from 'react';
import { Button } from 'antd';
import { useTranslation } from 'react-i18next';
import { Flexbox } from "react-layout-kit"

import { DESKTOP_HEADER_ICON_SIZE, MOBILE_HEADER_ICON_SIZE } from '@/const/layoutTokens';
import { useWorkspaceModal } from '@/hooks/useWorkspaceModal';
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';
import isEqual from "fast-deep-equal";

const ShareModal = dynamic(() => import('@/features/ShareModal'));

interface ShareButtonProps {
  mobile?: boolean;
  open?: boolean;
  setOpen?: (open: boolean) => void;
}

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

const ShareButton = memo<ShareButtonProps>(({ mobile, setOpen, open }) => {
  const [isModalOpen, setIsModalOpen] = useWorkspaceModal(open, setOpen);
  const [shareLoading] = useChatStore((s) => [s.shareLoading]);
    const {t} = useTranslation(['chat', 'common']);

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

    const [systemRole] = useAgentStore((s) => [agentSelectors.currentAgentSystemRole(s)]);
    const messages = useChatStore(chatSelectors.activeBaseChats, 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))
    const topicTitle = topic?.title || t('shareModal.exportTitle');
    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 (
    <>
      {/*<ActionIcon*/}
      {/*  icon={Share2}*/}
      {/*  loading={shareLoading}*/}
      {/*  onClick={() => setIsModalOpen(true)}*/}
      {/*  size={mobile ? MOBILE_HEADER_ICON_SIZE : DESKTOP_HEADER_ICON_SIZE}*/}
      {/*  title={t('share')}*/}
      {/*/>*/}
      {/*<ShareModal onCancel={() => setIsModalOpen(false)} open={isModalOpen} />*/}
      <Flexbox gap={16} horizontal={!isMobile}>
        <Button onClick={() => downloadCSV()} shape="round" style={{borderColor: '#2E62FF', color: "#2E62FF",fontSize: '13px',height: '30px'}}>会话导出</Button>
      </Flexbox>
    </>
  );
});

export default ShareButton;
