import instance from '@/utils/axios';
import React, { useCallback, useEffect, useState } from 'react';
import styles from './upload.module.css';
import {postTorrentUpload } from '@/api/torrent';
import { useLocation, useNavigate } from 'react-router-dom'; // 用于跳转
import { getTagsByMainTag } from '@/utils/common';
import { Checkbox, Row, Col } from 'antd'; // 使用 antd 的 Checkbox 组件
import { MainTag, MainPostTag } from '@/types/common';
import { Select } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import type { UploadProps } from 'antd';
import { Button, message, Upload as UploadArea } from 'antd';
import request from '@/utils/request';
import {useApi} from '@/hooks/request';


const CreatePost = () => {
  const location = useLocation();
  const [postTitle, setPostTitle] = useState('');
  const [postContent, setPostContent] = useState('');
  const [isChecked, setIsChecked] = useState(false);
  const {type} = location.state || {type: ''}; // 获取路由传递的参数
  const [tagIds, setTagIds] = useState<number[]>([]);
  const [postType, setPostType] = useState<string>(type || ''); // 初始化 postType
  const navigate = useNavigate();
  const [tags, setTags] = useState<Map<string, number>>(new Map());
  const [torrentId, setTorrentId] = useState<number>(0); // 用于存储上传的种子 ID
  const [messageApi, contextHolder] = message.useMessage();

  const {refresh} = useApi((payload)=> request.post('/post', payload), false)

  const props: UploadProps = {
    name: 'file',
    action: process.env.API_BASE_URL + postTorrentUpload, // 替换为实际的上传接口地址
    headers: {
      authorization: `Bearer ${localStorage.getItem('token')}`, // 使用本地存储的 token
    },
    onChange(info) {

      if (info.file.status === 'done') {
        const response = info.file.response;
        if(response && response.code !== 200) {
           messageApi.error(response.message || '上传失败');
          return;
        }
        else {
          console.log('上传成功:', response);
          messageApi.success('上传成功')
          console.log(response.data.torrentId);
          setTorrentId(response.data.torrentId); // 假设返回的数据中有 torrentId
        }
      } else if (info.file.status === 'error') {
        messageApi.error(`${info.file.name} 文件上传失败`);
      }
    },
    
  };


  const handleSubmit = async () => {
    console.log(torrentId)
    if (!postTitle.trim() || !postType || !postContent.trim()) {
      alert('请填写完整内容（资源名、类型、内容介绍）');
      return;
    }

    if (!isChecked) {
      alert('请先确认您已知晓以上内容');
      return;
    }

    const payload = {
      post: {
        postTitle,
        postContent,
        torrentId,
        postType:'resource'
      },
      tagIds: new Array(...tagIds, MainPostTag[postType as keyof typeof MainPostTag]), // 确保 tagIds 是一个数组
    };
    try{
      const res = await refresh(payload)
      messageApi.success('发布成功', 3).then(()=>{
        navigate('/')
      });
      ; // 发布成功后跳转到首页
    } catch (err){
       messageApi.error((err as Error).message || '发布失败，请稍后再试');
    }
    
  };

  useEffect(() => {
    setTags(getTagsByMainTag(type)); // 获取对应类型的标签
  },[]);

  const handlePostTypeChange = useCallback((value:string) => {
    setPostType(value);
    setTags(getTagsByMainTag(value)); // 更新 tags
    setTagIds([]); // 清空已选的标签 ID
  }, [postType, setTags, setTagIds]);


  return (
    <div className={styles.container}>
      {contextHolder}
      <div className={styles.formGroup}>
        <label>资源名：</label>
        <input
          type="text"
          value={postTitle}
          placeholder="请输入文本"
          onChange={(e) => setPostTitle(e.target.value)}
          className={styles.input}
        />
      </div>
  
      <div className={styles.formGroup}>
        <label>种子类型：</label>
        <Select
          value={postType}
          onChange={handlePostTypeChange}

          options ={ MainTag.map((item) => ({
            label: item,
            value: item
          }))} />
      </div>

      <div className={styles.formGroup}>
        <label>类型选择：</label>
        <Checkbox.Group
          value={tagIds}
          onChange={(checkedValues) => setTagIds(checkedValues as number[])}
        >
          <Row gutter={[12, 12]}>
            {[...tags.entries()].map(([name, id]) => (
              <Col key={id} xs={12} sm={8} md={6} lg={4}>
                <Checkbox value={id}>{name}</Checkbox>
              </Col>
            ))}
          </Row>
        </Checkbox.Group>
      </div>

      {/* 暂时移除上传文件表单 */}
      <div className={styles.formGroup}>
        <label>上传资源：</label>
        <UploadArea {...props}>
          <Button icon={<UploadOutlined />}>Upload</Button>
        </UploadArea>
      </div>

      <div className={styles.formGroup}>
        <label>内容介绍：</label>
        <textarea
          placeholder="请输入内容介绍"
          value={postContent}
          onChange={(e) => setPostContent(e.target.value)}
          maxLength={200}
          className={styles.textarea}
        />
        <div className={styles.charCount}>{postContent.length}/200</div>
      </div>

      <div className={styles.requirement}>【发布内容要求】</div>

      <div className={styles.checkbox}>
        <input
          type="checkbox"
          checked={isChecked}
          onChange={() => setIsChecked(!isChecked)}
        />
        <span>我已知晓以上内容</span>
      </div>

      <button onClick={handleSubmit} className={styles.submitBtn} disabled={!isChecked}>
        我已知晓
      </button>
    </div>
  );
};

export default CreatePost;
