import React, { useState, useEffect } from 'react';
import axios from 'axios';
import './FriendMoments.css';
import Header from '../../components/Header';
import { Edit } from '@icon-park/react';

const FriendMoments = () => {
  const [feeds, setFeeds] = useState([]);
  const [filteredFeeds, setFilteredFeeds] = useState([]);
  const [query, setQuery] = useState('');
  const [userId, setUserId] = useState(456); // 从状态管理或登录信息获取

  // Modal state & form fields
  const [showModal, setShowModal] = useState(false);
  const [title, setTitle] = useState('');
  const [content, setContent] = useState('');
  const [selectedImages, setSelectedImages] = useState([]);
  const [previewUrls, setPreviewUrls] = useState([]); // 新增：图片预览URLs

  // 拉取好友动态列表
  const fetchFeeds = async () => {
    try {
      // 修改为新的API路径
      const res = await axios.get(`/echo/dynamic/${userId}/getAllDynamics`);
      setFeeds(res.data.posts || []);
      setFilteredFeeds(res.data.posts || []);
    } catch (err) {
      console.error('获取动态列表失败：', err);
      alert('获取动态列表失败，请稍后重试');
    }
  };

  useEffect(() => {
    fetchFeeds();
  }, [userId]);

  // 搜索处理
  const handleSearch = () => {
    const q = query.trim().toLowerCase();
    if (!q) {
      setFilteredFeeds(feeds);
      return;
    }
    setFilteredFeeds(
      feeds.filter(f => 
        (f.title || '').toLowerCase().includes(q) || 
        (f.postContent || '').toLowerCase().includes(q)
      )
    );
  };

  const handleReset = () => {
    setQuery('');
    setFilteredFeeds(feeds);
  };

  // 对话框内：处理图片选择
  const handleImageChange = (e) => {
    const files = Array.from(e.target.files);
    if (!files.length) return;
    
    // 生成预览URLs
    const previewUrls = files.map(file => URL.createObjectURL(file));
    
    setSelectedImages(files);
    setPreviewUrls(previewUrls); // 更新预览URLs
  };

  // 对话框内：提交新动态
  const handleSubmit = async () => {
    if (!content.trim()) {
      alert('内容不能为空');
      return;
    }

    try {
      const formData = new FormData();
      formData.append('user_id', userId);
      formData.append('title', title.trim() || '');
      formData.append('content', content.trim());
      
      // 添加图片文件
      selectedImages.forEach((file, index) => {
        formData.append('image_url', file);
      });

      // 修改为新的API路径
      await axios.post(`/echo/dynamic/${userId}/createDynamic`, formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      });

      // 重置表单
      setTitle('');
      setContent('');
      setSelectedImages([]);
      setPreviewUrls([]); // 重置预览URLs
      setShowModal(false);
      fetchFeeds();
      alert('发布成功');
    } catch (err) {
      console.error('发布失败', err);
      alert('发布失败，请稍后重试');
    }
  };

  // 删除动态
  const handleDelete = async (dynamicId) => {
    if (!window.confirm('确定要删除这条动态吗？')) return;
    try {
      // 修改为新的API路径
      await axios.delete(`/echo/dynamic/me/deleteDynamic/${dynamicId}`);
      fetchFeeds();
      alert('删除成功');
    } catch (err) {
      console.error('删除失败', err);
      alert('删除失败，请稍后重试');
    }
  };

  // 点赞动态
  const handleLike = async (dynamicId) => {
    try {
      // 调用新的点赞API
      const res = await axios.post(`/echo/dynamic/like`, {
        userId,
        dynamicId
      });
      
      if (res.status === 200) {
        // 更新本地状态
        setFeeds(feeds.map(feed => {
          if (feed.postNo === dynamicId) {
            return {
              ...feed,
              postLikeNum: (feed.postLikeNum || 0) + 1,
              liked: true
            };
          }
          return feed;
        }));
      } else {
        alert(res.data.message || '点赞失败');
      }
    } catch (err) {
      console.error('点赞失败', err);
      alert('点赞失败，请稍后重试');
    }
  };

  // 取消点赞
  const handleUnlike = async (dynamicId) => {
    try {
      // 调用新的取消点赞API
      const res = await axios.delete(`/echo/dynamic/unlike`, {
        data: { userId, dynamicId }
      });
      
      if (res.status === 200) {
        // 更新本地状态
        setFeeds(feeds.map(feed => {
          if (feed.postNo === dynamicId) {
            return {
              ...feed,
              postLikeNum: Math.max(0, (feed.postLikeNum || 0) - 1),
              liked: false
            };
          }
          return feed;
        }));
      } else {
        alert(res.data.message || '取消点赞失败');
      }
    } catch (err) {
      console.error('取消点赞失败', err);
      alert('取消点赞失败，请稍后重试');
    }
  };

  return (
    <div className="friend-moments-container">
      <Header />
      <div className="fm-header">
        <button className="create-btn" onClick={() => setShowModal(true)}>
          <Edit theme="outline" size="18" style={{ marginRight: '6px' }} />
          创建动态
        </button>
        <div className="f-search-bar">
          <input
            className="search-input"
            type="text"
            value={query}
            onChange={e => setQuery(e.target.value)}
            placeholder="输入要搜索的动态"
          />
          <button className="search-btn" onClick={handleSearch}>搜索</button>
          <button className="search-btn" onClick={handleReset}>重置</button>
        </div>
      </div>

      <div className="feed-list">
        {filteredFeeds.map(feed => (
          <div className="feed-item" key={feed.postNo}>
            {feed.title && <h4>{feed.title}</h4>}
            <p>{feed.postContent}</p>

            {feed.imageUrl && feed.imageUrl.split(',').length > 0 && (
              <div className="feed-images">
                {feed.imageUrl.split(',').map((url, i) => (
                  <img key={i} src={url} alt={`动态图${i}`} />
                ))}
              </div>
            )}

            <div className="feed-footer">
              <span className="feed-date">
                {new Date(feed.postTime).toLocaleString()}
              </span>
              <div className="like-container">
                {feed.liked ? (
                  <button className="unlike-btn" onClick={() => handleUnlike(feed.postNo)}>
                    已点赞 ({feed.postLikeNum || 0})
                  </button>
                ) : (
                  <button className="like-btn" onClick={() => handleLike(feed.postNo)}>
                    点赞 ({feed.postLikeNum || 0})
                  </button>
                )}
              </div>
              {feed.user_id === userId && (
                <button className="delete-btn" onClick={() => handleDelete(feed.postNo)}>
                  删除
                </button>
              )}
            </div>
          </div>
        ))}
      </div>

      {/* Modal 对话框 */}
      {showModal && (
        <div className="modal-overlay" onClick={() => setShowModal(false)}>
          <div className="modal-dialog" onClick={e => e.stopPropagation()}>
            <h3>发布新动态</h3>
            <input
              type="text"
              placeholder="标题"
              value={title}
              onChange={e => setTitle(e.target.value)}
            />
            <textarea
              placeholder="写下你的内容..."
              value={content}
              onChange={e => setContent(e.target.value)}
            />
            <label className="file-label">
              选择图片
              <input
                type="file"
                accept="image/*"
                multiple
                onChange={handleImageChange}
                style={{ display: 'none' }}
              />
            </label>
            <div className="cf-preview">
              {previewUrls.map((url, i) => ( // 使用定义的previewUrls
                <img key={i} src={url} alt={`预览${i}`} />
              ))}
            </div>
            <div className="modal-actions">
              <button className="btn cancel" onClick={() => setShowModal(false)}>
                取消
              </button>
              <button className="btn submit" onClick={handleSubmit}>
                发布
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default FriendMoments;