import React, { useState, useEffect, memo } from 'react'
import { View, Text, ScrollView, Picker } from '@tarojs/components'
import { useQuery } from '@tanstack/react-query'
import { YongrenTabBarLayout } from '@d8d/yongren-shared-ui/components/YongrenTabBarLayout'
import { Navbar } from '@d8d/mini-shared-ui-components/components/navbar'
import { ColumnChart } from '@d8d/mini-charts/components/ColumnChart'
import { PieChart } from '@d8d/mini-charts/components/PieChart'
import { BarChart } from '@d8d/mini-charts/components/BarChart'
import { enterpriseStatisticsClient } from '../../api/enterpriseStatisticsClient'
import type {
  DisabilityTypeDistributionResponse,
  GenderDistributionResponse,
  AgeDistributionResponse,
  HouseholdDistributionResponse,
  JobStatusDistributionResponse,
  SalaryDistributionResponse
} from '../../api/types'

/**
 * 数据转换工具：将API统计数据转换为柱状图格式
 */
const convertToColumnData = (stats: any[]) => ({
  categories: stats.map(item => item.key),
  series: [{
    name: '人数',
    data: stats.map(item => item.value || 0)
  }]
})

/**
 * 数据转换工具：将API统计数据转换为饼图格式
 */
const convertToPieData = (stats: any[]) =>
  stats.map(item => ({
    name: item.key,
    data: item.value || 0
  }))

export interface StatisticsProps {
  // 组件属性定义（目前为空）
}

const Statistics: React.FC<StatisticsProps> = () => {
  // 状态：时间筛选（年-月）
  const [timeFilter, setTimeFilter] = useState({ year: 2023, month: 11 })
  const [showDatePicker, setShowDatePicker] = useState(false)

  // 生成年份选项（最近5年）
  const currentYear = new Date().getFullYear()
  const years = Array.from({ length: 5 }, (_, i) => currentYear - 4 + i)

  // 月份选项
  const months = Array.from({ length: 12 }, (_, i) => i + 1)

  // 状态：图表懒加载控制 - 哪些图表已经加载
  const [loadedCharts, setLoadedCharts] = useState<Set<string>>(new Set(['disability', 'gender'])) // 默认加载前两个关键图表

  // 类型守卫：检查响应是否包含统计数据
  const isSuccessfulResponse = (data: any): data is { companyId: number; stats: any[]; total: number } => {
    return data && typeof data === 'object' && 'stats' in data && Array.isArray(data.stats)
  }

  // 获取统计数据数组，如果响应不成功则返回空数组
  const getStats = (data: any): any[] => {
    return isSuccessfulResponse(data) ? data.stats : []
  }

  // 图表懒加载效果：逐步加载其他图表
  useEffect(() => {
    const timer1 = setTimeout(() => {
      setLoadedCharts(prev => new Set([...prev, 'age', 'household']))
    }, 500) // 500ms后加载年龄和户籍分布

    const timer2 = setTimeout(() => {
      setLoadedCharts(prev => new Set([...prev, 'jobStatus', 'salary']))
    }, 1000) // 1000ms后加载在职状态和薪资分布

    return () => {
      clearTimeout(timer1)
      clearTimeout(timer2)
    }
  }, [])

  // 处理时间筛选变化
  const handleTimeFilterChange = (newYear: number, newMonth: number) => {
    setTimeFilter({ year: newYear, month: newMonth })
    console.log('时间筛选变更:', newYear, '年', newMonth, '月')
    // TODO: 根据选择的年月重新加载数据
  }

  // 处理年份选择
  const onYearChange = (e: any) => {
    const selectedYear = years[e.detail.value]
    setTimeFilter(prev => ({ ...prev, year: selectedYear }))
  }

  // 处理月份选择
  const onMonthChange = (e: any) => {
    const selectedMonth = months[e.detail.value]
    setTimeFilter(prev => ({ ...prev, month: selectedMonth }))
  }

  // 获取残疾类型分布数据
  const { data: disabilityData, isLoading: isLoadingDisability } = useQuery({
    queryKey: ['statistics', 'disability-type-distribution'],
    queryFn: async () => {
      const response = await enterpriseStatisticsClient['disability-type-distribution'].$get({ query: {} })
      return await response.json()
    },
    enabled: loadedCharts.has('disability'),
    staleTime: 5 * 60 * 1000, // 数据过期时间5分钟
    gcTime: 10 * 60 * 1000 // 缓存时间10分钟
  })

  // 获取性别分布数据
  const { data: genderData, isLoading: isLoadingGender } = useQuery({
    queryKey: ['statistics', 'gender-distribution'],
    queryFn: async () => {
      const response = await enterpriseStatisticsClient['gender-distribution'].$get({ query: {} })
      return await response.json()
    },
    enabled: loadedCharts.has('gender'),
    staleTime: 5 * 60 * 1000, // 数据过期时间5分钟
    gcTime: 10 * 60 * 1000 // 缓存时间10分钟
  })

  // 获取年龄分布数据
  const { data: ageData, isLoading: isLoadingAge } = useQuery({
    queryKey: ['statistics', 'age-distribution'],
    queryFn: async () => {
      const response = await enterpriseStatisticsClient['age-distribution'].$get({ query: {} })
      return await response.json()
    },
    enabled: loadedCharts.has('age'),
    staleTime: 5 * 60 * 1000, // 数据过期时间5分钟
    gcTime: 10 * 60 * 1000 // 缓存时间10分钟
  })

  // 获取户籍分布数据
  const { data: householdData, isLoading: isLoadingHousehold } = useQuery({
    queryKey: ['statistics', 'household-distribution'],
    queryFn: async () => {
      const response = await enterpriseStatisticsClient['household-distribution'].$get({ query: {} })
      return await response.json()
    },
    enabled: loadedCharts.has('household'),
    staleTime: 5 * 60 * 1000, // 数据过期时间5分钟
    gcTime: 10 * 60 * 1000 // 缓存时间10分钟
  })

  // 获取在职状态分布数据
  const { data: jobStatusData, isLoading: isLoadingJobStatus } = useQuery({
    queryKey: ['statistics', 'job-status-distribution'],
    queryFn: async () => {
      const response = await enterpriseStatisticsClient['job-status-distribution'].$get({ query: {} })
      return await response.json()
    },
    enabled: loadedCharts.has('jobStatus'),
    staleTime: 5 * 60 * 1000, // 数据过期时间5分钟
    gcTime: 10 * 60 * 1000 // 缓存时间10分钟
  })

  // 获取薪资分布数据
  const { data: salaryData, isLoading: isLoadingSalary } = useQuery({
    queryKey: ['statistics', 'salary-distribution'],
    queryFn: async () => {
      const response = await enterpriseStatisticsClient['salary-distribution'].$get({ query: {} })
      return await response.json()
    },
    enabled: loadedCharts.has('salary'),
    staleTime: 5 * 60 * 1000, // 数据过期时间5分钟
    gcTime: 10 * 60 * 1000 // 缓存时间10分钟
  })

  const isLoading = isLoadingDisability || isLoadingGender || isLoadingAge ||
                    isLoadingHousehold || isLoadingJobStatus || isLoadingSalary

  return (
    <YongrenTabBarLayout activeKey="statistics">
      <ScrollView
        className="h-[calc(100%-60px)] overflow-y-auto px-4 pb-4 pt-0"
        scrollY
      >
        {/* 导航栏 */}
        <Navbar
          title="数据统计"
          leftIcon=""
          leftText=""
          onClickLeft={() => {}}
          backgroundColor="bg-white"
          border={true}
          fixed={true}
          placeholder={true}
        />

        {/* 数据筛选区域 - 对应原型第880-886行 */}
        <View className="mb-4 pt-4">
          <View className="flex justify-between items-center mb-3">
            <Text className="font-semibold text-gray-700">数据统计</Text>
            <View className="flex items-center bg-gray-100 rounded-lg">
              {/* 年份选择器 */}
              <Picker
                mode="selector"
                range={years}
                value={years.indexOf(timeFilter.year)}
                onChange={onYearChange}
              >
                <View className="flex items-center px-3 py-1">
                  <Text className="text-sm text-gray-700">{timeFilter.year}年</Text>
                </View>
              </Picker>
              {/* 月份选择器 */}
              <Picker
                mode="selector"
                range={months}
                value={timeFilter.month - 1}
                onChange={onMonthChange}
              >
                <View className="flex items-center px-2 py-1">
                  <Text className="text-sm text-gray-700">{timeFilter.month}月</Text>
                  <Text className="fas fa-chevron-down text-gray-500 ml-1"></Text>
                </View>
              </Picker>
            </View>
          </View>
        </View>


        {/* 统计卡片 */}
        <View className="grid grid-cols-2 gap-3 mb-4">
          <View className="stat-card bg-white rounded-lg p-3 shadow-sm flex flex-col">
            <Text className="text-sm text-gray-600 mb-2">在职人数</Text>
            <Text className="text-2xl font-bold text-gray-800">24</Text>
            <Text className="text-xs text-green-500 mt-1">↑ 比上月增加2人</Text>
          </View>
          <View className="stat-card bg-white rounded-lg p-3 shadow-sm flex flex-col">
            <Text className="text-sm text-gray-600 mb-2">平均薪资</Text>
            <Text className="text-2xl font-bold text-gray-800">¥4,650</Text>
            <Text className="text-xs text-green-500 mt-1">↑ 比上月增加¥150</Text>
          </View>
          <View className="stat-card bg-white rounded-lg p-3 shadow-sm flex flex-col">
            <Text className="text-sm text-gray-600 mb-2">在职率</Text>
            <Text className="text-2xl font-bold text-gray-800">92%</Text>
            <Text className="text-xs text-green-500 mt-1">↑ 比上月提升3%</Text>
          </View>
          <View className="stat-card bg-white rounded-lg p-3 shadow-sm flex flex-col">
            <Text className="text-sm text-gray-600 mb-2">新增人数</Text>
            <Text className="text-2xl font-bold text-gray-800">3</Text>
            <Text className="text-xs text-red-500 mt-1">↓ 比上月减少1人</Text>
          </View>
        </View>

        {/* 残疾类型分布 */}
        <View className="card bg-white p-4 mb-4 rounded-lg shadow-sm flex flex-col">
          <Text className="font-semibold text-gray-700">残疾类型分布</Text>
          {isLoadingDisability ? (
            <Text className="text-gray-500 text-center py-4">加载中...</Text>
          ) : (
            (() => {
              const stats = getStats(disabilityData)
              if (stats.length > 0) {
                const chartData = convertToColumnData(stats)
                return (
                  <View className="mt-3">
                    <ColumnChart
                      canvasId="disability-type-chart"
                      width={650}
                      height={200}
                      categories={chartData.categories}
                      series={chartData.series}
                      config={{
                        color: ['#3b82f6'],
                        fontSize: 10,
                        dataLabel: true,
                        xAxis: { disableGrid: true },
                        yAxis: {}
                      }}
                      tooltipFormatter={(item: any, category: string) => {
                        const statItem = stats.find(s => s.key === category)
                        return `${category} ${item.data}人 (${statItem?.percentage || 0}%)`
                      }}
                    />
                  </View>
                )
              } else {
                return <Text className="text-gray-500 text-center py-4 mt-3">暂无数据</Text>
              }
            })()
          )}
        </View>

        {/* 性别分布 */}
        <View className="card bg-white p-4 mb-4 rounded-lg shadow-sm flex flex-col">
          <Text className="font-semibold text-gray-700">性别分布</Text>
          {isLoadingGender ? (
            <Text className="text-gray-500 text-center py-4">加载中...</Text>
          ) : (() => {
              const genderStats = getStats(genderData)
              return genderStats.length > 0 ? (
                <View className="mt-3">
                  <ColumnChart
                    canvasId="gender-chart"
                    width={650}
                    height={200}
                    categories={genderStats.map(s => s.key)}
                    series={[{
                      name: '人数',
                      data: genderStats.map(s => s.value || 0)
                    }]}
                    config={{
                      color: ['#3b82f6', '#ec4899'],
                      fontSize: 11,
                      dataLabel: true,
                      xAxis: { disableGrid: true },
                      yAxis: {}
                    }}
                    tooltipFormatter={(item: any, category: string) => {
                      const statItem = genderStats.find(s => s.key === category)
                      return `${category} ${item.data}人 (${statItem?.percentage || 0}%)`
                    }}
                  />
                </View>
              ) : (
                <Text className="text-gray-500 text-center py-4">暂无数据</Text>
              )
            })()}
        </View>

        {/* 年龄分布 */}
        <View className="card bg-white p-4 mb-4 rounded-lg shadow-sm flex flex-col">
          <Text className="font-semibold text-gray-700">年龄分布</Text>
          {isLoadingAge ? (
            <Text className="text-gray-500 text-center py-4">加载中...</Text>
          ) : (() => {
              const ageStats = getStats(ageData)
              return ageStats.length > 0 ? (
                <View className="mt-3">
                  <PieChart
                    canvasId="age-chart"
                    width={650}
                    height={300}
                    pieType="pie"
                    series={convertToPieData(ageStats)}
                    config={{
                      color: ['#3b82f6', '#10b981', '#f59e0b', '#8b5cf6', '#ef4444'],
                      fontSize: 10,
                      dataLabel: true,
                      legend: { show: true }
                    }}
                    tooltipFormatter={(item: any) => {
                      const statItem = ageStats.find(s => s.key === item.name)
                      return `${item.name} ${item.data}人 (${statItem?.percentage || 0}%)`
                    }}
                  />
                </View>
              ) : (
                <Text className="text-gray-500 text-center py-4">暂无数据</Text>
              )
            })()}
        </View>

        {/* 户籍省份分布 */}
        <View className="card bg-white p-4 mb-4 rounded-lg shadow-sm flex flex-col">
          <Text className="font-semibold text-gray-700">户籍省份分布</Text>
          {isLoadingHousehold ? (
            <Text className="text-gray-500 text-center py-4">加载中...</Text>
          ) : (() => {
              const stats = getStats(householdData)
              if (stats.length > 0) {
                const chartData = convertToColumnData(stats.slice(0, 6))
                return (
                  <View className="mt-3">
                    <BarChart
                      canvasId="household-chart"
                      width={650}
                      height={280}
                      categories={chartData.categories}
                      series={chartData.series}
                      config={{
                        color: ['#3b82f6', '#10b981', '#f59e0b', '#8b5cf6', '#ef4444', '#ec4899'],
                        fontSize: 10,
                        dataLabel: true,
                        xAxis: { disableGrid: true },
                        yAxis: {}
                      }}
                      tooltipFormatter={(item: any, category: string) => {
                        const statItem = stats.find(s => s.key === category)
                        return `${category} ${item.data}人 (${statItem?.percentage || 0}%)`
                      }}
                    />
                  </View>
                )
              } else {
                return <Text className="text-gray-500 text-center py-4 mt-3">暂无数据</Text>
              }
            })()}
        </View>

        {/* 在职状态统计 */}
        <View className="card bg-white p-4 mb-4 rounded-lg shadow-sm flex flex-col">
          <Text className="font-semibold text-gray-700">在职状态统计</Text>
          {isLoadingJobStatus ? (
            <Text className="text-gray-500 text-center py-4">加载中...</Text>
          ) : (() => {
              const stats = getStats(jobStatusData)
              if (stats.length > 0) {
                return (
                  <View className="mt-3">
                    <PieChart
                      canvasId="job-status-chart"
                      width={650}
                      height={300}
                      pieType="ring"
                      series={convertToPieData(stats)}
                      config={{
                        color: ['#3b82f6', '#f59e0b', '#ef4444', '#10b981'],
                        fontSize: 10,
                        dataLabel: true,
                        legend: { show: true }
                      }}
                      tooltipFormatter={(item: any) => {
                        const statItem = stats.find(s => s.key === item.name)
                        return `${item.name} ${item.data}人 (${statItem?.percentage || 0}%)`
                      }}
                    />
                  </View>
                )
              } else {
                return <Text className="text-gray-500 text-center py-4 mt-3">暂无数据</Text>
              }
            })()}
        </View>

        {/* 薪资分布 */}
        <View className="card bg-white p-4 rounded-lg shadow-sm flex flex-col">
          <Text className="font-semibold text-gray-700">薪资分布</Text>
          {isLoadingSalary ? (
            <Text className="text-gray-500 text-center py-4">加载中...</Text>
          ) : (() => {
              const stats = getStats(salaryData)
              if (stats.length > 0) {
                const chartData = convertToColumnData(stats)
                return (
                  <View className="mt-3">
                    <BarChart
                      canvasId="salary-chart"
                      width={650}
                      height={280}
                      categories={chartData.categories}
                      series={chartData.series}
                      config={{
                        color: ['#3b82f6', '#10b981', '#f59e0b', '#8b5cf6', '#ef4444'],
                        fontSize: 10,
                        dataLabel: true,
                        xAxis: { disableGrid: true },
                        yAxis: {}
                      }}
                      tooltipFormatter={(item: any, category: string) => {
                        const statItem = stats.find(s => s.key === category)
                        return `${category} ${item.data}人 (${statItem?.percentage || 0}%)`
                      }}
                    />
                  </View>
                )
              } else {
                return <Text className="text-gray-500 text-center py-4 mt-3">暂无数据</Text>
              }
            })()}
        </View>
      </ScrollView>
    </YongrenTabBarLayout>
  )
}

export default memo(Statistics)