<?php

use App\Models\Security;
use App\Models\SecurityOrder;
use App\Services\LiveStockService;
use App\Services\Trading\TradingSettingsService;
use App\Models\Wallet;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Layout;
use Livewire\Component;

return new #[Layout('layouts.trading')] class extends Component {
    #[Computed]
    public function wallet(): Wallet
    {
        return Wallet::query()->firstOrCreate(
            ['user_id' => auth()->id()],
            ['currency_code' => 'USD']
        );
    }

    #[Computed]
    public function securities(): array
    {
        return app(LiveStockService::class)->getSecuritiesForDisplay();
    }

    #[Computed]
    public function holdings(): array
    {
        return auth()->user()
            ->portfolioHoldings()
            ->with('security')
            ->get()
            ->map(function ($holding): array {
                $currentValue = (float) $holding->quantity * (float) $holding->security->current_amount;
                $gainLossPercent = (float) $holding->average_buy_price > 0
                    ? (((float) $holding->security->current_amount - (float) $holding->average_buy_price) / (float) $holding->average_buy_price) * 100
                    : 0;

                return [
                    'symbol' => $holding->security->trading_name,
                    'name' => $holding->security->name,
                    'current_value' => $currentValue,
                    'gain_loss_percent' => $gainLossPercent,
                ];
            })
            ->all();
    }

    #[Computed]
    public function portfolio(): array
    {
        $inTrade = collect($this->holdings)->sum('current_value');
        $wallet = $this->wallet;
        $invested = auth()->user()->portfolioHoldings()->sum('total_invested');
        $gainLoss = $invested > 0 ? (($inTrade - (float) $invested) / (float) $invested) * 100 : 0;

        return [
            'balance' => (float) $wallet->balance,
            'inTrade' => (float) $inTrade,
            'gainLoss' => (float) $gainLoss,
            'currency' => $wallet->currency_code,
        ];
    }

    #[Computed]
    public function watchlist(): array
    {
        return auth()->user()
            ->watchlistItems()
            ->with('security')
            ->latest()
            ->limit(5)
            ->get()
            ->map(fn ($item): array => [
                'id' => $item->security->id,
                'symbol' => $item->security->trading_name,
                'name' => $item->security->name,
                'price' => (float) $item->security->current_amount,
                'change' => $item->security->latestChangePercent(),
            ])
            ->all();
    }

    #[Computed]
    public function newestSecurity(): ?array
    {
        $security = Security::query()->latest()->first();

        if (! $security) {
            return null;
        }

        return [
            'name' => $security->name,
            'symbol' => $security->trading_name,
        ];
    }

    #[Computed]
    public function pendingOrdersCount(): int
    {
        return SecurityOrder::query()
            ->where('user_id', auth()->id())
            ->where('status', 'pending')
            ->count();
    }

    #[Computed]
    public function isMarketOpen(): bool
    {
        return app(TradingSettingsService::class)->isMarketOpen();
    }

    protected function view($data = [])
    {
        return app('view')->file('/Users/cybertruck/DevProjects/2026/FxZidii/storage/framework/views/livewire/views/563ab22a.blade.php', $data);
    }
}; 