import { useState, useEffect } from 'react';

const GITEE_API = 'https://gitee.com/api/v5/repos/camelliamc/gitlink-feedback';
const TOKEN = 'f8433b20f2a07a28cf95aa0e17edfac4';

const getDocTitle = (path) => {
  const cleanPath = path.replace(/^\//, '');
  return `Vote_${cleanPath.replace(/\//g, '_')}`;
};

export default function VoteButtons() {
  const [upvotes, setUpvotes] = useState(0);
  const [downvotes, setDownvotes] = useState(0);
  const [userVote, setUserVote] = useState(null); // null | 'up' | 'down'
  const [docPath, setDocPath] = useState('');
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    const path = window.location.pathname;
    setDocPath(path);
    const stored = localStorage.getItem(`vote_${path}`);
    if (stored === 'up' || stored === 'down') {
      setUserVote(stored);
    }
    fetchVotes(path);
  }, []);

  const fetchVotes = async (path) => {
    try {
      const res = await fetch(`${GITEE_API}/issues?access_token=${TOKEN}&state=open&labels=vote`);
      const data = await res.json();
      const title = getDocTitle(path);
      const issue = data.find(i => i.title === title);

      if (issue) {
        const labels = issue.labels || [];
        const upLabel = labels.find(l => l.name.startsWith('up:'));
        const downLabel = labels.find(l => l.name.startsWith('down:'));
        if (upLabel) setUpvotes(parseInt(upLabel.name.split(':')[1]) || 0);
        if (downLabel) setDownvotes(parseInt(downLabel.name.split(':')[1]) || 0);
      }
    } catch (e) {
      console.error('获取投票失败:', e);
    }
  };

  const updateGiteeIssue = async (newUp, newDown) => {
    const title = getDocTitle(docPath);
    const res = await fetch(`${GITEE_API}/issues?access_token=${TOKEN}&state=open&labels=vote`);
    const data = await res.json();
    const existingIssue = data.find(i => i.title === title);
    const labels = [`vote`, `up:${newUp}`, `down:${newDown}`];

    if (existingIssue) {
      await fetch(`${GITEE_API}/issues/${existingIssue.number}?access_token=${TOKEN}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ labels })
      });
    } else {
      await fetch(`${GITEE_API}/issues?access_token=${TOKEN}`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          title,
          body: `文档投票 - ${docPath}`,
          labels
        })
      });
    }
  };

  const handleVote = async (type) => {
    if (loading || !docPath) return;
    setLoading(true);

    try {
      let newUp = upvotes;
      let newDown = downvotes;
      let newVote = null;

      if (userVote === null) {
        // 未投票 → 投票
        if (type === 'up') {
          newUp = upvotes + 1;
        } else {
          newDown = downvotes + 1;
        }
        newVote = type;
      } else if (userVote === type) {
        // 点击已选中的 → 取消投票
        if (type === 'up') {
          newUp = Math.max(0, upvotes - 1);
        } else {
          newDown = Math.max(0, downvotes - 1);
        }
        newVote = null;
      } else {
        // 切换投票
        if (type === 'up') {
          newUp = upvotes + 1;
          newDown = Math.max(0, downvotes - 1);
        } else {
          newDown = downvotes + 1;
          newUp = Math.max(0, upvotes - 1);
        }
        newVote = type;
      }

      await updateGiteeIssue(newUp, newDown);

      setUpvotes(newUp);
      setDownvotes(newDown);
      setUserVote(newVote);

      if (newVote) {
        localStorage.setItem(`vote_${docPath}`, newVote);
      } else {
        localStorage.removeItem(`vote_${docPath}`);
      }
    } catch (e) {
      console.error('投票失败:', e);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="vote-container">
      <span className="vote-label">这篇文档有帮助吗？</span>
      <div className="vote-buttons">
        <button
          onClick={() => handleVote('up')}
          className={`vote-btn vote-btn-up ${userVote === 'up' ? 'vote-btn-active-up' : ''}`}
          title={userVote === 'up' ? '取消投票' : '有帮助'}
        >
          <span className="vote-emoji">👍</span>
          <span className="vote-count">{upvotes}</span>
        </button>
        <button
          onClick={() => handleVote('down')}
          className={`vote-btn vote-btn-down ${userVote === 'down' ? 'vote-btn-active-down' : ''}`}
          title={userVote === 'down' ? '取消投票' : '没帮助'}
        >
          <span className="vote-emoji">👎</span>
          <span className="vote-count">{downvotes}</span>
        </button>
      </div>
    </div>
  );
}