import React, { useState, useEffect } from 'react';
import styles from './style/index.module.less';
import { Button, Divider, Input, Space, Table, Radio, Pagination, Modal, Message } from '@arco-design/web-react';
import { IconSearch } from '@arco-design/web-react/icon';
import { exportComponent, getCooperationComponentList, getMyComponentList, remove } from '@/api/componentBase';
import { componentRelease, componentRevoke } from '@/api/componentRelease';
import { ComponentItem } from '@/api/interface';
import AddComponentModal from '@/pages/componentDevelopment/componentList/addComponentModal';
import HandleButtonGroup from '@/pages/componentDevelopment/componentList/handleButtonGroup';
import {
  componentStatusConstant,
  componentStatusDict,
  publicStatusDict,
  publishStatusDict
} from '@/const/isdp/componentBase';
import dayjs from 'dayjs';
import { getReviewGroupByNew } from '@/api/componentMarket';

const Group = Radio.Group;

const GlobalVarContainer = () => {
  const [selectedItem, setSelectedItem] = useState('我的组件');
  const [selectComponent, setSelectComponent] = useState(null);
  const [componentData, setComponentData] = useState<ComponentItem[]>([]);
  const [pagination, setPagination] = useState({
    totalCount: 0,
    pageSize: 10,
    totalPage: 0,
    currPage: 1
  });
  const [loading, setLoading] = useState(false);
  const [visible, setVisible] = useState(false);

  const menuItems = [
    {
      key: '1',
      label: '我的组件',
      icon: '/ideContainer/icon/myComp.png',
      activeIcon: '/ideContainer/icon/myComp_active.png'
    },
    {
      key: '2',
      label: '协同组件',
      icon: '/ideContainer/icon/teamComp.png',
      activeIcon: '/ideContainer/icon/teamComp_active.png'
    },
    {
      key: '3',
      label: '组件审核',
      icon: '/ideContainer/icon/compAudit.png',
      activeIcon: '/ideContainer/icon/compAudit_active.png'
    }
  ];

  const columns = [
    {
      title: '组件名称',
      dataIndex: 'name'
    },
    {
      title: '组件标识',
      dataIndex: 'projectId'
    },
    {
      title: '分类',
      dataIndex: 'componentClassify'
    },
    {
      title: '创建人',
      dataIndex: 'createUserName'
    },
    {
      title: '代码语言',
      dataIndex: 'codeLanguage'
    },
    {
      title: '组件类型',
      dataIndex: 'type',
      render: (_, record) => {
        return (
          <span>{record.type === 'normal' ? '普通组件' : '监听组件'}</span>
        );
      }
    },
    {
      title: '组件状态',
      dataIndex: 'componentStatus',
      render: (_, record) => {
        const formattedData = componentStatusDict.find(item => item.value === componentStatusConstant[record.componentStatus]) || { label: '' };
        return (
          <span>{formattedData.label}</span>
        );
      }
    },
    {
      title: '发布状态',
      dataIndex: 'publicStatus',
      render: (_, record) => {
        const formattedData = publicStatusDict.find(item => item.value === record.publicStatus) || { label: '' };
        return (
          <span>{formattedData.label}</span>
        );
      }
    },
    {
      title: '公开状态',
      dataIndex: 'publishStatus',
      render: (_, record) => {
        const formattedData = publishStatusDict.find(item => item.value === record.publishStatus) || { label: '' };
        return (
          <span>{formattedData.label}</span>
        );
      }
    },
    {
      title: '修改时间',
      dataIndex: 'updateTime',
      render: (_, record) => {
        return (
          <span>{dayjs(record.updateTime).format('YYYY-MM-DD HH:mm:ss')}</span>
        );
      }
    },
    {
      title: '操作',
      dataIndex: 'operations',
      render: (_, record, index) => (
        <HandleButtonGroup
          row={record}
          index={index}
          onHandlePublishComponent={(row) => {
            // TODO: 实现发布组件逻辑
            console.log('Handle publish component', row);
          }}
          onGoToReview={(row) => {
            // TODO: 实现查看审核逻辑
            console.log('Go to review', row);
          }}
          onPublishOrRevokeComponent={async (action, identifier, version) => {
            try {
              if (action === 'publish') {
                await componentRelease({ identifier, version });
                Message.success('组件公开成功');
              }
              else if (action === 'revoke') {
                await componentRevoke({ identifier, version });
                Message.success('组件撤销成功');
              }
              // 重新获取数据以更新状态
              fetchComponentData();
            } catch (error) {
              console.error('操作失败:', error);
              Message.error(`组件${action === 'publish' ? '公开' : '撤销'}失败: ${error.message || ''}`);
            }
          }}
          onNavTo={(id, type) => {
            // TODO: 实现导航逻辑
            console.log('Nav to', id, type);
          }}
          onSourceCodeView={(row) => {
            // 跳转到组件编码Tab，并传递localProjectPath参数
            const event = new CustomEvent('navigateToTab', {
              detail: {
                path: 'componentCoding',
                localProjectPath: row.localProjectPath
              }
            });
            document.dispatchEvent(event);
          }}
          onShowEdit={(row, index) => {
            setSelectComponent(row);
            setVisible(true);
          }}
          onCopyHandler={(row) => {
            // TODO: 实现组件复制逻辑
            console.log('Copy handler', row);
          }}
          onShareCollaboration={(row) => {
            // TODO: 实现分享协作逻辑
            console.log('Share collaboration', row);
          }}
          onExportComponent={(id) => {
            // TODO: 实现导出组件逻辑
            console.log('Export component', id);
            exportComponent(id);
          }}
          onStopComponentShow={(row) => {
            // TODO: 实现下架组件逻辑
            console.log('Stop component show', row);
          }}
          onRowDel={(row) => {
            // 显示确认框
            Modal.confirm({
              title: '确认删除',
              content: `确定要删除组件 "${row.name}" 吗？此操作不可恢复。`,
              okButtonProps: { status: 'danger' },
              onOk: async () => {
                try {
                  const res = await remove(row.id);
                  console.log('res:', res);
                  Message.success('组件删除成功');
                  // 重新获取数据
                  fetchComponentData();
                } catch (error) {
                  console.error('删除组件失败:', error);
                  Message.error('组件删除失败');
                }
              }
            });
          }}
        />
      )
    }
  ];

  useEffect(() => {
    if (selectedItem === '我的组件' || selectedItem === '协同组件') {
      fetchComponentData();
    }
    else if (selectedItem === '组件审核') {
      fetchComponentReview();
    }
  }, [selectedItem, pagination.currPage, pagination.pageSize]);

  // 获取组件列表数据
  const fetchComponentData = async () => {
    setLoading(true);
    const apiMap = {
      '我的组件': getMyComponentList,
      '协同组件': getCooperationComponentList
    };
    try {
      const res: any = await apiMap[selectedItem]({
        currPage: pagination.currPage,
        pageSize: pagination.pageSize
      });

      setComponentData(res.data.list);
      setPagination({
        totalCount: res.data.totalCount,
        pageSize: res.data.pageSize,
        totalPage: res.data.totalPage,
        currPage: res.data.currPage
      });
    } catch (error) {
      console.error('获取组件列表失败:', error);
    } finally {
      setLoading(false);
    }
  };

  // 获取组件审核列表数据
  const fetchComponentReview = async () => {
    const res: any = await getReviewGroupByNew({
      queryType: 'create',
      current: pagination.currPage,
      size: pagination.pageSize
    });

    console.log('组件审核列表:', res);
  };

  const handlePageChange = (page: number, pageSize?: number) => {
    setPagination({
      ...pagination,
      currPage: page,
      pageSize: pageSize || pagination.pageSize
    });
  };


  return (
    <>
      <div className={styles['comp-list-container']}>
        {/*左侧菜单*/}
        <div className={styles['comp-list-menu']}>
          {menuItems.map((item, index) => (
            <div
              key={index}
              className={selectedItem === item.label ? styles['selected'] : ''}
              onClick={() => setSelectedItem(item.label)}
            >
              <img src={selectedItem === item.label ? item.activeIcon : item.icon} alt=""
                   style={{ width: 20, height: 20, marginRight: 12 }} />
              <span>{item.label}</span>
            </div>
          ))}
        </div>
        <div className={styles['comp-list-content']}>
          {/*头部*/}
          <div className={styles['comp-list-header']}>
            <div className={styles['comp-list-search']}>
              <Space>
                <Input
                  prefix={<IconSearch />}
                  placeholder={'搜索'}
                  style={{ width: 236 }}
                />
                <Button
                  type="primary"
                  style={{ marginLeft: 5, borderRadius: 4 }}
                >
                  搜索
                </Button>
              </Space>
            </div>
            <div className={styles['comp-list-handle']}>
              <Radio.Group defaultValue={'Beijing'} name="button-radio-group">
                {['未设计', '编码中', '已部署'].map((item) => {
                  return (
                    <Radio key={item} value={item}>
                      {({ checked }) => {
                        return (
                          <Button tabIndex={-1} key={item} shape="round" type={checked ? 'primary' : 'default'}>
                            {item}
                          </Button>
                        );
                      }}
                    </Radio>
                  );
                })}
              </Radio.Group>
              {selectedItem === '我的组件' && <Space split={<Divider type="vertical" />}>
                <Button type="secondary" style={{ borderRadius: 4 }}>生成组件</Button>
                <Button type="outline" style={{ borderRadius: 4 }}>导入组件</Button>
                <Button type="primary" style={{ borderRadius: 4 }} onClick={() => {
                  setSelectComponent(null);
                  setVisible(true);
                }}>+
                  新增组件</Button>
              </Space>}
            </div>

          </div>
          {/*数据列表*/}
          <div className={styles['comp-list-list']}>
            <Table
              columns={columns}
              data={componentData}
              loading={loading}
              pagination={false}
            />
            <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 16 }}>
              <Pagination
                current={pagination.currPage}
                pageSize={pagination.pageSize}
                total={pagination.totalCount}
                onChange={handlePageChange}
              />
            </div>
          </div>
        </div>
      </div>

      {/*新增弹窗*/}
      <AddComponentModal
        visible={visible}
        baseInfo={selectComponent}
        setVisible={setVisible}
        onReFresh={fetchComponentData}
      />
    </>
  );
};

export default GlobalVarContainer;