<?php

use Livewire\Component;
use Livewire\Attributes\Layout;
use App\Models\Deposit;
use App\Services\TransactionHandler;

new #[Layout('layouts::base')] class extends Component {
    public Deposit $deposit;
    public string $currencySymbol = '$';
    public array $currencies = [];

    public function mount(Deposit $deposit)
    {
        $this->deposit = $deposit;

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

        $this->loadCurrencies();
    }

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

    /**
     * Approve deposit using the new TransactionHandler service
     */
    public function approveDeposit(): void
    {
        try {
            $transaction = app(TransactionHandler::class)->approveDeposit($this->deposit);

            if (!$transaction) {
                $this->dispatch('showToast', message: 'Deposit already processed or not pending.', type: 'warning');
                return;
            }
            $this->deposit = $this->deposit->fresh();
            $this->dispatch('notification-sent');
            $this->dispatch('showToast', message: 'Deposit approved successfully!', type: 'success');
        } catch (\Exception $e) {
            $this->dispatch('showToast', message: $e->getMessage(), type: 'error');
        }
    }

    /**
     * Reject deposit using the new TransactionHandler service
     */
    public function rejectDeposit(): void
    {
        app(TransactionHandler::class)->rejectTransaction($this->deposit);

        $this->deposit = $this->deposit->fresh();

        $this->dispatch('showToast', message: 'Deposit rejected safely!', type: 'success');
    }
};
?>

<div class="space-y-8 py-6">

    {{-- Page Header --}}
    <x-page-header title="Deposit #{{ $deposit->id }}" subtitle="Approve or review deposit details"
        rightText="Back to List" back-url="{{ route('admin.deposit.index') }}" />

    <div class="space-y-6">

        {{-- ================= Deposit Summary (Hero Section) ================= --}}
        <div
            class="bg-linear-to-r from-sky-500 to-purple-500 text-white rounded-2xl shadow-lg p-6 flex flex-col sm:flex-row justify-between items-center gap-4">
            <div>
                <h2 class="text-2xl font-bold">Deposit #{{ $deposit->id }}</h2>
                <div class="flex items-center justify-between">
                    <span>Status:</span>
                    @php
                        $statusClasses = match ($deposit->status) {
                            Deposit::STATUS_APPROVED => 'bg-green-100 text-green-800',
                            Deposit::STATUS_REJECTED => 'bg-red-100 text-red-800',
                            default => 'bg-yellow-100 text-yellow-800',
                        };

                        $statusText = match ($deposit->status) {
                            deposit::STATUS_APPROVED => 'Approved',
                            deposit::STATUS_REJECTED => 'Rejected',
                            default => 'Pending',
                        };
                    @endphp

                    <span
                        class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium {{ $statusClasses }}">
                        {{ $statusText }}
                    </span>

                </div>
            </div>

            <div class="flex flex-col sm:flex-row items-center sm:space-x-6 gap-2">
                <div class="text-center sm:text-right">
                    <p class="text-xl font-bold">{{ $currencySymbol . number_format($deposit->total, 2) }}</p>
                    <p class="text-sm opacity-80">Total Amount</p>
                </div>

                @if ($deposit->status === 'pending')
                    <div class="flex space-x-2">
                        <x-flux::button wire:click="approveDeposit" variant="primary" color="green">
                            Approve Deposit
                        </x-flux::button>
                        <x-flux::button wire:click="rejectDeposit" variant="danger">
                            Reject Deposit
                        </x-flux::button>
                    </div>
                @endif
            </div>
        </div>

        {{-- ================= Main Content: Left + Right Columns ================= --}}
        <div class="lg:flex lg:space-x-6">

            {{-- ================= Left Column: Deposit Details ================= --}}
            <div class="lg:flex-1 space-y-6">

                <div class="lg:flex-1 space-y-6">

                    {{-- Metrics Cards --}}
                    <div
                        class="bg-white/30 dark:bg-gray-800/30 backdrop-blur-md rounded-xl shadow-lg p-6 grid grid-cols-2 sm:grid-cols-4 gap-6">
                        <x-transaction-card icon="flux::icon.currency-dollar" bgColor="bg-sky-100"
                            darkBgColor="dark:bg-sky-800" textColor="text-sky-600" darkTextColor="dark:text-sky-300"
                            label="Amount" value="{{ $currencySymbol . number_format($deposit->amount, 2) }}" />

                        <x-transaction-card icon="flux::icon.credit-card" bgColor="bg-red-100"
                            darkBgColor="dark:bg-red-800" textColor="text-red-600" darkTextColor="dark:text-red-300"
                            label="Charge" value="{{ $currencySymbol . number_format($deposit->charge, 2) }}" />

                        <x-transaction-card icon="flux::icon.banknotes" bgColor="bg-green-100"
                            darkBgColor="dark:bg-green-800" textColor="text-green-600"
                            darkTextColor="dark:text-green-300" label="Total"
                            value="{{ $currencySymbol . number_format($deposit->total, 2) }}" />

                        <x-transaction-card icon="flux::icon.calendar" bgColor="bg-yellow-100"
                            darkBgColor="dark:bg-yellow-800" textColor="text-yellow-600"
                            darkTextColor="dark:text-yellow-300" label="Date"
                            value="{{ $deposit->created_at->diffForHumans() }}" />
                    </div>

                    <div class="flex items-end justify-end">
                        @if ($deposit->paymentMethod)
                            <a href="{{ route('admin.dashboard', ['paymentMethodId' => $deposit->paymentMethod->id]) }}"
                                class="text-blue-600 dark:text-blue-400 font-semibold hover:underline">
                                View Deposit Method Information
                            </a>
                        @else
                            <span class="italic text-gray-400">N/A</span>
                        @endif
                    </div>

                    {{-- Payment & Account Info --}}
                    <div
                        class="bg-white/30 dark:bg-gray-800/30 backdrop-blur-md rounded-xl shadow-lg p-6 grid grid-cols-2 sm:grid-cols-4 gap-6">

                        <x-transaction-card icon="flux::icon.wallet" bgColor="bg-indigo-100"
                            darkBgColor="dark:bg-indigo-800" textColor="text-indigo-600"
                            darkTextColor="dark:text-indigo-300" label="Payment Method"
                            value="{{ $deposit->paymentMethod->name ?? 'N/A' }}" />

                        <x-transaction-card icon="flux::icon.user-circle" bgColor="bg-purple-100"
                            darkBgColor="dark:bg-purple-800" textColor="text-purple-600"
                            darkTextColor="dark:text-purple-300" label="Account:"
                            value="{{ $deposit->account?->account_number ?? 'N/A' }}" />

                        <x-transaction-card icon="flux::icon.document-currency-bangladeshi" bgColor="bg-teal-100"
                            darkBgColor="dark:bg-teal-800" textColor="text-teal-600" darkTextColor="dark:text-teal-300"
                            label="Currency:" value="{{ $deposit->account?->profile?->currency ?? 'USD' }}" />


                        @if ($deposit->account?->profile?->user?->referrer)
                            <x-transaction-card icon="flux::icon.user-plus" bgColor="bg-pink-100"
                                darkBgColor="dark:bg-pink-800" textColor="text-pink-600"
                                darkTextColor="dark:text-pink-300" label="Referrer:"
                                value="{{ $deposit->account->profile->user->referrer->name }}" />
                        @endif
                    </div>

                </div>


                {{-- ---------- Uploaded File ---------- --}}
                @if ($deposit->file_path)
                    @php
                        $fileUrl = Storage::url($deposit->file_path);
                        $fileExt = strtolower(pathinfo($deposit->file_path, PATHINFO_EXTENSION));
                        $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'];
                    @endphp

                    <section class="bg-white/30 dark:bg-gray-800/30 backdrop-blur-md rounded-xl shadow-lg p-6">
                        <h3 class="font-semibold text-lg mb-4 text-gray-900 dark:text-white">Uploaded Payment Proof</h3>

                        @if (in_array($fileExt, $imageExtensions))
                            <a href="{{ $fileUrl }}" target="_blank"
                                class="block mx-auto w-36 h-36 overflow-hidden rounded-md shadow-md hover:shadow-xl transition">
                                <img src="{{ $fileUrl }}" alt="Deposit File"
                                    class="w-full h-full object-cover hover:scale-105 transition-transform duration-200"
                                    loading="lazy" />
                            </a>
                            <p class="mt-2 text-sm text-gray-500 dark:text-gray-400 text-center capitalize">
                                Click to view full image
                            </p>
                        @else
                            <a href="{{ $fileUrl }}" target="_blank"
                                class="inline-flex items-center px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-md transition font-semibold">
                                <x-flux::icon.viewfinder-circle class="w-4 h-4 mr-2" />
                                View File
                            </a>
                            @if ($deposit->file_description)
                                <p class="mt-2 text-sm text-gray-500 dark:text-gray-400">
                                    {{ $deposit->file_description }}
                                </p>
                            @endif
                        @endif
                    </section>
                @endif

            </div>

            {{-- ================= Right Column: User Profile ================= --}}
            <div class="lg:w-1/3 mt-6 lg:mt-0 space-y-6 sticky top-6">

                <div
                    class="bg-white/30 dark:bg-gray-800/30 backdrop-blur-md rounded-xl shadow-lg p-6 flex flex-col items-center text-center space-y-4">
                    @php
                        $user = $deposit->account->profile->user;
                        $avatar = $deposit->account->profile->profile_photo
                            ? Storage::disk('public')->url($deposit->account->profile->profile_photo)
                            : null;
                    @endphp

                    <div
                        class="w-28 h-28 rounded-full overflow-hidden border-4 border-sky-500 flex items-center justify-center text-4xl font-semibold bg-gray-300 dark:bg-gray-700">
                        @if ($avatar)
                            <img src="{{ asset($avatar) }}" alt="User Avatar" class="w-full h-full object-cover">
                        @else
                            {{ strtoupper(substr($user->name ?? 'N/A', 0, 1)) }}
                        @endif
                    </div>

                    <h4 class="font-bold text-lg text-gray-900 dark:text-white">{{ $user->name ?? 'N/A' }}</h4>
                    <p class="text-gray-500 dark:text-gray-400 lowercase">{{ $user->email ?? 'N/A' }}</p>
                    <span
                        class="px-3 py-1 bg-sky-100 dark:bg-sky-700 text-sky-800 dark:text-white rounded-full text-sm font-medium">
                        KYC: {{ ucfirst($user->kyc_status) }}
                    </span>

                    <a href="{{ route('admin.users.show', $user) }}"
                        class="mt-3 px-5 py-2 bg-sky-600 hover:bg-sky-700 text-white font-semibold rounded-lg transition">
                        View Profile
                    </a>
                </div>

                {{-- ---------- Timestamps ---------- --}}
                <div class=" text-sm text-gray-600 dark:text-gray-400">
                    <div class="bg-gray-100 dark:bg-gray-900 p-4 rounded-xl shadow-sm">
                        <p class="font-medium">Last Updated</p>
                        <p>{{ $deposit->updated_at->toDayDateTimeString() }}</p>
                    </div>
                </div>

            </div>

        </div>
    </div>




</div>
