import { useEffect, useState } from 'react';
import axios from 'axios';
import { Link } from 'react-router-dom';

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

  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);
    } finally {
    //   setLoading(false);
    }
  };

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

//   if (loading) {
//     return <p className="text-slate-500">Loading profile...</p>;
//   }

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

  return (
    <div className="page-shell">
    <div className="page-container">
      <div className="mb-6">
        <Link to="/dashboard" className="btn-back">
          Back to dashboard
        </Link>
      </div>
      <h1 className="page-title">Profile</h1>

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

      <div className="form-card divide-y divide-slate-100 p-0 overflow-hidden">
        <div className="px-5 py-4 flex justify-between gap-4">
          <span className="text-sm font-medium text-slate-500">Name</span>
          <span className="text-sm text-slate-800">{user.name}</span>
        </div>
        <div className="px-5 py-4 flex justify-between gap-4">
          <span className="text-sm font-medium text-slate-500">Email</span>
          <span className="text-sm text-slate-800">{user.email}</span>
        </div>
        {user.id && (
          <div className="px-5 py-4 flex justify-between gap-4">
            <span className="text-sm font-medium text-slate-500">User ID</span>
            <span className="text-sm text-slate-800 font-mono truncate">
              {user.id}
            </span>
          </div>
        )}
      </div>
    </div>
    </div>
  );
}

export default Profile;
