<?php
use App\Models\PortfolioHolding;
use App\Models\Security;
use App\Models\SecurityOrder;
use App\Models\SecurityWatchlist;
use App\Models\Wallet;
use App\Models\WalletTransaction;
use App\Jobs\Vrm\SendMail;
use App\Mail\AdminTransactionMail;
use App\Mail\WalletTransactionMail;
use App\Services\DefaultCurrencyService;
use App\Services\Sms\SmsAfrikasTalking;
use App\Services\Trading\TradingSettingsService;
use App\Traits\Vrm\Livewire\WithNotifications;
use Illuminate\Support\Facades\DB;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Layout;
use Livewire\Component;
?>

<div>
    @include('partials.trading.topbar', ['title' => 'TRADE'])

    <div class="px-4 space-y-4">
        {!! $this->renderNotification() !!}

        @if ($tradeStep === 'browse')
            <div class="bg-card rounded-lg p-3 border border-border text-sm text-foreground">
                {{ __('Available Balance') }}: {{ $this->currencyCode }} {{ number_format($this->wallet->available_balance, 2) }}
            </div>

            @if (! $this->isMarketOpen)
                <div class="rounded-lg border border-destructive/50 bg-destructive/10 px-3 py-2 text-sm text-destructive">
                    {{ __('Market is closed for today.') }}
                </div>
            @endif

            <div class="relative">
                <i class="fa-solid fa-search absolute left-3 top-1/2 -translate-y-1/2 h-5 w-5 text-muted-foreground"></i>
                <input
                    type="text"
                    wire:model.live.debounce.300ms="search"
                    placeholder="{{ __('What are you looking for today?') }}"
                    class="w-full bg-card border border-border rounded-lg py-3 pl-11 pr-4 text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary"
                />
            </div>

            <div>
                <h2 class="text-foreground font-semibold mb-3">{{ $showWatchlist ? __('My Watchlist') : __('Available Securities') }}</h2>
            </div>

            <div class="space-y-2">
                @php
                    $displayList = $showWatchlist ? $this->watchlistSecurities : $this->filteredSecurities;
                @endphp
                @forelse ($displayList as $security)
                    @php
                        $securityId = (int) ($security['id'] ?? 0);
                        $symbol = (string) ($security['symbol'] ?? '');
                        $name = (string) ($security['name'] ?? '');
                        $change = (float) ($security['change'] ?? 0);
                        $price = (float) ($security['price'] ?? 0);
                        $initials = (string) ($security['initials'] ?? substr($symbol !== '' ? $symbol : 'ST', 0, 2));
                        $isTradable = $securityId > 0;
                        $isInvested = $isTradable && in_array($securityId, $this->investedSecurityIds, true);
                    @endphp
                    <div
                        wire:key="trade-{{ $securityId ?: $symbol }}"
                        @if ($isTradable) wire:click="startBuyFlow({{ $securityId }})" @endif
                        class="w-full bg-card rounded-xl px-3 py-3 border border-border {{ $isTradable ? 'cursor-pointer transition hover:border-primary/50' : '' }}"
                    >
                        <div class="flex items-center justify-between gap-3">
                            <div class="flex items-center gap-3 min-w-0">
                                <div class="w-10 h-10 bg-secondary rounded-full flex items-center justify-center shrink-0 overflow-hidden">
                                    @if (!empty($security['logo']))
                                        <img src="{{ asset($security['logo']) }}" alt="" class="size-10 rounded-full object-cover" />
                                    @else
                                        <span class="text-xs font-bold text-foreground">{{ strtoupper(substr($initials, 0, 2)) }}</span>
                                    @endif
                                </div>
                                <div class="min-w-0">
                                    <div class="flex items-center gap-2">
                                        <p class="text-foreground font-bold text-sm">{{ $symbol !== '' ? $symbol : strtoupper($initials) }}</p>
                                        @if ($isInvested)
                                            <span class="inline-flex items-center rounded-full bg-primary/15 px-2 py-0.5 text-[10px] font-semibold text-primary">
                                                {{ __('Invested') }}
                                            </span>
                                        @endif
                                    </div>
                                    <p class="text-muted-foreground text-xs truncate">{{ $name }}</p>
                                </div>
                            </div>
                            <div class="text-right shrink-0">
                                <p class="text-foreground font-bold text-sm">{{ $this->currencyCode }} {{ number_format($price, 2) }}</p>
                                <span class="text-xs font-medium {{ $change >= 0 ? 'text-gain' : 'text-loss' }}">
                                    {{ $change >= 0 ? '▲' : '▼' }}{{ number_format(abs($change), 2) }}%
                                </span>
                            </div>
                        </div>
                    </div>
                @empty
                    <p class="text-center text-sm text-muted-foreground py-6">{{ __('No securities available.') }}</p>
                @endforelse
            </div>
        @elseif ($tradeAction === 'buy' && $this->selectedSecurity)
            @if ($tradeStep === 'amount')
                <div class="bg-card rounded-xl border border-border p-4 space-y-4">
                    <p class="text-sm font-semibold text-foreground">{{ __('Buy :symbol', ['symbol' => $this->selectedSecurity->trading_name]) }}</p>
                    <p class="text-xs text-muted-foreground">{{ __('Price per share') }}: {{ $this->currencyCode }} {{ number_format($this->selectedSecurity->latestPrice(), 2) }}</p>
                    <div>
                        <label class="block text-xs font-medium text-muted-foreground mb-1">{{ __('Amount to Invest') }}</label>
                        <input type="number" min="0.01" step="0.01" wire:model.live.debounce.250ms="tradeAmount" class="w-full rounded-md border border-border bg-background px-3 py-2 text-sm text-foreground" />
                        <p class="mt-1 text-xs text-muted-foreground">{{ __('Estimated shares') }}: {{ $this->estimatedTradeShares() }}</p>
                    </div>
                    <div class="grid grid-cols-2 gap-2">
                        <button type="button" wire:click="finishTradeFlow" class="w-full rounded-md border border-border bg-background px-4 py-2 text-sm font-semibold text-foreground">{{ __('Back') }}</button>
                        <button type="button" wire:click="goToTradeConfirmation" class="w-full rounded-md bg-primary px-4 py-2 text-sm font-semibold text-primary-foreground">{{ __('Continue') }}</button>
                    </div>
                </div>
            @elseif ($tradeStep === 'confirm')
                <div class="bg-card rounded-xl border border-border p-4 space-y-4">
                    <p class="text-sm font-semibold text-foreground">{{ __('Confirm Buy Request') }}</p>
                    <div class="space-y-1 text-sm">
                        <p class="text-foreground font-semibold">{{ $this->selectedSecurity->trading_name }}</p>
                        <p class="text-muted-foreground">{{ __('Amount') }}: {{ $this->currencyCode }} {{ number_format((float) $tradeAmount, 2) }}</p>
                        <p class="text-muted-foreground">{{ __('Estimated shares') }}: {{ $this->estimatedTradeShares() }}</p>
                    </div>
                    <div class="grid grid-cols-2 gap-2">
                        <button type="button" wire:click="backToTradeAmount" class="w-full rounded-md border border-border bg-background px-4 py-2 text-sm font-semibold text-foreground">{{ __('Edit') }}</button>
                        <button type="button" wire:click="submitTradeRequest" class="w-full rounded-md bg-primary px-4 py-2 text-sm font-semibold text-primary-foreground">{{ __('Confirm') }}</button>
                    </div>
                </div>
            @elseif ($tradeStep === 'result')
                <div class="bg-card rounded-xl border border-border p-4 space-y-4 text-center">
                    <div class="mx-auto size-12 rounded-full bg-primary text-primary-foreground flex items-center justify-center">
                        <i class="fa-solid fa-check"></i>
                    </div>
                    <p class="text-sm font-semibold text-foreground">{{ __('Buy Request Submitted') }}</p>
                    <p class="text-sm text-muted-foreground">{{ __('The request will be completed.') }}</p>
                    <p class="text-xs text-muted-foreground">{{ $tradeResultSymbol }} • {{ __('Qty') }}: {{ $tradeResultQuantity }} • {{ $this->currencyCode }} {{ number_format($tradeResultTotalAmount, 2) }}</p>
                    <button type="button" wire:click="finishTradeFlow" class="w-full rounded-md bg-primary px-4 py-2 text-sm font-semibold text-primary-foreground">{{ __('Done') }}</button>
                </div>
            @endif
        @endif
    </div>

    @if ($tradeStep === 'browse')
        <div class="fixed bottom-24 right-4 z-40">
            <button
                type="button"
                wire:click="toggleWatchlist"
                class="flex items-center gap-2 bg-primary text-primary-foreground font-semibold py-3 px-5 rounded-full shadow-lg hover:opacity-90 transition-opacity"
            >
                <i class="fa-solid fa-star h-5 w-5"></i>
                {{ __('My Watchlist') }}
            </button>
        </div>
    @endif
</div>