import React, { useEffect, useState, useCallback } from 'react'
import { View, Text, ScrollView } from '@tarojs/components'
import Taro from '@tarojs/taro'
import NavBar from '@/components/NavBar'
import { pageShopOrder } from '@/api/shop/shopOrder'
import Loading from '@/components/common/Loading'

definePageConfig({
  navigationBarTitleText: '数据看板',
})

interface DashboardStats {
  orders: number
  revenue: number
  paidOrders: number
  pendingOrders: number
  canceledOrders: number
}

const StatisticsDashboardPage: React.FC = () => {
  const [loading, setLoading] = useState(true)
  const [todayStats, setTodayStats] = useState<DashboardStats>({ orders: 0, revenue: 0, paidOrders: 0, pendingOrders: 0, canceledOrders: 0 })
  const [weekStats, setWeekStats] = useState<DashboardStats>({ orders: 0, revenue: 0, paidOrders: 0, pendingOrders: 0, canceledOrders: 0 })

  const formatDate = (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 calcStats = (orders: any[]): DashboardStats => {
    const paidOrders = orders.filter(o => o.payStatus === true || o.payStatus === 1)
    const revenue = paidOrders.reduce((sum, o) => sum + parseFloat(o.payPrice || '0'), 0)
    const pendingOrders = orders.filter(o => o.orderStatus === 0 || (!o.payStatus && o.orderStatus !== 2))
    const canceledOrders = orders.filter(o => o.orderStatus === 2)
    return {
      orders: orders.length,
      revenue,
      paidOrders: paidOrders.length,
      pendingOrders: pendingOrders.length,
      canceledOrders: canceledOrders.length,
    }
  }

  const loadData = useCallback(async () => {
    setLoading(true)
    try {
      const now = new Date()
      const todayStr = formatDate(now)
      const weekAgo = new Date(now.getTime() - 6 * 24 * 60 * 60 * 1000)
      const weekAgoStr = formatDate(weekAgo)

      const [todayRes, weekRes] = await Promise.all([
        pageShopOrder({ page: 1, limit: 200, startTime: `${todayStr} 00:00:00`, endTime: `${todayStr} 23:59:59` } as any).catch(() => null),
        pageShopOrder({ page: 1, limit: 500, startTime: `${weekAgoStr} 00:00:00`, endTime: `${todayStr} 23:59:59` } as any).catch(() => null),
      ])

      if (todayRes?.list) {
        setTodayStats(calcStats(todayRes.list))
      }
      if (weekRes?.list) {
        setWeekStats(calcStats(weekRes.list))
      }
    } catch (e) {
      console.error('加载统计数据失败', e)
    } finally {
      setLoading(false)
    }
  }, [])

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

  const goTo = (path: string) => {
    Taro.navigateTo({ url: path })
  }

  const renderStatCard = (label: string, value: string | number, color: string, sub?: string) => (
    <View className="bg-white rounded-lg p-4">
      <Text className="text-sm text-gray-500 mb-2 block">{label}</Text>
      <Text className="text-2xl font-bold block" style={{ color }}>{value}</Text>
      {sub && <Text className="text-xs mt-1 block" style={{ color: '#52c41a' }}>{sub}</Text>}
    </View>
  )

  return (
    <View className="min-h-screen bg-gray-100">
      <NavBar title="数据看板" />
      <ScrollView scrollY>
        {loading ? (
          <Loading />
        ) : (
          <View>
            {/* 今日数据 */}
            <View className="p-4">
              <View className="flex items-center justify-between mb-3">
                <Text className="text-base font-medium">今日数据</Text>
                <Text className="text-xs text-gray-400">实时</Text>
              </View>
              <View className="grid grid-cols-2 gap-3 mb-3">
                {renderStatCard('今日订单', todayStats.orders, '#3b82f6')}
                {renderStatCard('今日销售额', `¥${todayStats.revenue.toFixed(2)}`, '#ef4444')}
                {renderStatCard('已支付', todayStats.paidOrders, '#10b981')}
                {renderStatCard('待支付', todayStats.pendingOrders, '#f59e0b')}
              </View>
              {todayStats.canceledOrders > 0 && (
                <View className="bg-white rounded-lg px-4 py-3 flex items-center justify-between">
                  <Text className="text-sm text-gray-600">今日取消订单</Text>
                  <Text className="text-base font-medium text-gray-500">{todayStats.canceledOrders} 单</Text>
                </View>
              )}
            </View>

            {/* 近7天数据 */}
            <View className="p-4 pt-0">
              <View className="flex items-center justify-between mb-3">
                <Text className="text-base font-medium">近7天数据</Text>
                <Text className="text-xs text-gray-400">滚动统计</Text>
              </View>
              <View className="bg-white rounded-lg p-4">
                <View className="flex items-center justify-between py-3 border-b border-gray-50">
                  <Text className="text-sm text-gray-600">总订单数</Text>
                  <Text className="text-base font-medium">{weekStats.orders} 单</Text>
                </View>
                <View className="flex items-center justify-between py-3 border-b border-gray-50">
                  <Text className="text-sm text-gray-600">总销售额</Text>
                  <Text className="text-base font-medium text-red-500">¥{weekStats.revenue.toFixed(2)}</Text>
                </View>
                <View className="flex items-center justify-between py-3 border-b border-gray-50">
                  <Text className="text-sm text-gray-600">已支付订单</Text>
                  <Text className="text-base font-medium text-green-500">{weekStats.paidOrders} 单</Text>
                </View>
                <View className="flex items-center justify-between py-3">
                  <Text className="text-sm text-gray-600">客单价</Text>
                  <Text className="text-base font-medium text-orange-500">
                    ¥{weekStats.paidOrders > 0 ? (weekStats.revenue / weekStats.paidOrders).toFixed(2) : '0.00'}
                  </Text>
                </View>
              </View>
            </View>

            {/* 快捷入口 */}
            <View className="p-4 pt-0">
              <Text className="text-base font-medium mb-3 block">详细数据</Text>
              <View className="bg-white rounded-lg overflow-hidden">
                <View
                  className="p-4 border-b border-gray-50 flex items-center justify-between"
                  onClick={() => goTo('/pages/statistics/sales/index')}
                >
                  <View className="flex items-center gap-3">
                    <Text className="text-lg">📊</Text>
                    <Text className="text-sm text-gray-700">销售统计</Text>
                  </View>
                  <Text className="text-gray-400">→</Text>
                </View>
                <View
                  className="p-4 border-b border-gray-50 flex items-center justify-between"
                  onClick={() => goTo('/pages/statistics/users/index')}
                >
                  <View className="flex items-center gap-3">
                    <Text className="text-lg">👥</Text>
                    <Text className="text-sm text-gray-700">用户分析</Text>
                  </View>
                  <Text className="text-gray-400">→</Text>
                </View>
                <View
                  className="p-4 flex items-center justify-between"
                  onClick={() => goTo('/pages/order/list')}
                >
                  <View className="flex items-center gap-3">
                    <Text className="text-lg">📋</Text>
                    <Text className="text-sm text-gray-700">查看所有订单</Text>
                  </View>
                  <Text className="text-gray-400">→</Text>
                </View>
              </View>
            </View>

            {/* 刷新按钮 */}
            <View className="p-4 pt-0">
              <View
                className="bg-white rounded-lg p-4 text-center"
                onClick={loadData}
              >
                <Text className="text-sm text-blue-500">点击刷新数据</Text>
              </View>
            </View>
          </View>
        )}
      </ScrollView>
    </View>
  )
}

export default StatisticsDashboardPage
