<?php
use App\Models\Investment;
use App\Models\InvestmentPackage;
use App\Models\Wallet;
use App\Mail\AdminTransactionMail;
use App\Mail\SubscriptionCreatedMail;
use App\Services\DefaultCurrencyService;
use App\Services\Investment\SubscriptionService;
use App\Services\Sms\SmsAfrikasTalking;
use App\Traits\Vrm\Livewire\WithNotifications;
use Illuminate\Support\Facades\Mail;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Layout;
use Livewire\Component;
?>

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

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

        <div class="bg-primary/10 text-white rounded-xl p-4 border border-primary/20 space-y-2">
            <p class="text-sm text-white/80">{{ __('Available Balance') }}</p>
            <p class="text-md font-bold text-white">{{ $this->currencyCode }} {{ number_format($this->wallet->available_balance, 2) }}</p>
        </div>

        @if ($this->packages->isNotEmpty())
            <div class="space-y-3">
                <h2 class="text-base font-semibold text-foreground">{{ __('Available Packages') }}</h2>

                <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="{{ __('Search packages...') }}"
                        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 class="space-y-2">
                    @forelse ($this->filteredPackages as $pkg)
                        @php
                            $isSelected = (string) $pkg->id === $selectedPackageId;
                        @endphp
                        <button
                            type="button"
                            wire:key="package-{{ $pkg->id }}"
                            wire:click="choosePackage({{ $pkg->id }})"
                            class="w-full bg-card rounded-xl px-3 py-3 border text-left transition-colors {{ $isSelected ? 'border-primary ring-1 ring-primary/40' : 'border-border hover:border-primary/30' }}"
                        >
                            <div class="flex items-start justify-between gap-3">
                                <div class="flex items-start 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($pkg->photo))
                                            <img src="{{ asset($pkg->photo) }}" alt="" class="size-10 rounded-full object-cover" />
                                        @else
                                            <span class="text-xs font-bold text-foreground">{{ strtoupper(substr($pkg->name, 0, 2)) }}</span>
                                        @endif
                                    </div>
                                    <div class="min-w-0">
                                        <p class="text-foreground font-bold text-sm truncate">{{ $pkg->name }}</p>
                                        <p class="text-xs text-muted-foreground">
                                            {{ __('Min') }} {{ $this->currencyCode }} {{ number_format((float) $pkg->min_amount, 2) }}
                                            •
                                            {{ __('Max') }} {{ $this->currencyCode }} {{ number_format((float) $pkg->max_amount, 2) }}
                                        </p>
                                        <p class="text-xs text-muted-foreground">
                                            {{ $pkg->duration_hours }}{{ __('h') }} • {{ number_format((float) $pkg->interest_percent, 1) }}%
                                        </p>
                                    </div>
                                </div>

                                <div class="text-right shrink-0">
                                    <span class="inline-flex items-center rounded-full px-3 py-1 text-xs font-semibold transition-colors {{ $isSelected ? 'bg-primary text-primary-foreground' : 'bg-primary/10 text-primary' }}">
                                        <i class="fa-solid fa-hand-pointer mr-1 text-[10px]"></i>
                                        {{ __('Invest') }}
                                    </span>
                                    <p class="text-xs text-muted-foreground">{{ __('Tap to select') }}</p>
                                </div>
                            </div>
                        </button>
                    @empty
                        <p class="text-sm text-muted-foreground">{{ __('No packages found for your search.') }}</p>
                    @endforelse
                </div>

                @if ($this->selectedPackage)
                    @php
                        $pkg = $this->selectedPackage;
                    @endphp
                    <div class="bg-card rounded-xl p-4 border border-border space-y-3">
                        @if ($investStep === 'amount')
                            <h3 class="text-sm font-semibold text-foreground">{{ __('Invest in :name', ['name' => $pkg->name]) }}</h3>
                            <div>
                                <label class="required block text-xs font-medium text-muted-foreground mb-1">{{ __('Amount') }}</label>
                                <input type="number" step="0.01" min="{{ $pkg->min_amount }}" max="{{ $pkg->max_amount }}" wire:model.live.debounce.250ms="amount"
                                    class="w-full rounded-md border border-border bg-background px-3 py-2 text-sm" placeholder="{{ number_format((float) $pkg->min_amount, 2) }}" />
                                <p class="text-xs text-muted-foreground mt-1">{{ __('Min :min – Max :max', ['min' => number_format((float) $pkg->min_amount, 2), 'max' => number_format((float) $pkg->max_amount, 2)]) }} {{ $this->currencyCode }}</p>
                                <span class="text-destructive text-xs">{{ $errors->first('amount') }}</span>
                            </div>

                            <div class="rounded-lg border border-border bg-background px-3 py-2 text-sm text-muted-foreground">
                                <p>{{ __('Duration') }}: <span class="font-semibold text-foreground">{{ $pkg->duration_hours }} {{ __('hours') }}</span></p>
                                <p>{{ __('Expected Return') }}: <span class="font-semibold text-foreground">{{ $this->currencyCode }} {{ number_format($this->expectedReturnPreview, 2) }}</span></p>
                            </div>

                            <button type="button" wire:click="goToInvestConfirmation"
                                class="w-full rounded-md bg-primary px-4 py-2 text-sm font-semibold text-primary-foreground">
                                {{ __('Continue') }}
                            </button>
                        @elseif ($investStep === 'confirm')
                            <div class="rounded-2xl border border-border bg-background p-4 space-y-4">
                                <div class="flex justify-center">
                                    <div class="size-16 rounded-full bg-green-600 text-white flex items-center justify-center">
                                        <i class="fa-solid fa-chart-line text-xl"></i>
                                    </div>
                                </div>
                                <p class="text-center text-lg font-black text-foreground uppercase">{{ __('Invest to :name', ['name' => config('app.name')]) }}</p>
                                <div class="text-center">
                                    <p class="text-xl font-black text-foreground">{{ __('Amount') }}: {{ number_format((float) $amount, 2) }}</p>
                                    <p class="text-muted-foreground text-sm">{{ __('Transaction Fee: :currency :fee', ['currency' => $this->currencyCode, 'fee' => number_format(0, 2)]) }}</p>
                                </div>
                            </div>
                            <div class="flex gap-2">
                                <button type="button" wire:click="backToInvestAmount"
                                    class="flex-1 rounded-md border border-border bg-background px-4 py-2 text-sm font-semibold text-foreground">
                                    {{ __('Edit') }}
                                </button>
                                <button type="button" wire:click="confirmInvestment"
                                    class="flex-1 rounded-md bg-primary px-4 py-2 text-sm font-semibold text-primary-foreground">
                                    {{ __('Invest') }}
                                </button>
                            </div>
                        @else
                            <div class="rounded-2xl border border-border bg-background p-5 text-center space-y-5">
                                <div class="mx-auto size-16 rounded-full flex items-center justify-center {{ $investResultStatus === 'failed' ? 'bg-destructive/20 text-destructive' : 'bg-green-100 text-green-600' }}">
                                    <i class="fa-solid {{ $investResultStatus === 'failed' ? 'fa-xmark' : ($investResultStatus === 'pending' ? 'fa-hourglass-half' : 'fa-check') }} text-xl"></i>
                                </div>
                                <div class="space-y-1">
                                    <p class="text-lg font-black text-foreground uppercase">
                                        {{ $investResultPackageName !== '' ? __('Invest to :name', ['name' => $investResultPackageName]) : __('Investment') }}
                                    </p>
                                    @if ($investResultAmount > 0)
                                        <p class="text-xl font-black text-foreground">{{ __('Amount') }}: {{ number_format($investResultAmount, 2) }}</p>
                                    @endif
                                    <p class="text-sm text-muted-foreground">{{ __('Transaction Fee: :currency :fee', ['currency' => $this->currencyCode, 'fee' => number_format(0, 2)]) }}</p>
                                </div>
                                <p class="{{ $investResultStatus === 'failed' ? 'text-destructive' : 'text-green-600' }} text-lg font-medium">
                                    {{ $investResultMessage !== '' ? $investResultMessage : __('Your request has been received. Kindly wait for confirmation.') }}
                                </p>
                                <button type="button" wire:click="finishInvestmentFlow"
                                    class="w-full rounded-md bg-primary px-4 py-2 text-sm font-semibold text-primary-foreground">
                                    {{ __('Done') }}
                                </button>
                            </div>
                        @endif
                    </div>
                @endif
            </div>
        @else
            <p class="text-sm text-muted-foreground">{{ __('No investment packages available at the moment.') }}</p>
        @endif

        <div class="space-y-2">
            <h3 class="text-sm font-semibold text-foreground">{{ __('Your Investments') }}</h3>
            @forelse ($this->investments as $investment)
                @php
                    $isMatured = $investment->status === 'active' && $investment->matures_at->isPast();
                    $statusClass = match (strtolower((string) $investment->status)) {
                        'active' => 'bg-emerald-900/20 text-emerald-600',
                        'claimed' => 'bg-secondary text-muted-foreground',
                        default => 'bg-secondary text-muted-foreground',
                    };
                @endphp
                <div class="bg-card rounded-xl p-3 border border-border space-y-2" wire:key="investment-{{ $investment->id }}">
                    <div class="flex items-start justify-between gap-3">
                        <div>
                            <p class="text-sm font-semibold text-foreground">
                                {{ $investment->package?->name ?? __('Investment') }}:
                                {{ $this->currencyCode }} {{ number_format((float) $investment->principal_amount, 2) }}
                                <span class="text-muted-foreground">→</span>
                                {{ $this->currencyCode }} {{ number_format((float) $investment->expected_return_amount, 2) }}
                            </p>
                            <p class="text-xs text-muted-foreground">
                                {{ __('Matures') }}: {{ $investment->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' : $statusClass }}">
                            {{ $isMatured ? __('Matured') : ucfirst($investment->status) }}
                        </span>
                    </div>

                </div>
            @empty
                <p class="text-sm text-muted-foreground">{{ __('No investments yet.') }}</p>
            @endforelse
        </div>
    </div>

</div>