import React, { useState, useEffect } from "react";
import { Card } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Line } from "react-chartjs-2";
import { Chart, LineController, LineElement, PointElement, LinearScale, Title,
CategoryScale } from 'chart.js';
Chart.register(LineController, LineElement, PointElement, LinearScale, Title,
CategoryScale);
const TradeMe = () => {
const [stock, setStock] = useState("AAPL");
const [price, setPrice] = useState(null);
const [watchlist, setWatchlist] = useState([]);
const [portfolio, setPortfolio] = useState([]);
const [transactions, setTransactions] = useState([]);
const [search, setSearch] = useState("");
const [chartData, setChartData] = useState({ labels: [], datasets: [] });
useEffect(() => {
fetchStockPrice(stock);
fetchStockHistory(stock);
}, [stock]);
const fetchStockPrice = async (symbol) => {
const response = await fetch(`https://api.example.com/stock/${symbol}`);
const data = await response.json();
setPrice(data.price);
};
const fetchStockHistory = async (symbol) => {
const response = await fetch(`https://api.example.com/stock/history/$
{symbol}`);
const data = await response.json();
setChartData({
labels: data.dates,
datasets: [{
label: `${symbol} Price`,
data: data.prices,
borderColor: "#3b82f6",
backgroundColor: "rgba(59, 130, 246, 0.5)",
}],
});
};
const handleBuy = () => {
const newStock = { symbol: stock, price: price, quantity: 1 };
setPortfolio([...portfolio, newStock]);
setTransactions([...transactions, { type: "Buy", symbol: stock, price }]);
};
const handleSell = () => {
setPortfolio(portfolio.filter(item => item.symbol !== stock));
setTransactions([...transactions, { type: "Sell", symbol: stock, price }]);
};
const calculateProfitLoss = () => {
let totalProfitLoss = 0;
portfolio.forEach(item => {
totalProfitLoss += (price - item.price) * item.quantity;
});
return totalProfitLoss.toFixed(2);
};
const addToWatchlist = () => {
if (!watchlist.includes(stock)) {
setWatchlist([...watchlist, stock]);
}
};
const handleSearch = (e) => {
setSearch(e.target.value.toUpperCase());
};
const updateStock = () => {
if (search) {
setStock(search);
setSearch("");
}
};
return (
<div className="flex flex-col items-center justify-center p-6">
<h1 className="text-2xl font-bold">TRADE ME Dashboard</h1>
<div className="mt-4 flex space-x-2">
<Input value={search} onChange={handleSearch} placeholder="Enter stock
symbol..." className="p-2 border rounded" />
<Button onClick={updateStock} className="bg-blue-500">Search</Button>
</div>
<Card className="p-4 mt-4">
<p className="text-lg">Stock: {stock}</p>
<p className="text-lg">Price: ${price || "Loading..."}</p>
<div className="flex space-x-4 mt-4">
<Button onClick={handleBuy} className="bg-green-500">Buy</Button>
<Button onClick={handleSell} className="bg-red-500">Sell</Button>
<Button onClick={addToWatchlist} className="bg-yellow-500">Add to
Watchlist</Button>
</div>
</Card>
<div className="mt-6 w-full max-w-md">
<h2 className="text-xl font-semibold">Watchlist</h2>
<ul className="mt-2">
{watchlist.map((item, index) => (
<li key={index} className="p-2 border-b">{item}</li>
))}
</ul>
</div>
<div className="mt-6 w-full max-w-md">
<h2 className="text-xl font-semibold">Portfolio</h2>
<ul className="mt-2">
{portfolio.length > 0 ? portfolio.map((item, index) => (
<li key={index} className="p-2 border-b">{item.symbol} - ${item.price}
(Qty: {item.quantity})</li>
)) : <p>No stocks in portfolio</p>}
</ul>
<p className="mt-4 text-lg font-semibold">Profit/Loss: $
{calculateProfitLoss()}</p>
</div>
<div className="mt-6 w-full max-w-md">
<h2 className="text-xl font-semibold">Transaction History</h2>
<ul className="mt-2">
{transactions.length > 0 ? transactions.map((tx, index) => (
<li key={index} className="p-2 border-b">{tx.type} {tx.symbol} at $
{tx.price}</li>
)) : <p>No transactions yet</p>}
</ul>
</div>
<div className="mt-6 w-full max-w-lg">
<h2 className="text-xl font-semibold">Stock Price Chart</h2>
<Line data={chartData} />
</div>
</div>
);
};
export default TradeMe;