from PySide6.QtWidgets import QWidget, QLabel, QVBoxLayout, QTableWidget, QTableWidgetItem, QHeaderView
from PySide6.QtCore import Qt

class PositionsPanel(QWidget):
    def __init__(self):
        super().__init__()
        self.init_ui()

    def init_ui(self):
        layout = QVBoxLayout(self)

        # Title
        title_label = QLabel("Positions")
        title_label.setAlignment(Qt.AlignCenter)
        title_label.setStyleSheet("font-size: 24px; font-weight: bold; margin-bottom: 20px;")
        layout.addWidget(title_label)

        self.positions_table = QTableWidget()
        self.positions_table.setColumnCount(6)
        self.positions_table.setHorizontalHeaderLabels(["Symbol", "Quantity", "Average Price", "Current Price", "Market Value", "Unrealized P&L"])
        self.positions_table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        layout.addWidget(self.positions_table)

        layout.addStretch(1) # Pushes content to the top
        self.setLayout(layout)

    def update_position(self, symbol, quantity, avg_price, current_price, market_value, unrealized_pnl):
        # Check if position already exists
        for row in range(self.positions_table.rowCount()):
            if self.positions_table.item(row, 0).text() == symbol:
                self.positions_table.setItem(row, 1, QTableWidgetItem(str(quantity)))
                self.positions_table.setItem(row, 2, QTableWidgetItem(str(avg_price)))
                self.positions_table.setItem(row, 3, QTableWidgetItem(str(current_price)))
                self.positions_table.setItem(row, 4, QTableWidgetItem(str(market_value)))
                self.positions_table.setItem(row, 5, QTableWidgetItem(str(unrealized_pnl)))
                return

        # Add new position if not found
        row_position = self.positions_table.rowCount()
        self.positions_table.insertRow(row_position)
        self.positions_table.setItem(row_position, 0, QTableWidgetItem(symbol))
        self.positions_table.setItem(row_position, 1, QTableWidgetItem(str(quantity)))
        self.positions_table.setItem(row_position, 2, QTableWidgetItem(str(avg_price)))
        self.positions_table.setItem(row_position, 3, QTableWidgetItem(str(current_price)))
        self.positions_table.setItem(row_position, 4, QTableWidgetItem(str(market_value)))
        self.positions_table.setItem(row_position, 5, QTableWidgetItem(str(unrealized_pnl)))