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 (
      <div className="page-content">
        <p className="text-muted">{error || 'No profile data found. Try signing in again.'}</p>
      </div>
    );
  }

  return (
    <div className="page-content max-w-lg">
      <h1 className="page-title">Profile</h1>
      <p className="page-subtitle">Your account details</p>

      {error && <p className="alert-error">{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-muted">Name</span>
          <span className="text-sm text-brand-900">{user.name}</span>
        </div>
        <div className="px-5 py-3.5 flex justify-between gap-4">
          <span className="text-sm text-muted">Email</span>
          <span className="text-sm 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-muted">User ID</span>
            <span className="text-sm text-brand-900 font-mono truncate">{user.id}</span>
          </div>
        )}
      </div>
    </div>
  );
}

export default Profile;
