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

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

  const handleRetrieve = async () => {
    try {
      const response = await axios.get('http://localhost:5001/api/auth/me', {
        headers: {
          Authorization: `Bearer ${localStorage.getItem('token')}`,
        },
      });
      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');
      }
      console.error('Server Error:', err.response?.data || err.message);
    }
  };

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

  if (!user) {
    return (
      <p className="text-sm text-slate-500">
        {error || 'No profile data found. Try signing in again.'}
      </p>
    );
  }

  return (
    <div className="max-w-md">
      <h1 className="text-xl font-semibold text-brand-900 mb-1">Profile</h1>
      <p className="text-sm text-slate-500 mb-6">Your account details.</p>

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

      <div className="card divide-y divide-slate-100">
        <div className="px-5 py-3.5 flex justify-between gap-4">
          <span className="text-sm text-slate-500">Name</span>
          <span className="text-sm font-medium text-brand-900">{user.name}</span>
        </div>
        <div className="px-5 py-3.5 flex justify-between gap-4">
          <span className="text-sm text-slate-500">Email</span>
          <span className="text-sm font-medium text-brand-900">{user.email}</span>
        </div>
        {user.id && (
          <div className="px-5 py-3.5 flex justify-between gap-4">
            <span className="text-sm text-slate-500">User ID</span>
            <span className="text-sm font-mono text-slate-600 truncate max-w-[200px]">{user.id}</span>
          </div>
        )}
      </div>
    </div>
  );
}

export default Profile;
