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

const GroupItem = ({ group }) => {

  console.log('group:', group);
  const { handleJoinGroup, joinStatus } = useGroupStore();
  const { user } = useUser();
  
  const userId = user?.userId;
  const groupId = group.groupId; // ✅ 使用正确字段
console.log('加入小组请求 - groupId:', group.group_id, 'userId:', userId);

  const [showCreatePost, setShowCreatePost] = useState(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> {/* ✅ 使用 groupName */}
          <p style={{ color: '#BA929A' }}>{group.memberCount || 0}人加入了小组</p>

          <button
            onClick={() => handleJoinGroup(groupId, userId)}
            disabled={joinStatus[groupId] === '加入成功' || !userId}
          >
            
            {joinStatus[groupId] === '加入成功' ? '已加入' : userId ? '+加入小组' : '请登录'}
          </button>

          {userId && joinStatus[groupId] === '加入成功' && (
            <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;