<?php
use App\Models\Investment;
use App\Models\SecurityOrder;
use App\Models\Wallet;
use App\Models\WalletTransaction;
use App\Mail\AdminTransactionMail;
use App\Mail\InvestmentClaimedMail;
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 Illuminate\Support\Facades\Mail;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Layout;
use Livewire\Component;
?>

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

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

        <div class="flex border-b border-border mb-4">
            <button
                type="button"
                wire:click="setTab('portfolio')"
                class="flex-1 pb-3 text-sm font-semibold transition-colors {{ $activeTab === 'portfolio' ? 'text-foreground border-b-2 border-primary' : 'text-muted-foreground' }}"
            >
                {{ __('Portfolio') }}
            </button>
            <button
                type="button"
                wire:click="setTab('investments')"
                class="flex-1 pb-3 text-sm font-semibold transition-colors {{ $activeTab === 'investments' ? 'text-foreground border-b-2 border-primary' : 'text-muted-foreground' }}"
            >
                {{ __('Investments') }}
            </button>
            <button
                type="button"
                wire:click="setTab('performance')"
                class="flex-1 pb-3 text-sm font-semibold transition-colors {{ $activeTab === 'performance' ? 'text-foreground border-b-2 border-primary' : 'text-muted-foreground' }}"
            >
                {{ __('Performance') }}
            </button>
        </div>

        @if ($activeTab === 'portfolio')
            <div class="space-y-4">
                <div class="bg-card rounded-xl p-5 border border-border">
                    <p class="text-muted-foreground text-sm mb-1">{{ __('Your portfolio value') }}</p>
                    <h2 class="text-md font-bold text-foreground mb-3">{{ $this->portfolio['currency'] }} {{ number_format($this->portfolio['balance'], 2) }}</h2>
                    <div class="border-t border-border pt-3 flex items-center justify-between">
                        <span class="text-muted-foreground text-sm">{{ __('Value') }} : {{ $this->portfolio['currency'] }} {{ number_format($this->portfolio['balance'] + $this->portfolio['inTrade'], 2) }}</span>
                        <span class="text-sm font-semibold px-4 py-1 rounded-full {{ $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>

                @php
                    $activeSellHolding = $this->selectedSellHolding();
                @endphp
                @if ($sellStep === 'list')
                    <div class="bg-card rounded-xl border border-border overflow-hidden">
                        @forelse ($this->visibleHoldings as $holding)
                            <div class="px-4 py-4 border-t border-border space-y-3 first:border-t-0" wire:key="holding-{{ $holding['id'] }}">
                                <div class="flex items-start justify-between gap-3">
                                    <div>
                                        <p class="text-foreground font-semibold text-sm">{{ $holding['symbol'] }}</p>
                                        <p class="text-muted-foreground text-xs">{{ $holding['name'] }}</p>
                                        <p class="text-muted-foreground text-xs mt-0.5">{{ __('First invested') }}: {{ $holding['firstInvestedAt'] }}</p>
                                    </div>
                                    <div class="text-right">
                                        <p class="text-foreground text-sm font-semibold">{{ $this->portfolio['currency'] }} {{ number_format($holding['value'], 2) }}</p>
                                        <p class="text-xs text-muted-foreground">{{ __('Current Value') }}</p>
                                    </div>
                                </div>
                                <div class="grid grid-cols-2 gap-2 text-xs">
                                    <div>
                                        <p class="text-muted-foreground">{{ __('Performance') }}</p>
                                        <p class="font-semibold {{ $holding['performancePercent'] >= 0 ? 'text-gain' : 'text-loss' }}">
                                            {{ $holding['performancePercent'] >= 0 ? '+' : '' }}{{ number_format($holding['performancePercent'], 2) }}%
                                        </p>
                                    </div>
                                    <div class="text-right">
                                        <p class="text-muted-foreground">{{ __('Available to Sell') }}</p>
                                        <p class="font-semibold text-foreground">{{ $holding['available_quantity'] }}</p>
                                    </div>
                                </div>
                                <p class="text-xs text-muted-foreground">
                                    {{ __('Since Invested') }}:
                                    <span class="{{ $holding['performanceAmount'] >= 0 ? 'text-gain' : 'text-loss' }}">
                                        {{ $holding['performanceAmount'] >= 0 ? '+' : '' }}{{ $this->portfolio['currency'] }} {{ number_format(abs($holding['performanceAmount']), 2) }}
                                    </span>
                                </p>
                                @if ($holding['available_quantity'] > 0)
                                    <button
                                        type="button"
                                        wire:click="startSellFlow({{ $holding['id'] }})"
                                        class="w-full rounded-md bg-primary px-3 py-2 text-sm font-semibold text-primary-foreground"
                                    >
                                        {{ __('Sell') }}
                                    </button>
                                @endif
                            </div>
                        @empty
                            <div class="px-4 py-8 text-center text-sm text-muted-foreground">{{ __('No holdings yet.') }}</div>
                        @endforelse
                        @if ($this->hasMoreHoldings)
                            <div class="px-4 py-4 border-t border-border">
                                <button
                                    type="button"
                                    wire:click="showMoreHoldings"
                                    class="w-full rounded-md border border-border bg-background px-3 py-2 text-sm font-semibold text-foreground"
                                >
                                    {{ __('Show More') }}
                                </button>
                            </div>
                        @endif
                    </div>
                @endif

                @if ($sellStep === 'details' && $activeSellHolding)
                    @php
                        $sellHolding = $activeSellHolding;
                    @endphp
                    <div class="bg-card rounded-xl border border-border p-4 space-y-4">
                        <p class="text-sm font-semibold text-foreground">{{ __('Sell :symbol Shares', ['symbol' => $sellHolding['symbol']]) }}</p>
                        <div class="text-xs space-y-1">
                            <p class="text-muted-foreground">{{ $sellHolding['name'] }}</p>
                            <p class="text-muted-foreground">{{ __('Available shares') }}: {{ $sellHolding['available_quantity'] }}</p>
                            <p class="text-muted-foreground">{{ __('Current price') }}: Ksh {{ number_format((float) $sellHolding['price'], 2) }}</p>
                        </div>
                        <div>
                            <label class="block text-xs font-medium text-muted-foreground mb-1">{{ __('Shares to Sell') }}</label>
                            <input
                                type="number"
                                min="{{ max(1, (int) ($this->sellLimits['min_per_request'] ?? 1)) }}"
                                max="{{ max(1, $this->sellMaxAllowedForHolding((int) $sellHolding['id'])) }}"
                                step="1"
                                wire:model.live.debounce.250ms="sellShares"
                                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">
                                {{ __('Min :min • Max :max', ['min' => (int) ($this->sellLimits['min_per_request'] ?? 1), 'max' => (int) ($this->sellLimits['max_per_request'] ?? 0) > 0 ? number_format((int) $this->sellLimits['max_per_request']) : __('No limit')]) }}
                            </p>
                            <p class="text-xs text-muted-foreground">
                                {{ __('Daily remaining shares') }}:
                                {{ (int) ($this->sellLimits['max_per_day'] ?? 0) > 0 ? number_format($this->sellRemainingDailyShares) : __('No limit') }}
                            </p>
                        </div>
                        <div>
                            <label class="block text-xs font-medium text-muted-foreground mb-1">{{ __('Estimated Amount (Ksh)') }}</label>
                            <input
                                type="text"
                                readonly
                                value="Ksh {{ number_format($this->sellPreviewAmount(), 2) }}"
                                class="w-full rounded-md border border-border bg-muted/30 px-3 py-2 text-sm font-semibold text-foreground cursor-not-allowed"
                            />
                        </div>
                        <div class="grid grid-cols-2 gap-2">
                            <button type="button" wire:click="resetSellFlow" 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="goToSellConfirmation" class="w-full rounded-md bg-primary px-4 py-2 text-sm font-semibold text-primary-foreground">{{ __('Continue') }}</button>
                        </div>
                    </div>
                @endif

                @if ($sellStep === 'confirm' && $activeSellHolding)
                    @php
                        $sellHolding = $activeSellHolding;
                    @endphp
                    <div class="bg-card rounded-xl border border-border p-4 space-y-4">
                        <p class="text-sm font-semibold text-foreground">{{ __('Confirm Sell Request') }}</p>
                        <div class="text-sm space-y-1">
                            <p class="text-foreground font-semibold">{{ $sellHolding['symbol'] }} - {{ $sellHolding['name'] }}</p>
                            <p class="text-muted-foreground">{{ __('Shares') }}: {{ (int) $sellShares }}</p>
                            <p class="text-muted-foreground">{{ __('Estimated payout') }}: Ksh {{ number_format($this->sellPreviewAmount(), 2) }}</p>
                        </div>
                        <div class="grid grid-cols-2 gap-2">
                            <button type="button" wire:click="backToSellDetails" 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="submitSellRequest" class="w-full rounded-md bg-primary px-4 py-2 text-sm font-semibold text-primary-foreground">{{ __('Confirm') }}</button>
                        </div>
                    </div>
                @endif

                @if ($sellStep === '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">{{ __('Sell Request Submitted') }}</p>
                        <p class="text-sm text-muted-foreground">{{ __('The request will be completed.') }}</p>
                        <p class="text-xs text-muted-foreground">{{ $sellSubmittedSymbol }} • {{ __('Qty') }}: {{ $sellSubmittedShares }} • Ksh {{ number_format($sellSubmittedAmount, 2) }}</p>
                        <button type="button" wire:click="resetSellFlow" class="w-full rounded-md bg-primary px-4 py-2 text-sm font-semibold text-primary-foreground">{{ __('Done') }}</button>
                    </div>
                @endif
            </div>
        @endif

        @if ($activeTab === 'investments')
            <div class="space-y-4">
                <p class="text-sm text-muted-foreground">{{ __('Your investment subscriptions and progress.') }}</p>
                @forelse ($this->subscriptionInvestments as $inv)
                    @php
                        $isMatured = $inv->matures_at->isPast();
                        $progressPercent = $inv->duration_hours ? min(100, (int) round($inv->progress_ratio * 100)) : 0;
                    @endphp
                    <div class="bg-card rounded-xl p-4 border border-border space-y-3" wire:key="inv-{{ $inv->id }}">
                        <div class="flex items-start justify-between gap-3">
                            <div>
                                <p class="text-foreground font-semibold text-sm">{{ $inv->package?->name ?? __('Investment') }}</p>
                                <p class="text-xs text-muted-foreground">{{ $this->portfolio['currency'] }} {{ number_format((float) $inv->principal_amount, 2) }} → {{ $this->portfolio['currency'] }} {{ number_format((float) $inv->expected_return_amount, 2) }}</p>
                                <p class="text-xs text-muted-foreground">{{ __('Matures') }}: {{ $inv->matures_at->format('Y-m-d H:i') }}</p>
                            </div>
                            <span class="text-xs px-2 py-0.5 rounded-full {{ $isMatured ? 'bg-primary/20 text-primary' : 'investment-status--active' }}">
                                {{ $isMatured ? __('Matured') : __('Active') }}
                            </span>
                        </div>
                        <div>
                            <div class="flex justify-between text-xs text-muted-foreground mb-1">
                                <span>{{ __('Accrued') }}: {{ $this->portfolio['currency'] }} {{ number_format($inv->accrued_amount, 2) }}</span>
                                <span class="font-semibold text-emerald-700">{{ $progressPercent }}%</span>
                            </div>
                            <div class="h-4 rounded-sm border border-emerald-600 bg-white overflow-hidden">
                                <div
                                    class="h-full transition-all bg-[repeating-linear-gradient(135deg,theme(colors.emerald.600)_0_8px,white_8px_16px)]"
                                    style="width: {{ $progressPercent }}%"
                                ></div>
                            </div>
                        </div>
                        @if ($isMatured)
                            <button type="button" wire:click="$js.confirmClaimReturn({{ $inv->id }})"
                                class="w-full rounded-md bg-primary px-3 py-2 text-sm font-semibold text-primary-foreground">
                                {{ __('Claim Return') }}
                            </button>
                        @endif
                    </div>
                @empty
                    <div class="px-4 py-8 text-center text-sm text-muted-foreground">{{ __('No investment subscriptions yet.') }}</div>
                @endforelse
            </div>
        @endif

        @if ($activeTab === 'performance')
            <div class="space-y-3">
                @forelse ($this->holdings as $holding)
                    @php
                        $barWidth = min(abs($holding['performancePercent']) * 2, 100);
                    @endphp
                    <div class="bg-card rounded-xl p-4 border border-border" wire:key="perf-{{ $holding['id'] }}">
                        <div class="flex items-center justify-between mb-2">
                            <div>
                                <p class="text-foreground font-semibold text-sm">{{ $holding['symbol'] }}</p>
                                <p class="text-muted-foreground text-xs">{{ $holding['name'] }}</p>
                            </div>
                            <div class="text-right">
                                <p class="text-foreground font-semibold text-sm">{{ $this->portfolio['currency'] }} {{ number_format($holding['value'], 2) }}</p>
                                <span class="text-xs font-medium {{ $holding['performancePercent'] >= 0 ? 'text-gain' : 'text-loss' }}">
                                    {{ $holding['performancePercent'] >= 0 ? '+' : '' }}{{ number_format($holding['performancePercent'], 2) }}%
                                </span>
                            </div>
                        </div>
                        <div class="bg-secondary rounded-full h-2 overflow-hidden">
                            <div class="h-full rounded-full {{ $holding['performancePercent'] >= 0 ? 'bg-gain' : 'bg-loss' }}" style="width: {{ $barWidth }}%"></div>
                        </div>
                        <p class="text-xs text-muted-foreground mt-2">{{ __('Since invested') }}: {{ $holding['performanceAmount'] >= 0 ? '+' : '' }}{{ $this->portfolio['currency'] }} {{ number_format(abs($holding['performanceAmount']), 2) }}</p>
                    </div>
                @empty
                    <div class="px-4 py-8 text-center text-sm text-muted-foreground">{{ __('No performance data yet.') }}</div>
                @endforelse
            </div>
        @endif
    </div>

    @script
        <script>
            $js('confirmClaimReturn', async (investmentId) => {
                const result = await Swal.fire({
                    title: 'Claim investment return?',
                    text: 'This will move the matured return into your wallet.',
                    icon: 'question',
                    showCancelButton: true,
                    confirmButtonText: 'Yes, claim now',
                });

                if (!result.isConfirmed) {
                    return;
                }

                await $wire.claimInvestment(investmentId);
            });
        </script>
    @endscript
</div>