import React, { useState, useEffect, useCallback, useMemo } from 'react'
import { Search, Download, ArrowLeft } from 'lucide-react'
import { useNavigate } from 'react-router-dom'
import ApiService from '../services/apiService'
import EventService, { EVENT_TYPES } from '../services/eventService'
import type { PrizeConfig } from '../database/database'
import type { LotteryRecord } from '../types'

// 为了兼容现有代码，创建DrawRecord类型别名
type DrawRecord = LotteryRecord & { is_winner: boolean }

// 页面组件属性接口 - 使用Record类型避免空接口警告
type RecordsPageProps = Record<string, never>

const Records: React.FC<RecordsPageProps> = () => {
  const navigate = useNavigate()
  const [records, setRecords] = useState<DrawRecord[]>([])
  const [prizes, setPrizes] = useState<PrizeConfig[]>([])
  const [loading, setLoading] = useState(true)
  const [searchTerm, setSearchTerm] = useState('')
  const [selectedPrize, setSelectedPrize] = useState<string>('')
  const [dateRange, setDateRange] = useState({ start: '', end: '' })
  const [stats, setStats] = useState({
    totalDraws: 0,
    totalWins: 0,
    winRate: 0,
    prizeStats: [] as { prize_name: string; count: number }[]
  })

  const loadData = useCallback(async () => {
    setLoading(true)
    try {
      const api = ApiService.getInstance()
      const [recordsData, prizesData] = await Promise.all([
        api.getAllRecords(),
        api.getAllPrizes()
      ])
      
      // 转换记录数据格式
      const formattedRecords: DrawRecord[] = recordsData.map(record => ({
        ...record,
        is_winner: record.prize_id !== null
      }))
      
      setRecords(formattedRecords)
      setPrizes(prizesData)
      calculateStats(formattedRecords)
    } catch (error) {
      console.error('Records页面 - 加载数据失败:', error)
      // 设置空数据以避免界面错误
      setRecords([])
      setPrizes([])
      setStats({
        totalDraws: 0,
        totalWins: 0,
        winRate: 0,
        prizeStats: []
      })
    } finally {
      setLoading(false)
    }
  }, [])

  useEffect(() => {
    loadData()
    
    // 监听记录更新事件，实现智能刷新
    const eventService = EventService.getInstance();
    const unsubscribeRecords = eventService.subscribe(EVENT_TYPES.RECORDS_UPDATED, () => {
      console.log('Records页面 - 收到记录更新事件，重新加载数据');
      loadData();
    });
    
    return () => {
      unsubscribeRecords();
    };
  }, [loadData])

  const calculateStats = (recordsData: DrawRecord[]) => {
    const totalDraws = recordsData.length
    const totalWins = recordsData.filter(r => r.is_winner).length
    const winRate = totalDraws > 0 ? (totalWins / totalDraws) * 100 : 0
    
    const prizeStats = recordsData
      .filter(r => r.is_winner && r.prize_name)
      .reduce((acc, record) => {
        const existing = acc.find(p => p.prize_name === record.prize_name)
        if (existing) {
          existing.count++
        } else {
          acc.push({ prize_name: record.prize_name!, count: 1 })
        }
        return acc
      }, [] as { prize_name: string; count: number }[])
    
    setStats({ totalDraws, totalWins, winRate, prizeStats })
  }

  // 使用useMemo优化过滤逻辑，避免重复计算
  const filteredRecords = useMemo(() => {
    return records.filter(record => {
      const matchesSearch = searchTerm === '' || 
        record.student_id.includes(searchTerm) ||
        (record.prize_name && record.prize_name.toLowerCase().includes(searchTerm.toLowerCase()))
      
      const matchesPrize = selectedPrize === '' || record.prize_name === selectedPrize
      
      const matchesDate = (!dateRange.start || new Date(record.draw_time) >= new Date(dateRange.start)) &&
                         (!dateRange.end || new Date(record.draw_time) <= new Date(dateRange.end))
      
      return matchesSearch && matchesPrize && matchesDate
    })
  }, [records, searchTerm, selectedPrize, dateRange])

  const exportRecords = () => {
    const csvContent = [
      ['学号', '抽奖时间', '是否中奖', '奖项名称'].join(','),
      ...filteredRecords.map(record => [
        record.student_id,
        new Date(record.draw_time).toLocaleString(),
        record.is_winner ? '是' : '否',
        record.prize_name || '未中奖'
      ].join(','))
    ].join('\n')
    
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
    const link = document.createElement('a')
    const url = URL.createObjectURL(blob)
    link.href = url
    link.download = `抽奖记录_${new Date().toISOString().split('T')[0]}.csv`
    link.click()
    
    // 清理URL对象，防止内存泄漏
    setTimeout(() => {
      URL.revokeObjectURL(url)
    }, 100)
  }

  if (loading) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-gray-900 to-gray-800 flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
          <p className="text-gray-300">加载中...</p>
        </div>
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-gray-900 to-gray-800 p-6">
      <div className="max-w-7xl mx-auto">
        {/* 头部 */}
        <div className="bg-gray-800 rounded-lg shadow-md p-6 mb-6 border border-gray-700">
          <div className="flex justify-between items-center mb-6">
            <div className="flex items-center gap-4">
              <button
                onClick={() => navigate('/')}
                className="flex items-center gap-2 px-3 py-2 text-gray-300 hover:text-gray-100 transition-colors rounded-lg hover:bg-gray-700"
              >
                <ArrowLeft size={20} />
                返回首页
              </button>
              <h1 className="text-3xl font-bold text-gray-100">抽奖记录查询</h1>
            </div>
            <button
              onClick={exportRecords}
              className="flex items-center gap-2 px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors"
            >
              <Download size={20} />
              导出记录
            </button>
          </div>

          {/* 统计信息 */}
          <div className="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
            <div className="bg-gray-700 p-4 rounded-lg border border-gray-600">
              <h3 className="text-sm font-medium text-blue-400 mb-1">总抽奖次数</h3>
              <p className="text-2xl font-bold text-blue-300">{stats.totalDraws}</p>
            </div>
            <div className="bg-gray-700 p-4 rounded-lg border border-gray-600">
              <h3 className="text-sm font-medium text-green-400 mb-1">中奖次数</h3>
              <p className="text-2xl font-bold text-green-300">{stats.totalWins}</p>
            </div>
            <div className="bg-gray-700 p-4 rounded-lg border border-gray-600">
              <h3 className="text-sm font-medium text-purple-400 mb-1">中奖率</h3>
              <p className="text-2xl font-bold text-purple-300">{stats.winRate.toFixed(1)}%</p>
            </div>
            <div className="bg-gray-700 p-4 rounded-lg border border-gray-600">
              <h3 className="text-sm font-medium text-orange-400 mb-1">奖项种类</h3>
              <p className="text-2xl font-bold text-orange-300">{stats.prizeStats.length}</p>
            </div>
          </div>

          {/* 筛选条件 */}
          <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
            <div className="relative">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" size={20} />
              <input
                type="text"
                placeholder="搜索学号或奖项名称"
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="w-full pl-10 pr-4 py-2 bg-gray-700 border border-gray-600 rounded-lg text-gray-100 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
              />
            </div>
            <select
              value={selectedPrize}
              onChange={(e) => setSelectedPrize(e.target.value)}
              className="px-3 py-2 bg-gray-700 border border-gray-600 rounded-lg text-gray-100 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
            >
              <option value="">所有奖项</option>
              {prizes.map(prize => (
                <option key={prize.id} value={prize.prize_name}>{prize.prize_name}</option>
              ))}
            </select>
            <input
              type="date"
              value={dateRange.start}
              onChange={(e) => setDateRange({ ...dateRange, start: e.target.value })}
              className="px-3 py-2 bg-gray-700 border border-gray-600 rounded-lg text-gray-100 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
            />
            <input
              type="date"
              value={dateRange.end}
              onChange={(e) => setDateRange({ ...dateRange, end: e.target.value })}
              className="px-3 py-2 bg-gray-700 border border-gray-600 rounded-lg text-gray-100 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
            />
          </div>
        </div>

        {/* 记录列表 */}
        <div className="bg-gray-800 rounded-lg shadow-md overflow-hidden border border-gray-700">
          <div className="overflow-x-auto">
            <table className="min-w-full divide-y divide-gray-600">
              <thead className="bg-gray-700">
                <tr>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-300 uppercase tracking-wider">
                    学号
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-300 uppercase tracking-wider">
                    抽奖时间
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-300 uppercase tracking-wider">
                    结果
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-300 uppercase tracking-wider">
                    奖项名称
                  </th>
                </tr>
              </thead>
              <tbody className="bg-gray-800 divide-y divide-gray-600">
                {filteredRecords.length === 0 ? (
                  <tr>
                    <td colSpan={4} className="px-6 py-12 text-center text-gray-400">
                      暂无记录
                    </td>
                  </tr>
                ) : (
                  filteredRecords.map((record) => (
                    <tr key={record.id} className="hover:bg-gray-700">
                      <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-100">
                        {record.student_id}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-300">
                        {new Date(record.draw_time).toLocaleString()}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-300">
                        <span className={`px-2 py-1 text-xs rounded-full ${
                          record.is_winner 
                            ? 'bg-green-100 text-green-800' 
                            : 'bg-red-100 text-red-800'
                        }`}>
                          {record.is_winner ? '中奖' : '未中奖'}
                        </span>
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-300">
                        {record.prize_name || '-'}
                      </td>
                    </tr>
                  ))
                )}
              </tbody>
            </table>
          </div>
        </div>

        {/* 奖项统计 */}
        {stats.prizeStats.length > 0 && (
          <div className="bg-gray-800 rounded-lg shadow-md p-6 mt-6 border border-gray-700">
            <h2 className="text-xl font-bold text-gray-100 mb-4">奖项统计</h2>
            <div className="grid grid-cols-1 md:grid-cols-3 lg:grid-cols-4 gap-4">
              {stats.prizeStats.map((stat, index) => (
                <div key={index} className="bg-gray-700 p-4 rounded-lg border border-gray-600">
                  <h3 className="text-sm font-medium text-gray-300 mb-1">{stat.prize_name}</h3>
                  <p className="text-xl font-bold text-gray-100">{stat.count} 次</p>
                </div>
              ))}
            </div>
          </div>
        )}
      </div>
    </div>
  )
}

export default Records