import { useEffect, useState } from 'react'
import Taro, { useDidShow } from '@tarojs/taro'
import { View, Text } from '@tarojs/components'
import { Cell, CellGroup, InfiniteLoading, PullToRefresh, Empty, Loading } from '@nutui/nutui-react-taro'
import dayjs from 'dayjs'

import { pageGltTicketOrder } from '@/api/glt/gltTicketOrder'
import type { GltTicketOrder } from '@/api/glt/gltTicketOrder/model'

const PAGE_SIZE = 10

export default function TicketOrdersPage() {
  const [list, setList] = useState<GltTicketOrder[]>([])
  const [loading, setLoading] = useState(false)
  const [hasMore, setHasMore] = useState(true)
  const [page, setPage] = useState(1)

  const userId = (() => {
    const raw = Taro.getStorageSync('UserId')
    const id = Number(raw)
    return Number.isFinite(id) && id > 0 ? id : undefined
  })()

  const reload = async (isRefresh = true) => {
    if (loading) return
    if (!userId) {
      setList([])
      setHasMore(false)
      return
    }

    setLoading(true)
    try {
      const currentPage = isRefresh ? 1 : page
      const res = await pageGltTicketOrder({
        page: currentPage,
        limit: PAGE_SIZE,
        userId
      } as any)

      const resList = res?.list || []
      const next = isRefresh ? resList : [...list, ...resList]
      setList(next)

      const total = typeof res?.count === 'number' ? res.count : next.length
      setHasMore(next.length < total)
      setPage(currentPage + 1)
    } catch (e) {
      console.error('获取送水订单失败:', e)
      Taro.showToast({ title: '获取送水订单失败', icon: 'none' })
      setHasMore(false)
    } finally {
      setLoading(false)
    }
  }

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

  useDidShow(() => {
    setPage(1)
    setHasMore(true)
    reload(true)
    // eslint-disable-next-line react-hooks/exhaustive-deps
  })

  return (
    <View className="bg-gray-50 min-h-screen">

      <View className="px-3">
        <PullToRefresh onRefresh={() => reload(true)}>
          {list.length === 0 && !loading ? (
            <View className="bg-white rounded-lg p-6">
              <Empty description="暂无送水订单" />
            </View>
          ) : (
            <CellGroup>
              {list.map((o) => {
                const qty = Number(o.totalNum || 0)
                const timeText = o.createTime ? dayjs(o.createTime).format('YYYY-MM-DD HH:mm') : ''
                const addr = o.address || (o.addressId ? `地址ID：${o.addressId}` : '')
                const remark = o.buyerRemarks || ''
                return (
                  <Cell
                    key={o.id}
                    title={
                      <View className="flex flex-col">
                        <Text className="text-sm text-gray-900">送水 {qty || '-'} 桶</Text>
                        {addr ? <Text className="text-xs text-gray-500">{addr}</Text> : null}
                        {remark ? <Text className="text-xs text-gray-500">备注：{remark}</Text> : null}
                      </View>
                    }
                    extra={<Text className="text-xs text-gray-500">{timeText}</Text>}
                  />
                )
              })}
            </CellGroup>
          )}

          <InfiniteLoading
            hasMore={hasMore}
            onLoadMore={() => reload(false)}
            loadingText={
              <View className="flex justify-center items-center py-4">
                <Loading />
                <View className="ml-2">加载中...</View>
              </View>
            }
            loadMoreText={
              <View className="text-center py-4 text-gray-500">
                {list.length === 0 ? '暂无数据' : '没有更多了'}
              </View>
            }
          />
        </PullToRefresh>
      </View>
    </View>
  )
}
