import React, { useState } from 'react';
import { followUser, unfollowUser } from '../api/api_ljc';

const FollowButton = ({ userId, isFollowing, onFollowChange, style }) => {
  const [loading, setLoading] = useState(false);
  const handleFollow = async () => {
    if (loading) return;
    setLoading(true);
    try {
      console.log('FollowButton clicked, isFollowing:', isFollowing, 'userId:', userId);
      if (isFollowing) {
        const res = await unfollowUser(userId);
        console.log('unfollowUser response:', res);
        onFollowChange(false);
      } else {
        const res = await followUser(userId);
        console.log('followUser response:', res);
        onFollowChange(true);
      }
    } catch (error) {
      alert('关注操作失败，请重试！');
      console.error('关注操作失败:', error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <button
      onClick={handleFollow}
      disabled={loading}
      style={{
        border: 'none',
        outline: 'none',
        borderRadius: 20,
        padding: '6px 22px',
        fontSize: 15,
        fontWeight: 600,
        cursor: loading ? 'not-allowed' : 'pointer',
        background: isFollowing ? '#f5f5f5' : 'linear-gradient(90deg,#ff4b2b,#ff416c)',
        color: isFollowing ? '#888' : '#fff',
        boxShadow: isFollowing ? 'none' : '0 2px 8px #ff416c22',
        transition: 'all 0.2s',
        ...style
      }}
    >
      {loading ? '处理中...' : isFollowing ? '已关注' : '+ 关注'}
    </button>
  );
};

export default FollowButton;