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

  return (
    <div className="max-w-lg ml-100">
              <div className='mt-8 mb-6'>
                <Link to="/dashboard"
            type="button"
            className=" font-medium hover:text-white border border-slate-600 rounded-lg px-3 py-2 hover:bg-slate-800 transition-colors"
          >
            BACK
          </Link>
      </div>
      <h1 className="text-2xl font-bold text-slate-800 mb-6">Profile</h1>

      {error && (
        <p className="mb-4 text-sm text-red-600 bg-red-50 border border-red-200 rounded px-3 py-2">
          {error}
        </p>
      )}

      <div className="bg-white rounded-lg shadow-sm border border-slate-200 divide-y divide-slate-200">
        <div className="px-6 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-6 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-6 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>
  );
}

export default Profile;
