import React, { useState, useEffect } from 'react';
import { useGroupStore } from '../../context/useGroupStore';
import { useUser } from '../../context/UserContext';
import CreatePostForm from './CreatePostForm';
import axios from 'axios';

const GroupItem = ({ group }) => {
  const { handleJoinGroup, joinStatus, setJoinStatus,fetchGroupList } = useGroupStore();
  const { user } = useUser();

  const userId = user?.userId;
  const groupId = group.groupId;

  const [isMember, setIsMember] = useState(false);
  const [loading, setLoading] = useState(false); // 新增：加载状态
  const [error, setError] = useState(''); // 新增：错误信息

  useEffect(() => {
    console.log('joinStatus updated:', joinStatus);
    setIsMember(joinStatus[groupId] === '加入成功');
  }, [joinStatus, groupId]);

  // 初始挂载时检查成员状态（新增）
  useEffect(() => {
    if (userId && groupId) {
      checkMembershipStatus();
    }
  }, [userId, groupId]);

  // 检查成员状态（新增）
  const checkMembershipStatus = async () => {
    try {
      const res = await axios.get(`/echo/groups/${groupId}/members`);
      const isMember = res.data.members.some(member => member.user_id === userId);
      setIsMember(isMember);
      // setJoinStatus(groupId, isMember ? '加入成功' : '未加入');
    } catch (error) {
      console.error('检查成员状态失败:', error);
    }
  };

  const [showCreatePost, setShowCreatePost] = useState(false);

  const handleLeaveGroup = async () => {
    setLoading(true);
    try {
      const res = await axios.post(`/echo/groups/${groupId}/leave`, {
        user_id: userId,
      });
      if (res.data.status === 'success') {
          fetchGroupList(); // 刷新小组列表
        // setJoinStatus(groupId, '未加入');
        setIsMember(false);
        // 可选：刷新小组成员计数
        group.memberCount = (group.memberCount || 0) - 1;
      } else {
        setError(res.data.message || '退出失败');
      }
    } catch (error) {
      console.error('退出小组失败:', error);
      setError('退出小组失败');
    } finally {
      setLoading(false);
    }
  };

  // 修改加入小组逻辑（新增）
  const handleJoin = async () => {
    setLoading(true);
    try {
      const res = await handleJoinGroup(groupId, userId);
      if (res && res.status === 'success') {
        setJoinStatus(groupId, '加入成功');
        setIsMember(true);
        // 可选：刷新小组成员计数
        group.memberCount = (group.memberCount || 0) + 1;
      } else {
        setError(res?.message || '加入失败');
      }
    } catch (error) {
      console.error('加入小组失败:', error);
      setError('加入小组失败');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="group-item">
      <div className="group-content">
        <img
          style={{ width: '40%', height: '40%' }}
          src={group.coverImage || 'https://picsum.photos/200/200'}
          alt={group.groupName}
          className="group-cover"
        />
        <div className="group-info-right">
          <h3>{group.groupName}</h3>
          <p style={{ color: '#BA929A' }}>{group.memberCount || 0}人加入了小组</p>

          {/* 加入/退出按钮逻辑 */}
          {userId && (
            <button
              onClick={() => {
                if (isMember) {
                  handleLeaveGroup();
                } else {
                  handleJoin();
                }
              }}
              disabled={loading}
            >
              {loading ? '处理中...' : isMember ? '退出小组' : '+加入小组'}
            </button>
          )}
          {!userId && <button disabled>请登录</button>}

          {/* 显示错误信息（新增） */}
          {error && <p style={{ color: 'red' }}>{error}</p>}

          {/* 发布帖子按钮 */}
          {userId && isMember && (
            <button onClick={() => setShowCreatePost(!showCreatePost)}>
              +发布帖子
            </button>
          )}
        </div>
      </div>

      <div className="group-description">
        <p>{group.description}</p>
      </div>
      <p>分类：{group.category}</p>

      {showCreatePost && (
        <CreatePostForm 
          groupId={groupId}
          onClose={() => setShowCreatePost(false)}
        />
      )}
    </div>
  );
};

export default GroupItem;
