import React, { useState, useEffect } from 'react'
import Taro, { useRouter } from '@tarojs/taro'
import { View, Text } from '@tarojs/components'
import { Loading, Empty, Button } from '@nutui/nutui-react-taro'
import './index.scss'

// 物流信息接口
interface LogisticsInfo {
  expressCompany: string // 快递公司
  expressNo: string // 快递单号
  status: string // 物流状态
  updateTime: string // 更新时间
  estimatedTime?: string // 预计送达时间
  currentLocation?: string // 当前位置
}

// 物流跟踪记录
interface LogisticsTrack {
  time: string
  location: string
  status: string
  description: string
}

// 支持的快递公司
const EXPRESS_COMPANIES = {
  'SF': '顺丰速运',
  'YTO': '圆通速递',
  'ZTO': '中通快递',
  'STO': '申通快递',
  'YD': '韵达速递',
  'HTKY': '百世快递',
  'JD': '京东物流',
  'EMS': '中国邮政'
}

const LogisticsPage: React.FC = () => {
  const router = useRouter()
  const { orderId, expressNo, expressCompany } = router.params

  const [loading, setLoading] = useState(true)
  const [logisticsInfo, setLogisticsInfo] = useState<LogisticsInfo | null>(null)
  const [trackList, setTrackList] = useState<LogisticsTrack[]>([])
  const [error, setError] = useState<string>('')

  useEffect(() => {
    if (orderId) {
      loadLogisticsInfo()
    }
  }, [orderId])

  // 加载物流信息
  const loadLogisticsInfo = async () => {
    try {
      setLoading(true)
      setError('')

      // 模拟API调用 - 实际项目中替换为真实API
      const mockLogisticsInfo: LogisticsInfo = {
        expressCompany: expressCompany || 'SF',
        expressNo: expressNo || 'SF1234567890',
        status: '运输中',
        updateTime: new Date().toISOString(),
        estimatedTime: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString(),
        currentLocation: '北京市朝阳区'
      }

      const mockTrackList: LogisticsTrack[] = [
        {
          time: new Date().toISOString(),
          location: '北京市朝阳区',
          status: '运输中',
          description: '快件正在运输途中，请耐心等待'
        },
        {
          time: new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString(),
          location: '北京转运中心',
          status: '已发出',
          description: '快件已从北京转运中心发出'
        },
        {
          time: new Date(Date.now() - 6 * 60 * 60 * 1000).toISOString(),
          location: '北京转运中心',
          status: '已到达',
          description: '快件已到达北京转运中心'
        },
        {
          time: new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString(),
          location: '上海市浦东新区',
          status: '已发货',
          description: '商家已发货，快件已交给快递公司'
        }
      ]

      // 模拟网络延迟
      await new Promise(resolve => setTimeout(resolve, 1000))

      setLogisticsInfo(mockLogisticsInfo)
      setTrackList(mockTrackList)

    } catch (error) {
      console.error('加载物流信息失败:', error)
      setError('加载物流信息失败，请重试')
    } finally {
      setLoading(false)
    }
  }

  // 刷新物流信息
  const refreshLogistics = () => {
    loadLogisticsInfo()
  }

  // 联系客服
  const contactService = () => {
    Taro.showModal({
      title: '联系客服',
      content: '客服电话：400-123-4567\n工作时间：9:00-18:00',
      showCancel: false
    })
  }

  // 格式化时间
  const formatTime = (timeStr: string) => {
    const date = new Date(timeStr)
    return `${date.getMonth() + 1}-${date.getDate()} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
  }

  if (loading) {
    return (
      <View className="logistics-page">
        <View className="loading-container">
          <Loading type="spinner" />
          <Text className="loading-text">正在查询物流信息...</Text>
        </View>
      </View>
    )
  }

  if (error) {
    return (
      <View className="logistics-page">
        <Empty
          description={error}
          imageSize={80}
        >
          <Button type="primary" size="small" onClick={refreshLogistics}>
            重新加载
          </Button>
        </Empty>
      </View>
    )
  }

  if (!logisticsInfo) {
    return (
      <View className="logistics-page">
        <Empty
          description="暂无物流信息"
          imageSize={80}
        >
          <Button type="primary" size="small" onClick={() => Taro.navigateBack()}>
            返回
          </Button>
        </Empty>
      </View>
    )
  }

  return (
    <View className="logistics-page">
      {/* 物流基本信息 */}
      <View className="logistics-header">
        <View className="express-info">
          <Text className="company-name">
            {EXPRESS_COMPANIES[logisticsInfo.expressCompany as keyof typeof EXPRESS_COMPANIES] || logisticsInfo.expressCompany}
          </Text>
          <Text className="express-no">{logisticsInfo.expressNo}</Text>
        </View>
        <View className="status-info">
          <Text className="status">{logisticsInfo.status}</Text>
          {logisticsInfo.currentLocation && (
            <Text className="location">当前位置：{logisticsInfo.currentLocation}</Text>
          )}
          {logisticsInfo.estimatedTime && (
            <Text className="estimated-time">
              预计送达：{formatTime(logisticsInfo.estimatedTime)}
            </Text>
          )}
        </View>
      </View>

      {/* 物流跟踪 */}
      <View className="logistics-track">
        <View className="track-header">
          <Text className="track-title">物流跟踪</Text>
          <Button size="small" fill="outline" onClick={refreshLogistics}>
            刷新
          </Button>
        </View>

        <View className="track-list">
          {trackList.map((track, index) => (
            <View key={index} className={`track-item ${index === 0 ? 'current' : ''}`}>
              <View className="track-dot" />
              <View className="track-content">
                <View className="track-info">
                  <Text className="track-status">{track.status}</Text>
                  <Text className="track-time">{formatTime(track.time)}</Text>
                </View>
                <Text className="track-location">{track.location}</Text>
                <Text className="track-description">{track.description}</Text>
              </View>
            </View>
          ))}
        </View>
      </View>

      {/* 底部操作 */}
      <View className="logistics-footer">
        <Button block onClick={contactService}>
          联系客服
        </Button>
      </View>
    </View>
  )
}

export default LogisticsPage
