<?php

use Livewire\Component;
use App\Models\User;
use App\Models\Account;
use App\Models\Transaction;
use Illuminate\Support\Facades\Cache;
use Livewire\Attributes\Layout;
use Livewire\Attributes\On;

new #[Layout('layouts::base')] class extends Component {
    public User $user;

    public ?Account $selectedAccount = null;
    public ?int $selectedAccountId = null;
    public $accounts;
    public string $currencySymbol = '$';

    public array $countries = [];
    public array $states = [];
    public array $currencies = [];
    public $latestTransactions = [];
    public int $profileVersion = 0;

    // Stats
    public array $stats = [
        'walletBalance' => 0,
        'totalDeposit' => 0,
        'totalWithdrawal' => 0,
        'totalLoan' => 0,
        'revenue' => 0,
        'expenses' => 0,
        'ticketsOpen' => 0,
        'ticketsClosed' => 0,
    ];

    public function mount(User $user)
    {
        $this->user = $user;
        $this->accounts = $user->profile?->accounts ?? collect();

        // Default to primary or first account
        $primary = $this->accounts->firstWhere('is_primary', true) ?? $this->accounts->first();
        $this->selectedAccount = $primary;
        $this->selectedAccountId = $primary?->id;

        $this->currencySymbol = \App\Support\Currency::symbol($user->profile?->currency ?? 'USD');
        $this->loadCurrencies();
        // Load initial stats
        $this->loadStats();
        $this->updateLatestTransactions();
    }

    public function updatedSelectedAccountId($accountId)
    {
        $this->selectedAccount = $this->accounts->firstWhere('id', $accountId) ?? null;
        $this->loadStats(); // always reload stats when account changes
        $this->updateLatestTransactions();
    }

    private function updateLatestTransactions()
    {
        $account = $this->selectedAccount;

        if (!$account) {
            $this->latestTransactions = [];
            return;
        }

        $query = Transaction::where('account_id', $account->id);

        $this->latestTransactions = $query->latest()->take(10)->get();
    }

    public function loadCurrencies()
    {
        $this->currencies = Cache::rememberForever('currencies_json', function () {
            return collect(json_decode(file_get_contents(resource_path('data/currencies.json')), true))
                ->sortBy('name')
                ->values()
                ->toArray();
        });
    }

    public function loadStats()
    {
        // Reset
        $this->stats = [
            'walletBalance' => 0,
            'totalDeposit' => 0,
            'totalWithdrawal' => 0,
            'totalLoan' => 0,
            'revenue' => 0,
            'expenses' => 0,
            'ticketsOpen' => 0,
            'ticketsClosed' => 0,
        ];

        if (!$this->selectedAccount) {
            return;
        }

        $account = $this->selectedAccount;

        $this->stats = [
            'walletBalance' => (float) ($account->available_balance ?? 0),
            'totalDeposit' => (float) ($account->deposits()->sum('amount') ?? 0),
            'totalWithdrawal' => (float) ($account->withdrawals()->sum('amount') ?? 0),
            'totalLoan' => (float) ($account->loans()->sum('amount') ?? 0),
            'revenue' => (float) ($account->transactions()->incoming()->sum('amount') ?? 0),
            'expenses' => (float) ($account->transactions()->outgoing()->sum('amount') ?? 0),
            'ticketsOpen' => $this->user->tickets()->open()->count() ?? 0,
            'ticketsClosed' => $this->user->tickets()->closed()->count() ?? 0,
        ];
    }

    // Helper method so children can trigger stats reload
    protected $listeners = [
        'updated' => 'refreshStats',
    ];

    public function refreshStats()
    {
        $this->loadStats();
    }

    #[On('profile-updated')]
    public function handleProfileUpdated($userId)
    {
        $this->user = User::with('profile.accounts')->find($userId);
        $this->selectedAccount = $this->accounts->firstWhere('id', $this->selectedAccountId);

        $this->currencySymbol = \App\Support\Currency::symbol($this->user->profile?->currency ?? 'USD');

        $this->accounts = $this->user->profile?->accounts ?? collect();

        $this->profileVersion++; // 🔥 forces child remount
        $this->loadStats();
        $this->updateLatestTransactions();
    }
};
?>

<x-slot:title>{{ config('app.name') }} || Manage User: {{ $user->name }}</x-slot:title>

<div class="py-4 space-y-5">

    <x-page-header title="{{ $this->user->name }} Information"
        subtitle="View detailed information about the user, including profile details, KYC status, and account activity."
        rightText="back to users" back-url="{{ route('admin.users.index') }}">
    </x-page-header>


    {{-- Account Selector --}}
    <x-select wire:model.live="selectedAccountId" label="Select Account" placeholder="Choose Account">
        @foreach ($accounts as $account)
            <option value="{{ $account->id }}">
                {{ $account->bank_account_type }} - {{ $account->masked_account_number }}
                {{ $currencySymbol }}{{ number_format($account->available_balance, 2) }}
            </option>
        @endforeach
    </x-select>

    {{-- Stats --}}
    <livewire:user.show.user-stats :stats="$stats" :currency-symbol="$currencySymbol"
        :wire:key="'stats-'.$selectedAccountId.'-'.$profileVersion" />

    {{-- Action --}}
    <livewire:user.show.user-action :user="$user" :accounts="$accounts" :selected-account-id="$selectedAccountId" :selected-account="$selectedAccount"
        :currency-symbol="$currencySymbol" :stats="$stats" :wire:key="'action-'.$selectedAccountId.'-'.$profileVersion" />

    {{-- KYC --}}
    <livewire:user.show.user-kyc :user="$user" :wire:key="'kyc-'.$user->id.'-'.$profileVersion" />

    {{-- Profile --}}
    <livewire:user.show.user-profile :user="$user" :currency-symbol="$currencySymbol" :currencies="$currencies"
        :wire:key="'profile-'.$user->id.'-'.$profileVersion" />



    @include('partials.recent-transaction-dashboard', [
        'latestTransactions' => $latestTransactions,
        'viewAllUrl' => route('admin.users.transactions', $user),
    ])


</div>
