import React, { useState } from 'react';
import axios from 'axios';
import Header from '../../components/Header';
import './PublishSeed.css';
import { useUser } from '../../context/UserContext';

const PublishSeed = () => {
  const [title, setTitle] = useState('');
  const [description, setDescription] = useState('');
  const [tags, setTags] = useState([]);
  const [category, setCategory] = useState('movie');
  const [file, setFile] = useState(null);
  const [imageUrl, setImageUrl] = useState('');
  const [message, setMessage] = useState('');
  const [isLoading, setIsLoading] = useState(false);

  const { user } = useUser(); // 从上下文中获取当前登录用户信息

  const handleTagsChange = (e) => {
    setTags(e.target.value.split(',').map(tag => tag.trim()));
  };

  const handleFileChange = (e) => {
    setFile(e.target.files[0]);
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setIsLoading(true);
    setMessage('');

    if (!user || !user.id) {
      setMessage('请先登录');
      setIsLoading(false);
      return;
    }

    if (!file || !file.name.endsWith('.torrent')) {
      setMessage('请上传一个 .torrent 文件');
      setIsLoading(false);
      return;
    }

    const formData = new FormData();
    formData.append('file', file); // 文件字段
    formData.append('title', title);
    formData.append('description', description);
    formData.append('category', category);
    formData.append('imageUrl', imageUrl);
    formData.append('tags', tags.join(',')); // 后端使用字符串或数组自行处理
    formData.append('uploader', user.id); // 添加上传者 ID（必须字段）

    try {
      const response = await axios.post('/seeds/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      });

      if (response.data.code === 0) {
        setMessage('种子上传成功');
      } else {
        setMessage(response.data.msg || '上传失败，请稍后再试');
      }
    } catch (error) {
      console.error(error);
      setMessage('上传失败，发生了错误');
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="publish-seed-container">
      <Header />
      <div className="pub-card">
        {message && <div className="message">{message}</div>}
        <form onSubmit={handleSubmit} encType="multipart/form-data">
          <div className="title-tag">
            <label>标题</label>
            <input
              type="text"
              value={title}
              onChange={(e) => setTitle(e.target.value)}
              required
            />
          </div>

          <div className="discription">
            <label>描述</label>
            <textarea
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              required
            />
          </div>

          <div className="title-tag">
            <label>标签 (逗号分隔)</label>
            <input
              type="text"
              value={tags.join(', ')}
              onChange={handleTagsChange}
              placeholder="例如：科幻, 动作"
              required
            />
          </div>

          <div className="pub-categoty">
            <label>分类</label>
            <select
              value={category}
              onChange={(e) => setCategory(e.target.value)}
              required
            >
              <option value="movie">电影</option>
              <option value="tv">电视剧</option>
              <option value="music">音乐</option>
            </select>
          </div>

          <div className="seed-file">
            <label>种子文件</label>
            <label className="seed-file-label">
              点击选择文件
              <input
                type="file"
                accept=".torrent"
                onChange={handleFileChange}
                style={{ display: 'none' }}
              />
            </label>
            {file && <div style={{ marginTop: '5px' }}>{file.name}</div>}
          </div>

          <div className="form-group">
            <label>封面图URL</label>
            <input
              type="url"
              value={imageUrl}
              onChange={(e) => setImageUrl(e.target.value)}
              placeholder="例如：http://example.com/images/cover.jpg"
              required
              style={{
                padding: '1%',
                width: '100%',
                borderRadius: '6px',
                border: '1px solid #e0c4a1',
                backgroundColor: '#fff5f5',
                color: '#5F4437',
                fontSize: '1rem',
                marginBottom: '2%',
              }}
            />
          </div>

          <div className="upload-button">
            <button type="submit" disabled={isLoading}>
              {isLoading ? '正在上传...' : '上传种子'}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
};

export default PublishSeed;
