import React, { useState, useEffect } from 'react'
import { View, Text, ScrollView } from '@tarojs/components'
import Taro, { useRouter } from '@tarojs/taro'
import { Button } from '@nutui/nutui-react-taro'
import { getShopBooking, rescheduleShopBooking } from '@/api/shop/shopBooking'
import type { ShopBooking } from '@/api/shop/shopBooking/model'
import dayjs from 'dayjs'

definePageConfig({
  navigationBarTitleText: '改签预约',
})

const BookingReschedulePage: React.FC = () => {
  const router = useRouter()
  const bookingId = router.params.id

  const [originalBooking, setOriginalBooking] = useState<ShopBooking | null>(null)
  const [loading, setLoading] = useState(true)
  const [submitting, setSubmitting] = useState(false)

  const [newDate, setNewDate] = useState('')
  const [newTime, setNewTime] = useState('')

  const getDateRange = () => {
    const dates: { value: string; label: string }[] = []
    const today = dayjs()
    for (let i = 1; i <= 14; i++) {
      const d = today.add(i, 'day')
      const weekDays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
      dates.push({
        value: d.format('YYYY-MM-DD'),
        label: `${d.month() + 1}月${d.date()}日 ${weekDays[d.day()]}`,
      })
    }
    return dates
  }
  const dateRange = getDateRange()

  const timeSlots = [
    { label: '09:00-10:00', value: '09:00-10:00' },
    { label: '10:00-11:00', value: '10:00-11:00' },
    { label: '11:00-12:00', value: '11:00-12:00' },
    { label: '14:00-15:00', value: '14:00-15:00' },
    { label: '15:00-16:00', value: '15:00-16:00' },
    { label: '16:00-17:00', value: '16:00-17:00' },
    { label: '17:00-18:00', value: '17:00-18:00' },
  ]

  useEffect(() => {
    if (!bookingId) {
      Taro.showToast({ title: '参数错误', icon: 'none' })
      setLoading(false)
      return
    }
    fetchBookingDetail()
  }, [bookingId])

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

  const handleSubmit = () => {
    if (!newDate) {
      Taro.showToast({ title: '请选择新日期', icon: 'none' })
      return
    }
    if (!newTime) {
      Taro.showToast({ title: '请选择新时段', icon: 'none' })
      return
    }

    const oldDate = originalBooking?.bookingDate || '-'
    const oldTime = originalBooking?.bookingTime || '-'
    const confirmContent = `确定将预约从\n${oldDate} ${oldTime}\n改签至\n${newDate} ${newTime}吗？`

    Taro.showModal({
      title: '确认改签',
      content: confirmContent,
      confirmText: '确认改签',
      confirmColor: '#0e932e',
      success: async (res) => {
        if (res.confirm) {
          await submitReschedule()
        }
      }
    })
  }

  const submitReschedule = async () => {
    try {
      setSubmitting(true)
      await rescheduleShopBooking({
        bookingId: bookingId,
        newDate: newDate,
        newTime: newTime,
      })
      Taro.showToast({ title: '改签成功', icon: 'success' })
      setTimeout(() => {
        Taro.navigateBack()
      }, 1500)
    } catch (e: any) {
      console.error('改签失败:', e)
      Taro.showToast({ title: e.message || '改签失败', icon: 'none' })
    } finally {
      setSubmitting(false)
    }
  }

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

  if (!originalBooking) {
    return (
      <View className='min-h-screen bg-gray-50 flex items-center justify-center'>
        <Text className='text-gray-400'>预约信息不存在</Text>
      </View>
    )
  }

  return (
    <View className='min-h-screen bg-gray-50 flex flex-col'>
      <ScrollView scrollY className='flex-1'>
        <View className='bg-white mx-3 mt-3 rounded-xl p-4'>
          <Text className='text-base font-medium text-gray-800 mb-3 block'>原预约信息</Text>

          <View className='bg-gray-50 rounded-lg p-3'>
            <View className='flex justify-between items-center mb-2'>
              <Text className='text-sm text-gray-500'>预约编号</Text>
              <Text className='text-sm text-gray-800'>{originalBooking.id}</Text>
            </View>
            <View className='flex justify-between items-center mb-2'>
              <Text className='text-sm text-gray-500'>服务类型</Text>
              <Text className='text-sm text-gray-800'>{originalBooking.serviceName}</Text>
            </View>
            <View className='flex justify-between items-center mb-2'>
              <Text className='text-sm text-gray-500'>预约日期</Text>
              <Text className='text-sm text-gray-800'>{originalBooking.bookingDate}</Text>
            </View>
            <View className='flex justify-between items-center'>
              <Text className='text-sm text-gray-500'>预约时段</Text>
              <Text className='text-sm text-gray-800'>{originalBooking.bookingTime}</Text>
            </View>
          </View>
        </View>

        <View className='bg-white mx-3 mt-3 rounded-xl p-4'>
          <Text className='text-base font-medium text-gray-800 mb-3 block'>选择新日期</Text>

          <ScrollView scrollX className='whitespace-nowrap'>
            <View className='flex gap-2'>
              {dateRange.map(date => (
                <View
                  key={date.value}
                  className={`inline-block px-3 py-2 rounded-lg text-center min-w-20 ${
                    newDate === date.value
                      ? 'bg-green-500 text-white'
                      : 'bg-gray-50 text-gray-600'
                  }`}
                  onClick={() => setNewDate(date.value)}
                >
                  <Text className='text-xs block'>{date.label}</Text>
                </View>
              ))}
            </View>
          </ScrollView>
        </View>

        <View className='bg-white mx-3 mt-3 rounded-xl p-4'>
          <Text className='text-base font-medium text-gray-800 mb-3 block'>选择新时段</Text>

          <View className='flex flex-wrap gap-2'>
            {timeSlots.map(slot => (
              <View
                key={slot.value}
                className={`px-4 py-2 rounded-lg text-center ${
                  newTime === slot.value
                    ? 'bg-green-500 text-white'
                    : 'bg-gray-50 text-gray-600'
                }`}
                onClick={() => setNewTime(slot.value)}
              >
                <Text className='text-sm'>{slot.label}</Text>
              </View>
            ))}
          </View>
        </View>

        <View className='bg-white mx-3 mt-3 rounded-xl p-4 mb-4'>
          <Text className='text-base font-medium text-gray-800 mb-3 block'>改签说明</Text>
          <View className='text-xs text-gray-500 leading-6 space-y-1'>
            <Text className='block'>1. 每个订单只能改签一次，请谨慎选择</Text>
            <Text className='block'>2. 改签需提前2小时申请</Text>
            <Text className='block'>3. 改签不收取任何手续费</Text>
            <Text className='block'>4. 如有疑问，请联系客服咨询</Text>
          </View>
        </View>
      </ScrollView>

      <View className='bg-white p-3 border-t border-gray-100' style={{ paddingBottom: '20px' }}>
        <Button
          type='primary'
          block
          loading={submitting}
          disabled={submitting || !newDate || !newTime}
          className='rounded-full'
          style={{ backgroundColor: '#0e932e', border: 'none' }}
          onClick={handleSubmit}
        >
          {submitting ? '提交中...' : '确认改签'}
        </Button>
      </View>
    </View>
  )
}

export default BookingReschedulePage
