import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { useAuth } from './AuthContext';

const UserProfile: React.FC = () => {
  const { user, logout } = useAuth();
  const [orders, setOrders] = useState<any[]>([]);

  useEffect(() => {
    if (user) {
      axios.get(`http://127.0.0.1:8000/orders/?user=${user.id}`)
        .then(res => setOrders(res.data));
    }
  }, [user]);

  return (
    <div className="p-6 max-w-4xl mx-auto">
      <h2 className="text-3xl font-bold mb-6">User Profile</h2>
      {user ? (
        <div className="bg-white p-6 rounded-lg shadow-md mb-8">
          <p className="mb-2"><strong>Username:</strong> {user.username}</p>
          <button onClick={logout} className="mt-4 bg-red-600 text-white px-4 py-2 rounded hover:bg-red-700">Logout</button>
        </div>
      ) : (
        <p>Please log in to see your profile.</p>
      )}

      {user && (
        <div>
          <h3 className="text-2xl font-bold mb-4">Order History</h3>
          {orders.length > 0 ? (
            <div className="bg-white p-4 rounded shadow-md">
              <table className="w-full text-left">
                <thead>
                  <tr className="border-b">
                    <th className="py-2">ID</th>
                    <th className="py-2">Date</th>
                    <th className="py-2">Total</th>
                  </tr>
                </thead>
                <tbody>
                  {orders.map(o => (
                    <tr key={o.id} className="border-b">
                      <td className="py-2">{o.id}</td>
                      <td className="py-2">{new Date(o.created_at).toLocaleDateString()}</td>
                      <td className="py-2">${o.total_price}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          ) : <p>No orders found.</p>}
        </div>
      )}
    </div>
  );
};

export default UserProfile;