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

const UserProfile = ({ currentUser }) => {
  const { uid } = useParams();
  const [userProfile, setUserProfile] = useState(null);
  const [posts, setPosts] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchUserData = async () => {
      if (!uid) return;
      try {
        const userData = await api(`/api/users/${uid}`);
        setUserProfile(userData);

        const userPosts = await api(`/api/posts/user/${uid}`);
        setPosts(userPosts);
      } catch (err) {
        console.error("Error fetching user data:", err);
      } finally {
        setLoading(false);
      }
    };
    fetchUserData();
  }, [uid]);

  const handleDeletePost = async (postId) => {
    try {
      await api(`/api/posts/${postId}`, { method: 'DELETE' });
      setPosts(prev => prev.filter(p => p.id !== postId));
    } catch (err) {
      console.error('Error deleting post:', err);
    }
  };

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

  if (!userProfile) {
    return <div className="error">Profil konnte nicht geladen werden.</div>;
  }

  return (
    <div className="profile-container">
      <div className="profile-header">
        <img
          src={userProfile.profil_bild || DEFAULT_PROFILE_IMAGE}
          alt="Profilbild"
          className="profile-picture"
          onError={(e) => {
            e.currentTarget.onerror = null;
            e.currentTarget.src = DEFAULT_PROFILE_IMAGE;
          }}
        />
        <div className="profile-info">
          <h2>{userProfile.username}</h2>
          <div className="profile-stats">
            <span>{posts.length} Posts</span>
            <span>{userProfile.following_count || 0} Friend</span>
          </div>
          <div className="profile-bio">
            <p>{userProfile.name} {userProfile.nachname}</p>
            <p>{userProfile.bio || ''}</p>
          </div>
        </div>
      </div>

      <div className="profile-posts">
        {posts.length === 0 ? (
          <div className="no-posts">No posts yet.</div>
        ) : (
          posts.map(post => (
            <div key={post.id} className="profile-post">
              <img
                src={post.bild || DEFAULT_POST_IMAGE}
                alt={post.title || `Post ${post.id}`}
                className="profile-post-image"
                onError={(e) => {
                  e.currentTarget.onerror = null;
                  e.currentTarget.src = DEFAULT_POST_IMAGE;
                }}
              />
              <div className="profile-post-overlay">
                <div className="profile-post-stats">
                  <span>❤️ {post.likes || 0}</span>
                  <span>💬 {post.kommentar?.length || 0}</span>
                </div>
                {currentUser && currentUser.id === parseInt(uid) && (
                  <button
                    className="delete-post"
                    onClick={() => handleDeletePost(post.id)}
                  >
                    🗑️ Löschen
                  </button>
                )}
              </div>
            </div>
          ))
        )}
      </div>
    </div>
  );
};

export default UserProfile;
