import { useEffect, useState } from 'react';
import axios from 'axios';

function Profile() {
  const [user, setUser] = useState(null);
  const [error, setError] = useState('');

  useEffect(() => {
    axios
      .get('http://localhost:5001/api/auth/me', {
        headers: { Authorization: `Bearer ${localStorage.getItem('token')}` },
      })
      .then((response) => {
        setUser(response.data.user);
        localStorage.setItem('user', JSON.stringify(response.data.user));
      })
      .catch((err) => {
        const storedUser = localStorage.getItem('user');
        if (storedUser) {
          setUser(JSON.parse(storedUser));
        } else {
          setError(err.response?.data?.message || 'Failed to load profile');
        }
      });
  }, []);

  if (!user) {
    return <p className="text-gray-600">{error || 'No profile data found.'}</p>;
  }

  return (
    <div className="max-w-lg">
      <h1 className="mb-6 text-2xl font-bold">Profile</h1>

      {error && <p className="alert-error">{error}</p>}

      <div className="box space-y-3">
        <div className="flex justify-between border-b border-gray-200 pb-2">
          <span className="text-gray-600">Name</span>
          <span>{user.name}</span>
        </div>
        <div className="flex justify-between border-b border-gray-200 pb-2">
          <span className="text-gray-600">Email</span>
          <span>{user.email}</span>
        </div>
        {user.id && (
          <div className="flex justify-between">
            <span className="text-gray-600">User ID</span>
            <span className="text-sm">{user.id}</span>
          </div>
        )}
      </div>
    </div>
  );
}

export default Profile;
