import React, { useState, useEffect } from 'react';
import { api } from '../../api';
import { DEFAULT_POST_IMAGE, DEFAULT_PROFILE_IMAGE } from '../../imagePlaceholders';
import './Profile.css';

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

  const [isEditing, setIsEditing] = useState(false);
  const [editData, setEditData] = useState({
    username: '',
    vorname: '',
    nachname: '',
    profil_bild: ''
  });

  const [searchTerm, setSearchTerm] = useState('');
  const [searchResults, setSearchResults] = useState([]);
  const [friendsList, setFriendsList] = useState([]);
  const [friendUsers, setFriendUsers] = useState([]);

  useEffect(() => {
    const fetchUserData = async () => {
      if (!currentUser) return;
      try {
        const userData = await api('/api/users/me');
        setUserProfile(userData);

        const following = await api(`/api/users/${currentUser.id}/following`);
        setFriendsList(following.map(u => u.id));
        setFriendUsers(following);

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

  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);
    }
  };

  const handleEditClick = () => {
    setEditData({
      username: userProfile.username || '',
      vorname: userProfile.name || '',
      nachname: userProfile.nachname || '',
      profil_bild: userProfile.profil_bild || ''
    });
    setIsEditing(true);
  };

  const handleInputChange = (e) => {
    const { name, value } = e.target;
    setEditData(prev => ({ ...prev, [name]: value }));
  };

  const handleSaveChanges = async () => {
    try {
      const updated = await api(`/api/users/${currentUser.id}`, {
        method: 'PUT',
        body: JSON.stringify({
          username: editData.username,
          name: editData.vorname,
          nachname: editData.nachname,
          profil_bild: editData.profil_bild,
        }),
      });

      setUserProfile(updated);

      // Keep localStorage in sync so the navbar / App still shows the correct user
      const storedUser = JSON.parse(localStorage.getItem('user'));
      const updatedStored = { ...storedUser, username: updated.username, profil_bild: updated.profil_bild };
      localStorage.setItem('user', JSON.stringify(updatedStored));
      if (onUserUpdate) onUserUpdate(updatedStored);

      setIsEditing(false);
    } catch (err) {
      console.error("Fehler beim Speichern des Profils:", err);
    }
  };

  const handleFriendSearch = async () => {
    if (!searchTerm.trim()) return;
    try {
      const results = await api(`/api/users/search?q=${encodeURIComponent(searchTerm)}`);
      setSearchResults(results.filter(u => u.id !== currentUser.id));
    } catch (err) {
      console.error('Fehler bei der Freundsuche:', err);
    }
  };

  const handleAddFriend = async (userId) => {
    try {
      await api(`/api/users/${userId}/follow`, { method: 'POST' });
      setFriendsList(prev => [...prev, userId]);
    } catch (err) {
      console.error("Fehler beim Hinzufügen eines Freundes:", 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"
          id="profile-picture"
          onError={(e) => {
            e.currentTarget.onerror = null;
            e.currentTarget.src = DEFAULT_PROFILE_IMAGE;
          }}
        />
        <div id="profile-info">
          {/* TODO: Username sauber aus Auth-Context oder `/api/users/me` mappen,
              damit Profil + Navbar immer denselben Wert zeigen. */}
          <h2>{userProfile.username}</h2>
          <div id="profile-stats">
            <span>{posts.length} Posts</span>
            <span>{userProfile.following_count} Friends</span>
          </div>
          <div className="profile-bio">
            <p>{userProfile.name} {userProfile.nachname}</p>
            <p>{userProfile.bio || ''}</p>
          </div>
          <button id="profile-edit-button" onClick={handleEditClick}>
           Edit Profile
          </button>
        </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>
                <button className="delete-post" onClick={() => handleDeletePost(post.id)}>
                  🗑️ Löschen
                </button>
              </div>
            </div>
          ))
        )}
      </div>

      <div className="friend-section">
        <h3> Freunde suchen:</h3>
        <div className="friend-search">
          <input
            type="text"
            placeholder="Username suchen..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
          />
          <button onClick={handleFriendSearch}>Suchen ...</button>
        </div>

        <div className="friend-results">
          {searchResults.map((user) => (
            <div key={user.id} className="friend-result">
              <span>{user.username}</span>
              {!friendsList.includes(user.id) ? (
                <button onClick={() => handleAddFriend(user.id)}>Add</button>
              ) : (
                <span className="already-friend">Geadded</span>
              )}
            </div>
          ))}
        </div>
      </div>

      {isEditing && (
        <div className="modal-backdrop">
          <div className="modal">
            <h3>Edit Profile:</h3>

            <div className="form-group">
              <label>Username</label>
              <input type="text" name="username" value={editData.username} onChange={handleInputChange} />
            </div>

            <div className="form-group">
              <label>Vorname</label>
              <input type="text" name="vorname" value={editData.vorname} onChange={handleInputChange} />
            </div>

            <div className="form-group">
              <label>Name</label>
              <input type="text" name="nachname" value={editData.nachname} onChange={handleInputChange} />
            </div>

            <div className="form-group">
              <label>Bild (URL)</label>
              <input type="text" name="profil_bild" value={editData.profil_bild} onChange={handleInputChange} />
            </div>

            <div className="form-group">
              <label>Friends:</label>
              {friendUsers.length > 0 ? (
                <ul className="friend-list">
                  {friendUsers.map(friend => (
                    <li key={friend.id}>{friend.username}</li>
                  ))}
                </ul>
              ) : (
                <p>No friends found....</p>
              )}
            </div>

            <div className="modal-buttons">
              <button onClick={handleSaveChanges}>Speichern</button>
              <button onClick={() => setIsEditing(false)}>Abbrechen</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default Profile;
