import React, { useState, useEffect } from 'react'
import { View, Text, ScrollView } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { pageShopBooking, cancelShopBooking } from '@/api/shop/shopBooking'
import type { ShopBooking, BookingStatus } from '@/api/shop/shopBooking/model'

definePageConfig({
  navigationBarTitleText: '预约订单',
})

const BookingListPage: React.FC = () => {
  const [activeTab, setActiveTab] = useState(0)
  const [orders, setOrders] = useState<ShopBooking[]>([])
  const [loading, setLoading] = useState(false)
  const [finished, setFinished] = useState(false)
  const [page, setPage] = useState(1)

  useEffect(() => {
    setOrders([])
    setPage(1)
    setFinished(false)
    loadList(1)
  }, [activeTab])

  const loadList = async (p: number) => {
    if (loading) return
    setLoading(true)

    try {
      // 根据 tab 筛选状态
      let status: BookingStatus | undefined
      if (activeTab === 1) status = 'pending'
      else if (activeTab === 2) status = 'in_progress'
      else if (activeTab === 3) status = 'completed'

      const res = await pageShopBooking({
        page: p,
        limit: 10,
        status,
      })

      if (res?.list) {
        const newList = res.list
        const total = res.count || 0
        if (p === 1) {
          setOrders(newList)
        } else {
          setOrders(prev => [...prev, ...newList])
        }
        // 判断是否已加载完所有数据
        setFinished(newList.length === 0 || orders.length + newList.length >= total)
        setPage(p)
      }
    } catch (err) {
      console.error('加载预约订单失败', err)
      Taro.showToast({ title: '加载失败', icon: 'none' })
    } finally {
      setLoading(false)
    }
  }

  // 加载更多
  const handleLoadMore = () => {
    if (!finished && !loading) {
      loadList(page + 1)
    }
  }

  // 获取状态标签
  const getStatusLabel = (status: BookingStatus) => {
    const map: Record<BookingStatus, { label: string; color: string }> = {
      'pending': { label: '待服务', color: 'text-orange-500' },
      'confirmed': { label: '已确认', color: 'text-blue-500' },
      'in_progress': { label: '进行中', color: 'text-blue-500' },
      'completed': { label: '已完成', color: 'text-green-500' },
      'cancelled': { label: '已取消', color: 'text-gray-400' },
      'rescheduled': { label: '已改签', color: 'text-purple-500' },
    }
    return map[status] || { label: '未知', color: 'text-gray-400' }
  }

  // 取消预约
  const handleCancel = async (id: string) => {
    Taro.showModal({
      title: '确认取消',
      content: '确定取消该预约吗？\n\n取消后款项将退回您的余额。',
      confirmColor: '#0e932e',
      success: async (res) => {
        if (res.confirm) {
          try {
            await cancelShopBooking(id)
            Taro.showToast({ title: '已取消，款项已退回余额', icon: 'success' })
            // 重新加载列表
            setOrders([])
            setPage(1)
            setFinished(false)
            loadList(1)
          } catch (err: any) {
            console.error('取消预约失败', err)
            Taro.showToast({ title: err?.message || '取消失败', icon: 'none' })
          }
        }
      }
    })
  }

  // 改签预约
  const handleReschedule = (id: string) => {
    Taro.navigateTo({ url: `/pages/booking/reschedule/index?id=${id}` })
  }

  // 查看详情
  const handleDetail = (id: string) => {
    Taro.navigateTo({ url: `/pages/booking/detail/index?id=${id}` })
  }

  return (
    <View className='h-screen bg-gray-50 flex flex-col'>
      {/* Tab 栏 */}
      <View className='bg-white flex'>
        {['全部', '待服务', '进行中', '已完成'].map((tab, index) => (
          <View
            key={index}
            className={`flex-1 text-center py-3 relative ${
              activeTab === index ? 'text-orange-500 font-medium' : 'text-gray-600'
            }`}
            onClick={() => setActiveTab(index)}
          >
            <Text className='text-sm'>{tab}</Text>
            {activeTab === index && (
              <View className='absolute bottom-0 left-0 right-0 flex justify-center'>
                <View className='w-8 h-px bg-orange-500 rounded' />
              </View>
            )}
          </View>
        ))}
      </View>

      {/* 订单列表 */}
      <ScrollView scrollY className='flex-1'>
        {orders.length === 0 ? (
          <View className='text-center py-16'>
            <Text className='text-4xl mb-3 block'>📅</Text>
            <Text className='text-sm text-gray-400 mb-3 block'>暂无预约订单</Text>
            <View
              className='inline-block bg-orange-500 text-white px-4 py-2 rounded-full'
              onClick={() => Taro.navigateTo({ url: '/pages/store/list/index' })}
            >
              <Text className='text-sm'>去预约</Text>
            </View>
          </View>
        ) : (
          <View className='p-3'>
            {orders.map(order => {
              const statusInfo = getStatusLabel(order.status)
              return (
                <View key={order.id} className='bg-white rounded-xl p-4 mb-3 shadow-sm'>
                  {/* 顶部状态 */}
                  <View className='flex justify-between items-center mb-3'>
                    <Text className='text-xs text-gray-500'>{order.bookingNo}</Text>
                    <Text className={`text-sm font-medium ${statusInfo.color}`}>
                      {statusInfo.label}
                    </Text>
                  </View>

                  {/* 预约信息 */}
                  <View className='flex items-center gap-2 mb-3'>
                    <View className='w-10 h-10 bg-blue-50 rounded-lg flex items-center justify-center flex-shrink-0'>
                      <Text className='text-xl'>🏪</Text>
                    </View>
                    <View className='flex-1'>
                      <Text className='text-sm text-gray-800 font-medium block'>{order.storeName}</Text>
                      <Text className='text-xs text-gray-500 mt-0 block'>{order.serviceName}</Text>
                    </View>
                  </View>

                  {/* 预约时间 */}
                  <View className='bg-gray-50 rounded-lg p-3 mb-3'>
                    <View className='flex justify-between items-center mb-2'>
                      <Text className='text-xs text-gray-500'>预约日期</Text>
                      <Text className='text-sm text-gray-800'>{order.bookingDate}</Text>
                    </View>
                    <View className='flex justify-between items-center'>
                      <Text className='text-xs text-gray-500'>预约时段</Text>
                      <Text className='text-sm text-gray-800'>{order.bookingTime}</Text>
                    </View>
                  </View>

                  {/* 操作按钮 */}
                  {order.status === 'pending' && (
                    <View className='flex gap-2 pt-2 border-t border-gray-50'>
                      <View
                        className='flex-1 text-center py-2 rounded-full border border-red-500'
                        onClick={() => handleCancel(order.id)}
                      >
                        <Text className='text-xs text-red-500'>取消预约</Text>
                      </View>
                      <View
                        className='flex-1 text-center py-2 rounded-full bg-orange-500'
                        onClick={() => handleDetail(order.id)}
                      >
                        <Text className='text-xs text-white'>查看详情</Text>
                      </View>
                    </View>
                  )}
                  {order.status !== 'pending' && (
                    <View className='flex justify-end pt-2 border-t border-gray-50'>
                      <View
                        className='text-center py-2 px-4 rounded-full bg-orange-500'
                        onClick={() => handleDetail(order.id)}
                      >
                        <Text className='text-xs text-white'>查看详情</Text>
                      </View>
                    </View>
                  )}
                </View>
              )
            })}
          </View>
        )}
      </ScrollView>
    </View>
  )
}

export default BookingListPage
