import {useEffect, useState} from "react";
import Taro from '@tarojs/taro'
import {Button, Cell, Space, Empty, ConfigProvider, InfiniteLoading} from '@nutui/nutui-react-taro'
import {View, ScrollView} from '@tarojs/components'
import {pageUserBalanceLog} from "@/api/user/balance-log";
import {UserBalanceLog} from "@/api/user/balance-log/model";
import {formatCurrency} from "@/utils/common";

const Wallet = () => {
  const [list, setList] = useState<UserBalanceLog[]>([])
  const [loading, setLoading] = useState(false)
  const [loadingMore, setLoadingMore] = useState(false)
  const [refreshing, setRefreshing] = useState(false)
  const [hasMore, setHasMore] = useState(true)
  const [currentPage, setCurrentPage] = useState(1)
  const [total, setTotal] = useState(0)
  const pageSize = 20

  const reload = () => {
    setLoading(true)
    const userId = Taro.getStorageSync('UserId')

    console.log('Loading balance log for userId:', userId)

    if (!userId) {
      console.warn('No userId found in storage')
      Taro.showToast({
        title: '请先登录',
        icon: 'error'
      });
      setLoading(false)
      return
    }

    pageUserBalanceLog({
      userId: parseInt(userId),
      page: 1,
      limit: 20
    })
      .then((res: any) => {
        console.log('Balance log response:', res)
        setList(res?.list || [])
      })
      .catch((error: any) => {
        console.error('Balance log error:', error)
        Taro.showToast({
          title: error?.message || '获取失败',
          icon: 'error'
        });
      })
      .finally(() => {
        setLoading(false)
      })
  }

  useEffect(() => {
    reload()
  }, []);

  if (loading) {
    return (
      <ConfigProvider>
        <div className={'h-full flex flex-col justify-center items-center'} style={{
          height: 'calc(100vh - 300px)',
        }}>
          <div>加载中...</div>
        </div>
      </ConfigProvider>
    )
  }

  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={() => reload()}>刷新</Button>
          </Space>
        </div>
      </ConfigProvider>
    )
  }

  return (
    <ConfigProvider>
      <View className="p-4">
        {list.map((item, index) => (
          <Cell.Group key={index} className="mb-4">
            <Cell className="flex flex-col gap-2 p-4">
              <View className="flex justify-between items-start w-full">
                <View className="flex-1">
                  <View className="font-medium text-base text-gray-800 mb-1">
                    {item.scene === 10 ? '会员充值' : item.scene === 20 ? '用户消费' : item.scene === 30 ? '管理员操作' : '订单退款'}
                  </View>
                  <View className="text-sm text-gray-500">
                    {item.comments}
                  </View>
                </View>
                <View className={`text-lg font-bold ${
                  item.scene === 10 ? 'text-green-500' : ''
                }`}>
                  {item.scene === 10 ? '+' : '-'}
                  {formatCurrency(Number(item.money), 'CNY') || '0.00'}
                </View>
              </View>

              <View className="flex justify-between w-full items-center text-xs text-gray-400 mt-2">
                <View>
                  {item.createTime}
                </View>
              </View>

              {item.remark && (
                <View className="text-xs text-gray-500 mt-1 p-2 bg-gray-50 rounded">
                  备注: {item.remark}
                </View>
              )}
            </Cell>
          </Cell.Group>
        ))}
      </View>
    </ConfigProvider>
  );
};

export default Wallet;
