import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import { api } from '../../api';
import { DEFAULT_PROFILE_IMAGE } from '../../imagePlaceholders';
import './Home.css';

const Home = ({ currentUser }) => {
  const [posts, setPosts] = useState([]);
  const [loading, setLoading] = useState(true);
  const [commentTexts, setCommentTexts] = useState({});
  const [commentInProgress, setCommentInProgress] = useState(false);
  const [likeInProgress, setLikeInProgress] = useState(null);
  const [commentVisible, setCommentVisible] = useState({});
  const [followingList, setFollowingList] = useState([]);

  useEffect(() => {
    const fetchFollowingList = async () => {
      if (!currentUser) return;
      try {
        const data = await api(`/api/users/${currentUser.id}/following`);
        // Store only IDs for quick lookup
        setFollowingList(data.map(u => u.id));
      } catch (err) {
        console.error("Fehler beim Laden der Freundesliste:", err);
      }
    };
    fetchFollowingList();
  }, [currentUser]);

  const fetchPosts = async () => {
    setLoading(true);
    try {
      const data = await api('/api/posts');
      setPosts(data);
    } catch (err) {
      console.error('Error fetching posts:', err);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchPosts();
  }, []);

  const handleFollowToggle = async (userIdToToggle) => {
    const alreadyFollowing = followingList.includes(userIdToToggle);
    try {
      await api(`/api/users/${userIdToToggle}/follow`, {
        method: alreadyFollowing ? 'DELETE' : 'POST',
      });
      setFollowingList(prev =>
        alreadyFollowing
          ? prev.filter(id => id !== userIdToToggle)
          : [...prev, userIdToToggle]
      );
    } catch (err) {
      console.error("Fehler beim (Ent)Folgen:", err);
    }
  };

  const handleLike = async (postId) => {
    if (!currentUser || likeInProgress === postId) return;
    const post = posts.find(p => p.id === postId);
    const alreadyLiked = post.liked_by.includes(currentUser.id);

    try {
      setLikeInProgress(postId);
      const updated = await api(`/api/posts/${postId}/like`, {
        method: alreadyLiked ? 'DELETE' : 'POST',
      });
      setPosts(prev => prev.map(p => p.id === postId ? updated : p));
    } catch (err) {
      console.error('Error updating like:', err);
    } finally {
      setLikeInProgress(null);
    }
  };

  const handleComment = async (postId) => {
    if (!currentUser || commentInProgress) return;
    const text = (commentTexts[postId] || '').trim();
    if (!text) return;

    try {
      setCommentInProgress(true);
      const newComment = await api(`/api/posts/${postId}/comments`, {
        method: 'POST',
        body: JSON.stringify({ text }),
      });
      setPosts(prev =>
        prev.map(p =>
          p.id === postId
            ? { ...p, kommentar: [...p.kommentar, newComment] }
            : p
        )
      );
      setCommentTexts(prev => ({ ...prev, [postId]: '' }));
    } catch (err) {
      console.error('Error adding comment:', err);
    } finally {
      setCommentInProgress(false);
    }
  };

  const handleCommentLike = async (postId, commentId) => {
    if (!currentUser) return;
    const post = posts.find(p => p.id === postId);
    const comment = post.kommentar.find(c => c.comment_id === commentId);
    const alreadyLiked = comment.liked_by?.includes(currentUser.id);

    try {
      const updated = await api(`/api/posts/${postId}/comments/${commentId}/like`, {
        method: alreadyLiked ? 'DELETE' : 'POST',
      });
      setPosts(prev =>
        prev.map(p =>
          p.id === postId
            ? { ...p, kommentar: p.kommentar.map(c => c.comment_id === commentId ? updated : c) }
            : p
        )
      );
    } catch (err) {
      console.error('Error liking comment:', err);
    }
  };

  const handleDeleteComment = async (postId, commentId) => {
    try {
      await api(`/api/posts/${postId}/comments/${commentId}`, { method: 'DELETE' });
      setPosts(prev =>
        prev.map(p =>
          p.id === postId
            ? { ...p, kommentar: p.kommentar.filter(c => c.comment_id !== commentId) }
            : p
        )
      );
    } catch (err) {
      console.error('Error deleting comment:', err);
    }
  };

  const toggleComments = (postId) => {
    setCommentVisible(prev => ({ ...prev, [postId]: !prev[postId] }));
  };

  if (loading) {
    return (
      <div className="loading">
        <div className="spinner"></div>
      </div>
    );
  }

  return (
       <div className="home-container"> 
      {posts.length === 0 ? (
        <div className="no-posts">Keine Posts gefunden.</div>
      ) : (
        posts.map((post) => (
          <div key={post.id} className="post-card">
            <div className="post-header">
              <div className="post-user-info">
                <img
                  src={post.user_profil_bild || DEFAULT_PROFILE_IMAGE}
                  alt={post.username}
                  className="profile-picture"
                  onError={(e) => {
                    e.currentTarget.onerror = null;
                    e.currentTarget.src = DEFAULT_PROFILE_IMAGE;
                  }}
                />
                <Link to={`/profile/${post.user_id}`} className="post-username">
                  {post.username}
                </Link>
              </div>

              {currentUser && post.user_id !== currentUser.id && (
                <button
                  className={`follow-toggle-btn ${followingList.includes(post.user_id) ? 'following' : ''}`}
                  onClick={() => handleFollowToggle(post.user_id)}
                >
                  {followingList.includes(post.user_id) ? 'Unfollow' : 'Follow'}
                </button>
              )}
            </div>
            

           {post.bild && (
  <div className="post-image-wrapper">
    <img
      src={post.bild}
      alt={post.title || 'Post image'}
      className="post-image"
      onError={(e) => { e.target.style.display = 'none'; }}
    />
  </div>
)}

            <div className="post-content">
              <h3 className="post-title">{post.title}</h3>
              <p className="post-description">{post.description}</p>
              <p className="post-ort">{post.ort}</p>
            </div>

            <div className="post-actions">
              <button
                className={`like-button ${post.liked_by.includes(currentUser.id) ? 'liked' : ''}`}
                onClick={() => handleLike(post.id)}
                disabled={likeInProgress === post.id}
              >
                {post.liked_by.includes(currentUser.id) ? '🤍' : '🤍'} {post.likes} Likes
              </button>

              <button className="comment-bubble" onClick={() => toggleComments(post.id)}>
                💬 {post.kommentar.length} Comments
              </button>
            </div>
 
            {commentVisible[post.id] && (
              <div className="post-comments-section">
                <h4>Comment</h4>
                {post.kommentar.length > 0 ? (
                  post.kommentar.map((comment) => (
                    <div key={comment.comment_id} className="comment">
                      <strong>{comment.username}:</strong> {comment.text}
                      <div className="comment-actions">
                        <button
                          className={`comment-like-button ${comment.liked_by?.includes(currentUser.id) ? 'liked' : ''}`}
                          onClick={() => handleCommentLike(post.id, comment.comment_id)}
                        >
                          {comment.liked_by?.includes(currentUser.id) ? '🤍' : '🤍'} {comment.likes}
                        </button>
                        {comment.user_id === currentUser.id && (
                          <button
                            className="delete-comment"
                            onClick={() => handleDeleteComment(post.id, comment.comment_id)}
                          >
                            🗑️
                          </button>
                        )}
                      </div>
                    </div>
                  ))
                ) : (
                  <p>Noch keine Kommentare.</p>
                )}
              </div>
            )}

            {currentUser && (
              <div className="post-comment-form">
                <input
                  type="text"
                  className="comment-input"
                  placeholder="Kommentar hinzufügen..."
                  value={commentTexts[post.id] || ''}
                  onChange={(e) =>
                    setCommentTexts(prev => ({ ...prev, [post.id]: e.target.value }))
                  }
                  onKeyDown={(e) => {
                    if (e.key === 'Enter' && !e.shiftKey) {
                      e.preventDefault();
                      handleComment(post.id);
                    }
                  }}
                />
                <button
                  className="comment-submit"
                  onClick={() => handleComment(post.id)}
                  disabled={!commentTexts[post.id]?.trim() || commentInProgress}
                >
                  Posten
                </button>
              </div>
            )}
          </div>
        ))
      )}
      {/* TODO: "Nach oben"-Button selbst implementieren.
          Tipp: fixed Button + `window.scrollTo({ top: 0, behavior: 'smooth' })`. */}
    </div>
    
  );
};

export default Home;


