import React, { useEffect, useState } from 'react';
import { getExperience, updateExperience, checkUpgrade, upgradeUserLevel } from '../../api/level';
import LevelCard from '../../components/LevelCard';

const user_id = 1; // 实际项目中请从用户上下文获取

const LevelPage = () => {
  const [levelInfo, setLevelInfo] = useState(null);
  const [upgradeStatus, setUpgradeStatus] = useState(null);
  const [message, setMessage] = useState('');

  const fetchExperience = async () => {
    try {
      const res = await getExperience(user_id);
      setLevelInfo(res.data);
    } catch (error) {
      console.error(error);
    }
  };

  const handleUpdate = async () => {
    try {
      const res = await updateExperience({ user_id, experience: 50, source: '签到' });
      setMessage(res.data.message || '经验更新成功');
      fetchExperience();
    } catch (error) {
      console.error(error);
    }
  };

  const handleCheckUpgrade = async () => {
    try {
      const res = await checkUpgrade(user_id);
      setUpgradeStatus(res.data);
    } catch (error) {
      console.error(error);
    }
  };

  const handleUpgrade = async () => {
    try {
      const res = await upgradeUserLevel({ user_id, can_upgrade: true });
      setMessage(res.data.message || '升级成功');
      fetchExperience();
    } catch (error) {
      setMessage(error.response?.data?.message || '升级失败');
    }
  };

  useEffect(() => {
    fetchExperience();
  }, []);

  return (
    <div className="max-w-xl mx-auto p-4">
      <h1 className="text-2xl font-bold mb-4">我的等级</h1>
      {levelInfo && (
        <LevelCard
          level={levelInfo.level}
          current={levelInfo.current_experience}
          next={levelInfo.next_level_experience}
        />
      )}

      <div className="space-x-2 mb-4">
        <button
          onClick={handleUpdate}
          className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700"
        >
          模拟签到加经验
        </button>
        <button
          onClick={handleCheckUpgrade}
          className="px-4 py-2 bg-green-600 text-white rounded hover:bg-green-700"
        >
          检查是否可升级
        </button>
      </div>

      {upgradeStatus && (
        <div className="mb-4">
          {upgradeStatus.can_upgrade ? (
            <button
              onClick={handleUpgrade}
              className="px-4 py-2 bg-purple-600 text-white rounded hover:bg-purple-700"
            >
              升级到下一级
            </button>
          ) : (
            <p className="text-gray-700">当前还不能升级。</p>
          )}
        </div>
      )}

      {message && <div className="text-sm text-green-700 mt-2">{message}</div>}
    </div>
  );
};

export default LevelPage;
