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 { getMyComponentList, remove } from '@/api/componentBase';
import { ComponentItem } from '@/api/interface';
import AddComponentModal from '@/pages/componentDevelopment/componentList/addComponentModal';
import HandleButtonGroup from '@/pages/componentDevelopment/componentList/handleButtonGroup';
import {
  componentStatusConstant,
  componentStatusDict,
  publicStatus,
  publicStatusDict, publishStatusConstant, publishStatusDict
} from '@/const/isdp/componentBase';
import dayjs from 'dayjs';

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={(action, identifier, version) => {
            // TODO: 实现公开/取消公开组件逻辑
            console.log('Publish or revoke component', action, identifier, version);
          }}
          onNavTo={(id, type) => {
            // TODO: 实现导航逻辑
            console.log('Nav to', id, type);
          }}
          onSourceCodeView={(row) => {
            // TODO: 实现查看源码逻辑
            console.log('Source code view', row);
          }}
          onShowEdit={(row, index) => {
            // TODO: 实现编辑组件逻辑
            console.log('Show edit', 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);
          }}
          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 === '我的组件') {
      fetchComponentData();
    }
  }, [selectedItem, pagination.currPage, pagination.pageSize]);

  const fetchComponentData = async () => {
    setLoading(true);
    try {
      const res: any = await getMyComponentList({
        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 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>
              <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;