import { useLoaderData } from "react-router";
import TradingViewChart from "../components/TradingViewChart";
import Navbar from "../components/Navbar";

export const meta = () => [{ title: "Stock Detail - AITrader" }];

interface LoaderData {
  ticker: string;
  position: number | null;
  orders: any[];
}

export async function loader({ params }: { params: { ticker: string } }) {
  const ticker = params.ticker?.toUpperCase() || "";
  
  // Fetch position
  const posRes = await fetch(`${process.env.BASE_URL}/api/alpaca/positions`);
  const positions = posRes.ok ? await posRes.json() : [];
  const position = positions.find((p: any) => p.ticker === ticker)?.qty ?? null;

  // Fetch orders
  const ordRes = await fetch(`${process.env.BASE_URL}/api/alpaca/orders`);
  const ordersData = ordRes.ok ? await ordRes.json() : { orders: [] };
  const orders = ordersData.orders?.filter((o: any) => o.symbol === ticker) || [];

  return Response.json({ ticker, position, orders });
}

export default function StockDetail() {
  const { ticker, position, orders } = useLoaderData() as LoaderData;

  return (
    <div className="min-h-screen bg-gradient-to-br from-gray-50 to-blue-50">
      <Navbar />
      <div className="mx-auto max-w-7xl px-6 py-8">
        <h1 className="text-3xl font-bold text-gray-900 mb-6">{ticker} Detail</h1>

        <TradingViewChart ticker={ticker} />

        <div className="mt-6">
          <h2>Position</h2>
          <p>{position ? `Qty: ${position}` : "No position"}</p>
        </div>

        <div className="mt-6">
          <h2>Recent Orders</h2>
          {orders.length === 0 ? <p>No orders</p> : <pre>{JSON.stringify(orders, null, 2)}</pre>}
        </div>
      </div>
    </div>
  );
}