<?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\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() !!}

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

        @if (! $this->isMarketOpen)
            <div class="rounded-lg border border-red-300 bg-red-50 px-3 py-2 text-sm text-red-700 dark:border-red-700 dark:bg-red-900/20 dark:text-red-300">
                {{ __('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>
            @if (! $showWatchlist)
                <div class="flex gap-2 overflow-x-auto pb-2">
                    @foreach (['All', 'Gainers', 'Losers'] as $f)
                        <button
                            type="button"
                            wire:click="setFilter('{{ $f }}')"
                            class="px-4 py-1.5 rounded-full text-sm font-medium whitespace-nowrap border transition-colors {{ $activeFilter === $f ? 'bg-primary text-primary-foreground border-primary' : 'bg-card text-muted-foreground border-border hover:border-primary/50' }}"
                        >
                            {{ $f }}
                        </button>
                    @endforeach
                </div>
            @endif
        </div>

        <div class="space-y-2">
            @php
                $displayList = $showWatchlist ? $this->watchlistSecurities : $this->filteredSecurities;
            @endphp
            @forelse ($displayList as $security)
                @php
                    $change = $security->latestChangePercent();
                    $isWatched = in_array($security->id, $this->watchlistIds, true);
                    $isSelected = $selectedSecurityId === $security->id;
                @endphp
                <div
                    wire:key="trade-{{ $security->id }}"
                    wire:click="selectSecurity({{ $security->id }})"
                    class="w-full bg-card rounded-xl p-4 border space-y-3 text-left transition-colors cursor-pointer {{ $isSelected ? 'border-primary' : 'border-border hover:border-primary/30' }}"
                >
                    <div class="flex items-center gap-3">
                        <div class="w-10 h-10 bg-secondary rounded-full flex items-center justify-center shrink-0">
                            <span class="text-xs font-bold text-foreground">{{ substr($security->trading_name, 0, 2) }}</span>
                        </div>
                        <div class="flex-1 min-w-0">
                            <p class="text-foreground font-bold text-sm">{{ $security->trading_name }}</p>
                            <p class="text-muted-foreground text-xs truncate">{{ $security->name }}</p>
                        </div>
                        <button type="button" wire:click.stop="toggleSecurityWatchlist({{ $security->id }})" class="text-sm {{ $isWatched ? 'text-yellow-500' : 'text-muted-foreground' }}">
                            <i class="fa-solid fa-star"></i>
                        </button>
                    </div>

                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-foreground font-bold text-sm">{{ $security->currency_code }} {{ number_format((float) $security->current_amount, 2) }}</p>
                            <span class="text-xs font-medium {{ $change >= 0 ? 'text-gain' : 'text-loss' }}">
                                {{ $change >= 0 ? '+' : '' }}{{ number_format($change, 2) }}%
                            </span>
                        </div>

                        <span class="rounded-md px-3 py-1.5 text-xs font-semibold bg-secondary text-foreground">
                            {{ __('View') }}
                        </span>
                    </div>
                </div>
            @empty
                <p class="text-center text-sm text-muted-foreground py-6">{{ __('No securities available.') }}</p>
            @endforelse
        </div>

        @if ($this->selectedSecurity)
            @php
                $selected = $this->selectedSecurity;
                $holding = $this->selectedHolding;
                $buyAmount = (float) ($orderAmounts[$selected->id] ?? 0);
                $buyQtyPreview = $buyAmount > 0 ? (int) floor($buyAmount / (float) $selected->current_amount) : 0;
                $change = $selected->latestChangePercent();
            @endphp

            <div class="bg-card rounded-xl border border-primary/40 p-4 space-y-4" wire:key="selected-security-{{ $selected->id }}">
                <div class="flex items-start justify-between gap-3">
                    <div>
                        <p class="text-foreground text-base font-bold">{{ $selected->trading_name }} - {{ $selected->name }}</p>
                        <p class="text-sm text-muted-foreground">
                            {{ $selected->currency_code }} {{ number_format((float) $selected->current_amount, 2) }}
                            <span class="ml-2 {{ $change >= 0 ? 'text-gain' : 'text-loss' }}">{{ $change >= 0 ? '+' : '' }}{{ number_format($change, 2) }}%</span>
                        </p>
                    </div>
                    <span class="text-xs rounded-full px-2 py-1 bg-secondary text-muted-foreground">{{ __('Selected') }}</span>
                </div>

                <div class="grid grid-cols-2 gap-3 text-sm">
                    <div class="rounded-lg border border-border p-3">
                        <p class="text-xs text-muted-foreground">{{ __('Shares Owned') }}</p>
                        <p class="font-semibold text-foreground">{{ $holding['quantity'] }}</p>
                    </div>
                    <div class="rounded-lg border border-border p-3">
                        <p class="text-xs text-muted-foreground">{{ __('Available to Sell') }}</p>
                        <p class="font-semibold text-foreground">{{ $holding['available_quantity'] }}</p>
                    </div>
                    <div class="rounded-lg border border-border p-3">
                        <p class="text-xs text-muted-foreground">{{ __('Invested') }}</p>
                        <p class="font-semibold text-foreground">{{ $selected->currency_code }} {{ number_format($holding['total_invested'], 2) }}</p>
                    </div>
                    <div class="rounded-lg border border-border p-3">
                        <p class="text-xs text-muted-foreground">{{ __('Current Value') }}</p>
                        <p class="font-semibold text-foreground">{{ $selected->currency_code }} {{ number_format($holding['current_value'], 2) }}</p>
                    </div>
                </div>

                @if ($holding['quantity'] > 0)
                    <div class="rounded-lg border border-border bg-background px-3 py-2 text-sm">
                        <p class="text-muted-foreground">{{ __('Performance') }}</p>
                        <p class="font-semibold {{ $holding['gain_loss_percent'] >= 0 ? 'text-gain' : 'text-loss' }}">
                            {{ $holding['gain_loss_percent'] >= 0 ? '+' : '' }}{{ number_format($holding['gain_loss_percent'], 2) }}% ({{ $selected->currency_code }} {{ number_format($holding['gain_loss_amount'], 2) }})
                        </p>
                    </div>
                @else
                    <p class="text-sm text-muted-foreground">{{ __('You have not purchased this security yet.') }}</p>
                @endif

                <div class="space-y-3 rounded-lg border border-border p-3">
                    <p class="text-sm font-semibold text-foreground">{{ __('Buy Security') }}</p>
                    <div class="space-y-2">
                        <label class="block text-xs text-muted-foreground">{{ __('Amount to invest') }}</label>
                        <input type="number" min="0.01" step="0.01" wire:model="orderAmounts.{{ $selected->id }}" placeholder="0.00"
                            class="w-full rounded-md border border-border bg-background px-3 py-2 text-sm" />
                        <p class="text-xs text-muted-foreground">{{ __('Estimated shares') }}: <span class="font-semibold text-foreground">{{ max(0, $buyQtyPreview) }}</span></p>
                    </div>
                    <button type="button" wire:click="placeBuyOrder({{ $selected->id }})"
                        @disabled(! $this->isMarketOpen)
                        class="w-full rounded-md px-3 py-2 text-sm font-semibold {{ $this->isMarketOpen ? 'bg-primary text-primary-foreground' : 'cursor-not-allowed bg-gray-400 text-white' }}">
                        {{ __('Submit Buy Request') }}
                    </button>
                </div>

                <div class="space-y-3 rounded-lg border border-border p-3">
                    <p class="text-sm font-semibold text-foreground">{{ __('Sell Security') }}</p>
                    <div class="space-y-2">
                        <label class="block text-xs text-muted-foreground">{{ __('Shares to sell') }}</label>
                        <input type="number" min="1" step="1" wire:model="sellQuantities.{{ $selected->id }}" placeholder="0"
                            class="w-full rounded-md border border-border bg-background px-3 py-2 text-sm" />
                        <p class="text-xs text-muted-foreground">{{ __('Available shares') }}: <span class="font-semibold text-foreground">{{ $holding['available_quantity'] }}</span></p>
                    </div>
                    <button type="button" wire:click="placeSellOrder({{ $selected->id }})"
                        @disabled(! $this->isMarketOpen)
                        class="w-full rounded-md px-3 py-2 text-sm font-semibold {{ $this->isMarketOpen ? 'bg-destructive text-destructive-foreground' : 'cursor-not-allowed bg-gray-400 text-white' }}">
                        {{ __('Submit Sell Request') }}
                    </button>
                </div>
            </div>
        @endif
    </div>

    <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>
</div>