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

const CreatePostForm = ({ groupId, onClose }) => {
  const { userId, handleCreatePost } = useGroupStore();
  const [title, setTitle] = useState('');
  const [content, setContent] = useState('');
  const [images, setImages] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);
    setError('');

    try {
      const success = await handleCreatePost(groupId, userId, content, title, images);
      
      if (success) {
        alert('帖子发布成功');
        onClose();
      } else {
        setError('帖子发布失败');
      }
    } catch (error) {
      setError(error.message || '帖子发布失败');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="create-post-form">
      <h4>发布新帖子</h4>
      <input
        type="text"
        placeholder="帖子标题"
        value={title}
        onChange={(e) => setTitle(e.target.value)}
        required
      />
      <textarea
        placeholder="帖子内容"
        value={content}
        onChange={(e) => setContent(e.target.value)}
        required
      />
      <input
        type="file"
        multiple
        onChange={(e) => setImages(e.target.files)}
      />
      
      {error && <p className="error">{error}</p>}
      
      <div className="button-group">
        <button onClick={handleSubmit} disabled={loading}>
          {loading ? '发布中...' : '发布'}
        </button>
        <button onClick={onClose} disabled={loading}>
          取消
        </button>
      </div>
    </div>
  );
};

export default CreatePostForm;