import { useState, useEffect } from "react";

export default function AlpacaAccountInfo() {
  const [account, setAccount] = useState<{
    cash: number;
    buying_power: number;
    portfolio_value: number;
  } | null>(null);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const fetchAccount = async () => {
      try {
        const res = await fetch("/api/alpaca/account");
        const data = await res.json();
        if (!res.ok) {
          throw new Error(data.error || "API error");
        }
        setAccount(data);
      } catch (err) {
        const message = err instanceof Error ? err.message : "Failed to load account info.";
        setError(message);
      }
    };
    fetchAccount();
  }, []);

  if (error) return <p className="text-red-600 p-4 text-center">{error}</p>;
  if (!account) return <p className="text-gray-600 p-4 text-center">Loading account…</p>;

  return (
    <div className="bg-white rounded-xl shadow-lg p-6 border border-gray-200">
      <h2 className="text-xl font-bold text-gray-900 mb-4 text-center">Trading Account</h2>
      <div className="space-y-3">
        <div className="flex justify-between items-center py-2 border-b border-gray-100">
          <span className="text-gray-600 font-medium">Cash</span>
          <span className="text-lg font-bold text-green-600">
            ${account.cash.toLocaleString(undefined, { minimumFractionDigits: 2 })}
          </span>
        </div>
        <div className="flex justify-between items-center py-2 border-b border-gray-100">
          <span className="text-gray-600 font-medium">Buying Power</span>
          <span className="text-lg font-bold text-blue-600">
            ${account.buying_power.toLocaleString(undefined, { minimumFractionDigits: 2 })}
          </span>
        </div>
        <div className="flex justify-between items-center py-2">
          <span className="text-gray-600 font-medium">Portfolio Value</span>
          <span className="text-lg font-bold text-purple-600">
            ${account.portfolio_value.toLocaleString(undefined, { minimumFractionDigits: 2 })}
          </span>
        </div>
      </div>
    </div>
  );
}