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

definePageConfig({
  navigationBarTitleText: '预约详情',
})

const BookingDetailPage: React.FC = () => {
  const router = useRouter()
  const [order, setOrder] = useState<ShopBooking | null>(null)
  const [loading, setLoading] = useState(true)
  const [cancelling, setCancelling] = useState(false)

  // 获取预约详情
  const loadBookingDetail = async () => {
    const id = router.params.id
    if (!id) {
      Taro.showToast({ title: '参数错误', icon: 'none' })
      setLoading(false)
      return
    }

    try {
      const data = await getShopBooking(id)
      setOrder(data)
    } catch (e: any) {
      console.error('获取预约详情失败:', e)
      Taro.showToast({ title: e.message || '获取详情失败', icon: 'none' })
    } finally {
      setLoading(false)
    }
  }

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

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

  // 取消预约
  const handleCancel = () => {
    if (!order?.id) return

    Taro.showModal({
      title: '确认取消',
      content: '确定取消该预约吗？\n\n取消后将无法恢复。',
      confirmColor: '#0e932e',
      success: async (res) => {
        if (res.confirm) {
          try {
            setCancelling(true)
            await cancelShopBooking(order.id)
            Taro.showToast({ title: '已取消', icon: 'success' })
            // 重新加载详情
            setTimeout(() => loadBookingDetail(), 1500)
          } catch (e: any) {
            console.error('取消预约失败:', e)
            Taro.showToast({ title: e.message || '取消失败', icon: 'none' })
          } finally {
            setCancelling(false)
          }
        }
      }
    })
  }

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

  // 返回列表
  const handleBackToList = () => {
    Taro.navigateBack()
  }

  if (loading) {
    return (
      <View className='min-h-screen bg-gray-50 flex items-center justify-center'>
        <Text className='text-gray-400'>加载中...</Text>
      </View>
    )
  }

  if (!order) {
    return (
      <View className='min-h-screen bg-gray-50 flex items-center justify-center'>
        <View className='text-center'>
          <Text className='text-gray-400 block mb-4'>暂无数据</Text>
          <View
            className='inline-block bg-orange-500 text-white px-4 py-2 rounded-full'
            onClick={handleBackToList}
          >
            <Text className='text-sm'>返回列表</Text>
          </View>
        </View>
      </View>
    )
  }

  const statusInfo = getStatusInfo(order.status)

  return (
    <View className='min-h-screen bg-gray-50 flex flex-col'>
      <ScrollView scrollY className='flex-1'>
        {/* 状态卡片 */}
        <View className='p-4 text-white' style={{ background: 'linear-gradient(to right, #0e932e, #2eb872)' }}>
          <View className='flex items-center gap-2'>
            <Text className='text-2xl'>📅</Text>
            <View>
              <Text className='text-xl font-bold block mb-1'>{statusInfo.label}</Text>
              <Text className='text-xs opacity-80 block'>预约编号：{order.bookingNo}</Text>
            </View>
          </View>
        </View>

        {/* 预约信息 */}
        <View className='bg-white mx-3 mt-3 rounded-xl p-4 shadow-sm'>
          <Text className='text-base font-medium text-gray-800 mb-3 block'>预约信息</Text>

          <View className='flex justify-between py-2 border-b border-gray-50'>
            <Text className='text-sm text-gray-500'>服务名称</Text>
            <Text className='text-sm text-gray-800'>{order.serviceName || '预约服务'}</Text>
          </View>
          <View className='flex justify-between py-2 border-b border-gray-50'>
            <Text className='text-sm text-gray-500'>预约日期</Text>
            <Text className='text-sm text-gray-800'>{order.bookingDate || '-'}</Text>
          </View>
          <View className='flex justify-between py-2 border-b border-gray-50'>
            <Text className='text-sm text-gray-500'>预约时段</Text>
            <Text className='text-sm text-gray-800'>{order.bookingTime || '-'}</Text>
          </View>
          {order.price > 0 && (
            <View className='flex justify-between py-2 border-b border-gray-50'>
              <Text className='text-sm text-gray-500'>服务费用</Text>
              <Text className='text-sm text-red-500 font-bold'>¥{order.price}</Text>
            </View>
          )}
          <View className='flex justify-between py-2'>
            <Text className='text-sm text-gray-500'>预约备注</Text>
            <Text className='text-sm text-gray-800'>{order.remark || '无'}</Text>
          </View>
        </View>

        {/* 联系人信息 */}
        {(order.contactName || order.contactPhone) && (
          <View className='bg-white mx-3 mt-3 rounded-xl p-4 shadow-sm'>
            <Text className='text-base font-medium text-gray-800 mb-3 block'>联系人</Text>
            {order.contactName && (
              <View className='flex justify-between py-2 border-b border-gray-50'>
                <Text className='text-sm text-gray-500'>姓名</Text>
                <Text className='text-sm text-gray-800'>{order.contactName}</Text>
              </View>
            )}
            {order.contactPhone && (
              <View className='flex justify-between py-2'>
                <Text className='text-sm text-gray-500'>电话</Text>
                <Text
                  className='text-sm text-blue-500'
                  onClick={() => Taro.makePhoneCall({ phoneNumber: order.contactPhone })}
                >
                  {order.contactPhone} 📞</Text>
              </View>
            )}
          </View>
        )}

        {/* 门店信息 */}
        <View className='bg-white mx-3 mt-3 rounded-xl p-4 shadow-sm'>
          <Text className='text-base font-medium text-gray-800 mb-3 block'>门店信息</Text>

          <View className='flex items-center gap-2 mb-2'>
            <Text className='text-lg'>🏪</Text>
            <Text className='text-sm font-medium text-gray-800'>{order.storeName || '门店'}</Text>
          </View>
          {order.storePhone && (
            <View className='flex items-center gap-2 mb-2'>
              <Text className='text-sm text-gray-400'>📞</Text>
              <Text
                className='text-sm text-blue-500'
                onClick={() => Taro.makePhoneCall({ phoneNumber: order.storePhone })}
              >
                {order.storePhone}
              </Text>
            </View>
          )}
          {order.address && (
            <View className='flex items-start gap-2 mb-2'>
              <Text className='text-sm text-gray-400'>📍</Text>
              <Text className='text-sm text-gray-600 flex-1'>{order.address}</Text>
            </View>
          )}
        </View>

        {/* 创建时间 */}
        {order.createTime && (
          <View className='mx-3 mt-3 mb-4'>
            <Text className='text-xs text-gray-400'>预约时间：{order.createTime}</Text>
          </View>
        )}

        {/* 操作按钮 - 仅待服务状态显示 */}
        {order.status === 'pending' && (
          <View className='p-3 gap-3 mx-3'>
            <View
              className='text-center py-3 rounded-full border border-red-500 bg-white mb-3'
              onClick={handleCancel}
            >
              <Text className='text-red-500 font-medium'>{cancelling ? '取消中...' : '取消预约'}</Text>
            </View>
            <View
              className='text-center py-3 rounded-full bg-green-500'
              onClick={handleReschedule}
            >
              <Text className='text-white font-medium'>改签预约</Text>
            </View>
          </View>
        )}

        <View className='h-6' />
      </ScrollView>
    </View>
  )
}

export default BookingDetailPage
