import React, { useEffect, useState, useCallback } from 'react'
import { View, Text, ScrollView } from '@tarojs/components'
import NavBar from '@/components/NavBar'
import { pageShopOrder } from '@/api/shop/shopOrder'
import type { ShopOrder } from '@/api/shop/shopOrder/model'

definePageConfig({
  navigationBarTitleText: '销售统计',
})

type TimeRange = 'week' | 'month'

interface DayStat {
  date: string
  amount: number
  orders: number
}

const SalesStatisticsPage: React.FC = () => {
  const [timeRange, setTimeRange] = useState<TimeRange>('week')
  const [loading, setLoading] = useState(true)
  const [dayStats, setDayStats] = useState<DayStat[]>([])
  const [totalRevenue, setTotalRevenue] = useState(0)
  const [totalOrders, setTotalOrders] = useState(0)
  const [avgPrice, setAvgPrice] = useState(0)

  const formatDateKey = (date: Date) => {
    const m = String(date.getMonth() + 1).padStart(2, '0')
    const d = String(date.getDate()).padStart(2, '0')
    return `${m}-${d}`
  }

  const formatDateFull = (date: Date) => {
    const y = date.getFullYear()
    const m = String(date.getMonth() + 1).padStart(2, '0')
    const d = String(date.getDate()).padStart(2, '0')
    return `${y}-${m}-${d}`
  }

  const loadData = useCallback(async (range: TimeRange) => {
    setLoading(true)
    try {
      const now = new Date()
      const days = range === 'week' ? 7 : 30
      const startDate = new Date(now.getTime() - (days - 1) * 24 * 60 * 60 * 1000)
      const startStr = `${formatDateFull(startDate)} 00:00:00`
      const endStr = `${formatDateFull(now)} 23:59:59`

      const res = await pageShopOrder({
        page: 1,
        limit: 500,
        startTime: startStr,
        endTime: endStr,
      } as any).catch(() => null)

      if (!res?.list) {
        setDayStats([])
        setTotalRevenue(0)
        setTotalOrders(0)
        setAvgPrice(0)
        return
      }

      const orders: ShopOrder[] = res.list

      // 按天分组
      const dayMap: Record<string, { amount: number; orders: number }> = {}
      for (let i = 0; i < days; i++) {
        const d = new Date(startDate.getTime() + i * 24 * 60 * 60 * 1000)
        dayMap[formatDateKey(d)] = { amount: 0, orders: 0 }
      }

      let totalRev = 0
      let paidCount = 0
      orders.forEach(o => {
        if (!o.createTime) return
        const key = o.createTime.substring(5, 10) // MM-DD
        if (dayMap[key]) {
          const amt = parseFloat(o.payPrice || '0')
          if (o.payStatus) {
            dayMap[key].amount += amt
            totalRev += amt
            paidCount++
          }
          dayMap[key].orders += 1
        }
      })

      const stats: DayStat[] = Object.entries(dayMap).map(([date, d]) => ({
        date,
        amount: d.amount,
        orders: d.orders,
      }))

      setDayStats(stats)
      setTotalRevenue(totalRev)
      setTotalOrders(orders.length)
      setAvgPrice(paidCount > 0 ? totalRev / paidCount : 0)
    } catch (e) {
      console.error('加载销售数据失败', e)
    } finally {
      setLoading(false)
    }
  }, [])

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

  const maxAmount = Math.max(...dayStats.map(d => d.amount), 1)

  return (
    <View className="min-h-screen bg-gray-100">
      <NavBar title="销售统计" />

      {/* 时间范围选择 */}
      <View className="bg-white flex">
        {([{ key: 'week', label: '近7天' }, { key: 'month', label: '近30天' }] as const).map(option => (
          <View
            key={option.key}
            className="flex-1 py-3 text-center relative"
            style={{ color: timeRange === option.key ? '#ef4444' : '#6b7280' }}
            onClick={() => setTimeRange(option.key)}
          >
            <Text className={timeRange === option.key ? 'font-medium' : ''}>{option.label}</Text>
            {timeRange === option.key && (
              <View className="absolute bottom-0 left-0 right-0 flex justify-center">
                <View className="h-1 rounded-t" style={{ width: '32px', backgroundColor: '#ef4444' }} />
              </View>
            )}
          </View>
        ))}
      </View>

      <ScrollView scrollY>
        {loading ? (
          <View className="p-8 text-center">
            <Text className="text-gray-400 text-sm">加载中...</Text>
          </View>
        ) : (
          <View className="p-4">
            {/* 汇总数据 */}
            <View className="bg-white rounded-lg p-4 mb-4">
              <View className="flex justify-around mb-4">
                <View className="text-center">
                  <Text className="text-2xl font-bold text-red-500 block">¥{totalRevenue.toFixed(2)}</Text>
                  <Text className="text-xs text-gray-500">总销售额</Text>
                </View>
                <View className="text-center">
                  <Text className="text-2xl font-bold text-blue-500 block">{totalOrders}</Text>
                  <Text className="text-xs text-gray-500">总订单数</Text>
                </View>
              </View>
              <View className="flex justify-around border-t border-gray-50 pt-4">
                <View className="text-center">
                  <Text className="text-2xl font-bold text-green-500 block">¥{avgPrice.toFixed(2)}</Text>
                  <Text className="text-xs text-gray-500">客单价</Text>
                </View>
                <View className="text-center">
                  <Text className="text-2xl font-bold text-orange-500 block">
                    {totalOrders > 0 ? ((dayStats.filter(d => d.amount > 0).length / dayStats.length) * 100).toFixed(1) : '0.0'}%
                  </Text>
                  <Text className="text-xs text-gray-500">有销售天占比</Text>
                </View>
              </View>
            </View>

            {/* 销售趋势柱状图 */}
            <View className="bg-white rounded-lg p-4 mb-4">
              <Text className="text-base font-medium mb-4 block">销售趋势</Text>
              {dayStats.every(d => d.amount === 0) ? (
                <View className="py-8 text-center">
                  <Text className="text-gray-400 text-sm">暂无销售数据</Text>
                </View>
              ) : (
                <View>
                  <View className="flex items-end justify-between" style={{ height: '120px', marginBottom: '8px' }}>
                    {dayStats.map((item, index) => (
                      <View key={index} className="flex flex-col items-center flex-1">
                        <View
                          className="rounded-t"
                          style={{
                            width: '80%',
                            height: `${Math.max((item.amount / maxAmount) * 100, item.amount > 0 ? 4 : 0)}%`,
                            backgroundColor: item.amount > 0 ? '#ef4444' : '#e5e7eb',
                            minHeight: item.amount > 0 ? '4px' : '2px',
                          }}
                        />
                      </View>
                    ))}
                  </View>
                  <View className="flex justify-between">
                    {dayStats.map((item, index) => (
                      <Text key={index} className="text-xs text-gray-400 flex-1 text-center">
                        {item.date.substring(3)}
                      </Text>
                    ))}
                  </View>
                </View>
              )}
            </View>

            {/* 每日明细 */}
            <View className="bg-white rounded-lg p-4">
              <Text className="text-base font-medium mb-3 block">每日明细</Text>
              {dayStats.length === 0 ? (
                <Text className="text-gray-400 text-sm text-center block py-4">暂无数据</Text>
              ) : (
                dayStats.slice().reverse().map((item, index) => (
                  <View key={index} className={`flex justify-between items-center py-3 ${index < dayStats.length - 1 ? 'border-b border-gray-50' : ''}`}>
                    <Text className="text-sm text-gray-600">{item.date}</Text>
                    <View className="text-right">
                      <Text className="text-base font-medium block">¥{item.amount.toFixed(2)}</Text>
                      <Text className="text-xs text-gray-400">{item.orders} 单</Text>
                    </View>
                  </View>
                ))
              )}
            </View>
          </View>
        )}
      </ScrollView>
    </View>
  )
}

export default SalesStatisticsPage
