import {useState} from "react";
import Taro, {useDidShow} from '@tarojs/taro'
import {Button, Cell, CellGroup, Space, Empty, ConfigProvider, Tag} from '@nutui/nutui-react-taro'
import {ArrowRight} from '@nutui/icons-react-taro'
import {AppVersion} from "@/api/app/appVersion/model";
import {listAppVersion} from "@/api/app/appVersion";

const STATUS_MAP: Record<string, { label: string; color: string }> = {
  pending: { label: '待发布', color: 'warning' },
  published: { label: '已发布', color: 'success' },
  offline: { label: '已下架', color: 'default' }
};

const AppVersionList = () => {
  const [list, setList] = useState<AppVersion[]>([])

  const reload = () => {
    listAppVersion({})
      .then(data => {
        setList(data || [])
      })
      .catch(() => {
        Taro.showToast({
          title: '获取数据失败',
          icon: 'error'
        });
      })
  }

  useDidShow(() => {
    reload()
  });

  if (list.length == 0) {
    return (
      <ConfigProvider>
        <div className={'h-full flex flex-col justify-center items-center'} style={{
          height: 'calc(100vh - 300px)',
        }}>
          <Empty
            style={{
              backgroundColor: 'transparent'
            }}
            description="暂无版本"
          />
          <Space>
            <Button onClick={() => Taro.navigateTo({url: '/app/appVersion/add'})}>新增版本</Button>
          </Space>
        </div>
      </ConfigProvider>
    )
  }

  return (
    <ConfigProvider>
      <CellGroup>
        {list.map((item) => (
          <Cell
            key={item.id}
            title={`${item.versionName || '未命名版本'} (${item.versionCode || 'v0.0.0'})`}
            description={item.description}
            align="center"
            rightIcon={<ArrowRight />}
            onClick={() => Taro.navigateTo({url: `/app/appVersion/add?id=${item.id}`})}
          >
            <Tag type={STATUS_MAP[item.status || 'pending']?.color as any}>
              {STATUS_MAP[item.status || 'pending']?.label}
            </Tag>
          </Cell>
        ))}
      </CellGroup>
      <Space direction="vertical" style={{padding: '16px'}}>
        <Button onClick={() => Taro.navigateTo({url: '/app/appVersion/add'})}>
          新增版本
        </Button>
      </Space>
    </ConfigProvider>
  );
};

export default AppVersionList;
