import { useEffect, useState } from 'react';
import axios from 'axios';
import PageLayout from '../components/PageLayout';

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 (
      <PageLayout title="Profile">
        <p className="text-sm text-slate-400">{error || 'No profile data found. Try signing in again.'}</p>
      </PageLayout>
    );
  }

  return (
    <PageLayout title="Profile">
      {error && <p className="lms-alert-error">{error}</p>}

      <div className="lms-card divide-y divide-slate-700 p-0">
        <div className="flex justify-between gap-4 px-6 py-4">
          <span className="text-sm text-slate-400">Name</span>
          <span className="text-sm text-white">{user.name}</span>
        </div>
        <div className="flex justify-between gap-4 px-6 py-4">
          <span className="text-sm text-slate-400">Username</span>
          <span className="text-sm text-white">{user.username}</span>
        </div>
        <div className="flex justify-between gap-4 px-6 py-4">
          <span className="text-sm text-slate-400">Role</span>
          <span className="text-sm capitalize text-white">{user.role}</span>
        </div>
        {user.id && (
          <div className="flex justify-between gap-4 px-6 py-4">
            <span className="text-sm text-slate-400">User ID</span>
            <span className="truncate font-mono text-sm text-white">{user.id}</span>
          </div>
        )}
      </div>
    </PageLayout>
  );
}

export default Profile;
