<?php

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

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

    #[Computed]
    public function securities(): array
    {
        return Security::query()
            ->where('is_active', true)
            ->with('latestLog')
            ->orderBy('trading_name')
            ->get()
            ->map(fn (Security $security): array => $this->mapSecurityForDisplay($security))
            ->values()
            ->all();
    }

    #[Computed]
    public function holdings(): array
    {
        return auth()
            ->user()
            ->portfolioHoldings()
            ->with('security')
            ->get()
            ->map(function ($holding): array {
                $latestPrice = (float) $holding->security->latestPrice();
                $currentValue = (float) $holding->quantity * $latestPrice;
                $gainLossPercent = (float) $holding->average_buy_price > 0 ? (($latestPrice - (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' => app(DefaultCurrencyService::class)->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->latestPrice(),
                    '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 pendingTransactionsCount(): int
    {
        $orders = SecurityOrder::query()
            ->where('user_id', auth()->id())
            ->where('status', 'pending')
            ->count();

        $walletRequests = WalletTransaction::query()
            ->where('user_id', auth()->id())
            ->where('status', 'pending')
            ->count();

        return $orders + $walletRequests;
    }

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

    #[Computed]
    public function defaultCurrencyCode(): string
    {
        return app(DefaultCurrencyService::class)->code();
    }

    private function mapSecurityForDisplay(Security $security): array
    {
        return [
            'id' => $security->id,
            'symbol' => strtoupper((string) $security->trading_name),
            'name' => (string) ($security->name ?: $security->trading_name),
            'price' => $security->latestPrice(),
            'change' => $security->latestChangePercent(),
            'logo' => $security->logo,
            'initials' => $this->buildInitials((string) $security->trading_name, (string) ($security->name ?: $security->trading_name)),
        ];
    }

    private function buildInitials(string $symbol, string $name): string
    {
        $lettersOnly = preg_replace('/[^A-Z]/', '', strtoupper($symbol)) ?? '';
        if ($lettersOnly !== '') {
            return substr($lettersOnly, 0, 2);
        }

        $nameParts = preg_split('/\s+/', trim($name)) ?: [];
        $initials = collect($nameParts)
            ->filter()
            ->take(2)
            ->map(fn (string $part): string => strtoupper(substr($part, 0, 1)))
            ->implode('');

        return $initials !== '' ? $initials : 'ST';
    }
}; ?>

<div>
    @include('partials.trading.topbar', ['title' => 'TRADE'])
    @include('partials.trading.marquee', [
        'securities' => $this->securities,
        'currencyCode' => $this->defaultCurrencyCode,
    ])

    <div class="space-y-4 px-4 py-4">
        <div class="{{ $this->isMarketOpen ? 'border border-primary/30 bg-primary/10' : 'border border-destructive/30 bg-destructive/10' }} flex items-center justify-between rounded-lg px-4 py-3">
            <div class="flex items-center gap-2">
                <i class="fa-solid fa-circle-info h-4 w-4 {{ $this->isMarketOpen ? 'text-primary' : 'text-destructive' }}"></i>
                <span class="text-sm font-medium {{ $this->isMarketOpen ? 'text-primary' : 'text-destructive' }}">
                    {{ $this->isMarketOpen ? __('Market is open') : __('Market is closed for today.') }}
                </span>
            </div>
        </div>

        <div class="rounded-xl border border-border bg-card p-5">
            <p class="mb-1 text-sm text-muted-foreground">{{ __('Your portfolio value') }}</p>
            <h2 class="mb-3 text-md font-bold text-foreground">{{ $this->portfolio['currency'] }} {{ number_format($this->portfolio['balance'], 2) }}</h2>
            <div class="hidden items-center justify-between border-t border-border pt-3">
                <span class="text-sm text-muted-foreground">{{ __('Value') }} : {{ $this->portfolio['currency'] }} {{ number_format($this->portfolio['balance'] + $this->portfolio['inTrade'], 2) }}</span>
                <span class="rounded-full px-4 py-1 text-sm font-semibold {{ $this->portfolio['gainLoss'] >= 0 ? 'bg-primary text-primary-foreground' : 'bg-destructive text-destructive-foreground' }}">
                    {{ $this->portfolio['gainLoss'] >= 0 ? '+' : '' }}{{ number_format($this->portfolio['gainLoss'], 2) }}%
                </span>
            </div>
        </div>

        <div class="rounded-xl border border-border bg-card p-5">
            <div class="mb-3 flex items-center gap-2">
                <i class="fa-solid fa-clock h-4 w-4 text-muted-foreground"></i>
                <h3 class="text-sm font-semibold text-foreground">{{ __('Pending / unapproved transactions') }}</h3>
            </div>
            <div class="rounded-lg bg-destructive/10 p-4 text-center">
                @if ($this->pendingTransactionsCount > 0)
                    <p class="mb-3 text-sm text-foreground">
                        {{ __('You have :count pending transaction(s) awaiting admin approval.', ['count' => $this->pendingTransactionsCount]) }}
                    </p>
                @else
                    <p class="mb-3 text-sm text-foreground">{{ __('You have no pending transactions.') }}</p>
                @endif
                <a href="{{ route('member.account') }}" wire:navigate class="inline-block rounded-lg bg-primary px-6 py-2.5 text-sm font-semibold text-primary-foreground">{{ __('View account') }}</a>
            </div>
        </div>

        <div class="rounded-xl border border-border bg-card p-4">
            <div class="mb-3 flex items-center gap-2">
                <i class="fa-solid fa-star h-4 w-4 text-primary"></i>
                <h3 class="text-sm font-semibold text-foreground">{{ __('Your Watchlist') }}</h3>
            </div>
            @if (count($this->watchlist) === 0)
                <p class="py-4 text-center text-sm text-muted-foreground">{{ __('Your watchlist is empty') }}</p>
            @else
                <div class="space-y-3">
                    @foreach ($this->watchlist as $s)
                        <div class="flex items-center justify-between py-2" wire:key="watch-{{ $s['id'] }}">
                            <div>
                                <p class="text-sm font-semibold text-foreground">{{ $s['symbol'] }}</p>
                                <p class="text-xs text-muted-foreground">{{ $s['name'] }}</p>
                            </div>
                            <div class="text-right">
                                <p class="text-sm font-semibold text-foreground">{{ number_format($s['price'], 2) }}</p>
                                <p class="text-xs {{ $s['change'] >= 0 ? 'text-gain' : 'text-loss' }}">{{ $s['change'] >= 0 ? '▲' : '▼' }}{{ number_format(abs($s['change']), 2) }}%</p>
                            </div>
                        </div>
                    @endforeach
                </div>
            @endif
        </div>

        <div class="fixed bottom-24 right-4 z-40 max-w-lg">
            <a href="{{ route('member.trade-now') }}" wire:navigate class="flex items-center gap-2 rounded-full bg-primary px-6 py-3 font-semibold text-primary-foreground shadow-lg transition-opacity hover:opacity-90">
                <i class="fa-solid fa-cart-shopping h-5 w-5"></i>
                {{ __('Buy Stocks') }}
            </a>
        </div>
    </div>
</div>
