import React,{ useState, useCallback, useEffect } from 'react';
import { useQuery } from '@tanstack/react-query';
import { useSearchParams } from "react-router";
import dayjs from 'dayjs';
import { message } from 'antd';
import { useSocketClient } from './hooks/useSocketClient.ts';
import { ClassroomDataAPI } from '../../api/classroom_data.ts';
import { ClassroomStatus } from '../../../share/types_stock.ts';
import type { ExamSocketRoomMessage } from './types.ts';
import type { AnswerRecord, Answer } from './types.ts';
import type { ClassroomData } from '../../../share/types_stock.ts';




// 答题卡页面
export default function ExamCard() {
  const [searchParams] = useSearchParams();
  const classroom = searchParams.get('classroom');
  const nickname = searchParams.get('nickname');
  const {
    socketRoom,
    answerManagement,
    currentQuestion,
    lastMessage,
    userAnswers
  } = useSocketClient(classroom as string);
  const [currentDate, setCurrentDate] = useState('');
  const [currentPrice, setCurrentPrice] = useState('0');
  const [holdingStock, setHoldingStock] = useState('0');
  const [holdingCash, setHoldingCash] = useState('0');
  const [isStarted, setIsStarted] = useState(false);
  const [answerRecords, setAnswerRecords] = useState<AnswerRecord[]>([]);

  const { data: classroomData, isLoading } = useQuery({
    queryKey: ['classroom', classroom],
    queryFn: async () => {
      if (!classroom) return null;
      const response = await ClassroomDataAPI.getClassroomDatas({ classroom_no: classroom });
      if (!response.data?.length) {
        message.error('获取教室数据失败');
        return null;
      }
      return response.data[0] || null;
    },
    enabled: !!classroom
  });

  useEffect(() => {
    if (!classroom || !nickname) {
      globalThis.location.href = '/exam';
      return;
    }
    if (classroomData && classroomData.status !== ClassroomStatus.OPEN) {
      message.error('该教室已关闭');
      globalThis.location.href = '/exam';
      return;
    }
  }, [classroom, nickname, classroomData]);

  // 处理房间消息
  useEffect(() => {
    if (!lastMessage?.message) return;

    const { type } = lastMessage.message;
    
    // 只处理重开消息的UI重置
    if (type === 'restart') {
      setCurrentDate('');
      setCurrentPrice('0');
      setHoldingStock('0');
      setHoldingCash('0');
      setIsStarted(false);
      setAnswerRecords([]);
    }
  }, [lastMessage]);

  useEffect(() => {
    if (currentQuestion) {
      console.log('currentQuestion', currentQuestion);
      setCurrentDate(currentQuestion.date);
      setCurrentPrice(String(currentQuestion.price));
      setIsStarted(true);
    } else {
      // 如果没有当前问题，重置状态
      setCurrentDate('');
      setCurrentPrice('0');
      setIsStarted(false);
    }
  }, [currentQuestion]);

  // 处理选择A（持股）
  const handleChooseA = useCallback(async () => {
    setHoldingStock('1');
    setHoldingCash('0');
    
    if (classroom && nickname) {
      const answer = {
        date: currentDate,
        holdingStock: '1',
        holdingCash: '0',
        userId: nickname,
        price: currentPrice
      };
      
      try {
        await answerManagement.storeAnswer(
          classroom as string,
          currentQuestion?.id || '',
          nickname,
          answer
        );
      } catch (error) {
        message.error('提交答案失败');
      }
    }
  }, [classroom, nickname, currentDate, currentPrice, answerManagement, currentQuestion]);

  const handleChooseB = useCallback(async () => {
    setHoldingStock('0');
    setHoldingCash('1');
    
    if (classroom && nickname) {
      const answer = {
        date: currentDate,
        holdingStock: '0',
        holdingCash: '1',
        userId: nickname,
        price: currentPrice
      };
      
      try {
        await answerManagement.storeAnswer(
          classroom as string,
          currentQuestion?.id || '',
          nickname,
          answer
        );
      } catch (error) {
        message.error('提交答案失败');
      }
    }
  }, [classroom, nickname, currentDate, currentPrice, answerManagement, currentQuestion]);

  // 初始化用户的答题记录
  useEffect(() => {
    if (userAnswers && userAnswers.length > 0) {
      const lastAnswer = userAnswers[userAnswers.length - 1];
      setHoldingStock(lastAnswer.holdingStock);
      setHoldingCash(lastAnswer.holdingCash);
      
      // 直接使用 userAnswers 中已计算好的数据
      const records = userAnswers.map((answer: Answer, index: number): AnswerRecord => ({
        date: answer.date,
        price: String(answer.price || '0'),
        holdingStock: answer.holdingStock,
        holdingCash: answer.holdingCash,
        profitAmount: answer.profitAmount || 0,
        profitPercent: answer.profitPercent || 0,
        index: index + 1
      }));
      
      setAnswerRecords(records);
    }
  }, [userAnswers]);

  if (isLoading || !classroomData) {
    return <div className="flex items-center justify-center min-h-screen">加载中...</div>;
  }

  return (
    <div className="flex flex-col items-center min-h-screen bg-gray-100 py-8">
      {/* 选择区域 */}
      <div className="w-full max-w-2xl">
        <div className="text-center mb-8">
          <h2 className="text-2xl font-bold mb-2">持股选A, 持币选B</h2>
          <div className="flex justify-center space-x-4 text-gray-600">
            {isStarted ? (
              <>
                <span>日期: {currentDate}</span>
                <span>价格: {currentPrice}</span>
              </>
            ) : (
              <div className="text-blue-600">
                <div className="mb-2">等待训练开始...</div>
                <div className="text-sm text-gray-500">
                  训练日期: {dayjs(classroomData.training_date).format('YYYY-MM-DD')}
                </div>
              </div>
            )}
          </div>
        </div>

        {/* 选择按钮 */}
        <div className="flex justify-center items-center space-x-4 mb-8 bg-white p-6 rounded-lg shadow-md">
          <button
            onClick={handleChooseA}
            disabled={!isStarted}
            className={`flex-1 py-8 text-3xl font-bold rounded-lg transition-colors ${
              !isStarted 
                ? 'bg-gray-200 text-gray-400 cursor-not-allowed'
                : holdingStock === '1'
                  ? 'bg-red-500 text-white'
                  : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
            }`}
          >
            A
          </button>
          <div className="text-xl font-medium text-gray-700">
            {isStarted ? '开始' : '等待'}
          </div>
          <button
            onClick={handleChooseB}
            disabled={!isStarted}
            className={`flex-1 py-8 text-3xl font-bold rounded-lg transition-colors ${
              !isStarted 
                ? 'bg-gray-200 text-gray-400 cursor-not-allowed'
                : holdingCash === '1'
                  ? 'bg-green-500 text-white'
                  : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
            }`}
          >
            B
          </button>
        </div>

        {/* 信息显示 */}
        <div className="bg-white p-6 rounded-lg shadow-md">
          <div className="grid grid-cols-2 gap-4 mb-4">
            <div className="text-gray-600">昵称: {nickname}</div>
            <div className="text-gray-600">代码: {classroomData.code}</div>
          </div>

          {/* 表格头部 */}
          <div className="grid grid-cols-8 gap-4 py-2 border-b border-gray-200 text-sm font-medium text-gray-600">
            <div>序</div>
            <div>训练日期</div>
            <div>持股</div>
            <div>持币</div>
            <div>价格</div>
            <div>收益(元)</div>
            <div>盈亏率</div>
            <div>号</div>
          </div>

          {/* 表格内容 */}
          <div className="max-h-60 overflow-y-auto">
            {[...answerRecords].reverse().map((record: AnswerRecord) => (
              <div key={record.date} className="grid grid-cols-8 gap-4 py-2 text-sm text-gray-800 hover:bg-gray-50">
                <div>{record.index}</div>
                <div>{dayjs(record.date).format('YYYY-MM-DD')}</div>
                <div className="text-red-500">{record.holdingStock}</div>
                <div className="text-green-500">{record.holdingCash}</div>
                <div>{record.price}</div>
                <div className={record.profitAmount >= 0 ? 'text-red-500' : 'text-green-500'}>
                  {record.profitAmount.toFixed(2)}
                </div>
                <div className={record.profitPercent >= 0 ? 'text-red-500' : 'text-green-500'}>
                  {record.profitPercent.toFixed(2)}%
                </div>
                <div>{record.index}</div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}