import { List, NavBar, SpinLoading, Toast } from 'antd-mobile';

import { UnorderedListOutline, SetOutline, UploadOutline, LoopOutline } from 'antd-mobile-icons';
import { useNavigate } from 'react-router-dom';
import { useAppDispatch, useAppSelector } from '../utils/hooks';
import { syncBaseData } from '../store/features/baseData';

export default function Mine2() {
  const navigate = useNavigate();
  const dispatch = useAppDispatch();
  const baseState = useAppSelector((state) => state.baseData);

  const onSync = async () => {
    const res = await dispatch(syncBaseData()).unwrap();
    if (res.success) {
      Toast.show('同步完成');
    } else {
      Toast.show(res.message);
    }
  };

  return (
    <div>
      <NavBar className="bg-white" back={null}>
        我的
      </NavBar>
      <div className="home-page-content overflow-x-hidden overflow-y-auto pt-3">
        <List>
          <List.Item prefix={<UnorderedListOutline />} onClick={() => navigate('/measure/records')}>
            测量记录
          </List.Item>
          <List.Item prefix={<UploadOutline />} onClick={() => navigate('/measure/upload')}>
            上传记录
          </List.Item>
          <List.Item prefix={<SetOutline />} onClick={() => navigate('/profile/setting')}>
            设置
          </List.Item>
          <List.Item prefix={<LoopOutline />} onClick={onSync}>
            <div className="flex justify-between">
              <span>同步基础数据</span>
              {baseState.syncBaseProgress.finish ? (
                <div>
                  {baseState.syncBaseProgress.error ? (
                    <span className="text-xs text-[red]">{baseState.syncBaseProgress.msg}</span>
                  ) : (
                    <span className="text-xs text-[green]">
                      {baseState.syncBaseProgress.progress >= 90 ? '同步完成' : ''}
                    </span>
                  )}
                </div>
              ) : (
                <div className="flex items-center gap-2">
                  <span className="text-xs">{`${baseState.syncBaseProgress.progress}%`}</span>
                  <SpinLoading style={{ '--size': '16px' }} />
                </div>
              )}
            </div>
          </List.Item>
        </List>
      </div>
    </div>
  );
}
