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

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

  const handleRetrieve = async () => {
    try {
      const response = await axios.get('http://localhost:1000/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();
  }, []);

  return (
    <AppLayout title="Profile" subtitle="Your account">
      <div className="mx-auto max-w-md">
        {!user ? (
          <p className="text-sm text-slate-500">{error || 'No profile data found. Try signing in again.'}</p>
        ) : (
          <>
            {error && <p className="alert-error mb-4">{error}</p>}
            <div className="card divide-y divide-slate-100">
              <div className="flex justify-between gap-4 px-5 py-3">
                <span className="text-sm text-slate-500">Name</span>
                <span className="text-sm text-slate-800">{user.name}</span>
              </div>
              <div className="flex justify-between gap-4 px-5 py-3">
                <span className="text-sm text-slate-500">Email</span>
                <span className="text-sm text-slate-800">{user.email}</span>
              </div>
              {user.id && (
                <div className="flex justify-between gap-4 px-5 py-3">
                  <span className="text-sm text-slate-500">User ID</span>
                  <span className="truncate font-mono text-xs text-slate-700">{user.id}</span>
                </div>
              )}
            </div>
          </>
        )}
      </div>
    </AppLayout>
  );
}

export default Profile;
