import React, { useEffect, useState } from 'react';
import axios from 'axios';
import Header from '../../components/Header';
import './UserProfile.css'; // 复用个人资料页面的样式
import UserNav from './UserNav';

const NewbieTasks = () => {
  const [tasks, setTasks] = useState([]);
  const [experience, setExperience] = useState({});
  const [currentStep, setCurrentStep] = useState({});
  const [loading, setLoading] = useState(true);

  const baseURL = '/echo/task/tutorial';
  const userId = 1;

  // 获取所有任务
  const fetchTasks = async () => {
    try {
      const response = await axios.get(`${baseURL}/getAllTasks`, {
        params: { user_id: userId },
      });
      setTasks(response.data.tasks || []);
    } catch (error) {
      console.error('获取任务失败:', error);
    }
  };

  // 获取经验与等级信息
  const fetchExperience = async () => {
    try {
      const response = await axios.get(`${baseURL}/getAllTasks`, {
        params: { user_id: userId },
      });
      setExperience(response.data || {});
    } catch (error) {
      console.error('获取经验失败:', error);
    }
  };

  // 获取当前引导步骤
  const fetchCurrentStep = async () => {
    try {
      const response = await axios.get(`${baseURL}/getNewStep`, {
        params: { user_id: userId },
      });
      setCurrentStep(response.data || {});
    } catch (error) {
      console.error('获取引导步骤失败:', error);
    }
  };

  // 更新任务状态
  const updateStatus = async (taskId) => {
    try {
      await axios.post(`${baseURL}/updateStatus`, {
        user_id: userId,
        task_id: taskId,
      });
      await fetchTasks();
      await fetchExperience();
    } catch (error) {
      console.error('更新状态失败:', error);
    }
  };

  // 提交任务进度
  const updateProgress = async (taskId, progress) => {
    try {
      await axios.post(`${baseURL}/updateProgress`, {
        user_id: userId,
        task_id: taskId,
        progress,
      });
      await fetchTasks();
    } catch (error) {
      console.error('更新进度失败:', error);
    }
  };

  // 领取奖励
  const claimReward = async (taskId) => {
    try {
      await axios.post(`${baseURL}/rewardClaim`, {
        user_id: userId,
        task_id: taskId,
      });
      await fetchTasks();
      await fetchExperience();
    } catch (error) {
      console.error('领取奖励失败:', error);
    }
  };

  // 查看奖励是否已发放
  const checkRewardStatus = async (taskId) => {
    try {
      const response = await axios.post(`${baseURL}/rewardReview`, {
        user_id: userId,
        task_id: taskId,
      });
      alert(response.data.message || '已完成');
    } catch (error) {
      console.error('查看失败:', error);
    }
  };

  // 页面初始化
  useEffect(() => {
    const init = async () => {
      await fetchTasks();
      await fetchExperience();
      await fetchCurrentStep();
      setLoading(false);
    };
    init();
  }, []);

  if (loading) return <p className="loading">加载中...</p>;

  return (
    <div className="user-profile-container">
      <Header />
      <div className="user-center">
        <div className="user-nav-container">
          <UserNav activeKey="newbieTasks" onSelect={() => {}} />
        </div>

        <div className="common-card right-content">
          <div className="profile-header">
            <h1>🎯 新手考核</h1>
          </div>

          <div className="profile-details">
            <p><strong>当前经验：</strong>{experience.current_experience}</p>
            <p><strong>等级：</strong>{experience.level}</p>
            <p><strong>奖励经验：</strong>{experience.reward?.experience || 0}</p>
            <p><strong>奖励积分：</strong>{experience.reward?.points || 0}</p>
          </div>

          <div className="profile-details">
            <p><strong>🧭 当前引导步骤：</strong>{currentStep.current_step}</p>
            <p>{currentStep.step_description}</p>
          </div>

          <div className="profile-details">
            <h2>任务列表</h2>
            <ul>
              {tasks.map(task => (
                <li key={task.task_id} style={{ marginBottom: '20px' }}>
                  <p><strong>任务：</strong>{task.title}</p>
                  <p><strong>描述：</strong>{task.description}</p>
                  <p><strong>进度：</strong>{task.progress}%</p>
                  <p><strong>状态：</strong>{task.status}</p>
                  <p><strong>奖励：</strong>经验 {task.reward.experience}，积分 {task.reward.points}</p>

                  <div style={{ marginTop: '10px' }}>
                    <button className="task-btn" onClick={() => updateStatus(task.task_id)}>更新状态</button>
                    <button className="task-btn" onClick={() => updateProgress(task.task_id, 100)}>提交进度</button>
                    <button className="task-btn" onClick={() => claimReward(task.task_id)}>领取奖励</button>
                    <button className="task-btn" onClick={() => checkRewardStatus(task.task_id)}>查看奖励是否已发放</button>
                  </div>
                </li>
              ))}
            </ul>
          </div>
        </div>
      </div>
    </div>
  );
};

export default NewbieTasks;
