<?php

use Livewire\Component;
use App\Models\Grant;
use Livewire\Attributes\Layout;
use Livewire\WithPagination;
use Livewire\Attributes\Computed;
use App\Traits\WithTableHelpers;
use App\Services\AdminGrantService;

new #[Layout('layouts::base', ['title' => 'grants management'])] class extends Component {
    use WithPagination, WithTableHelpers;

    public int $perPage = 10;
    public int $page = 1;
    public string $currencySymbol = '$';
    public bool $selectAll = false;
    public array $selectedGrants = [];
    public array $selectedMeta = [];
    public ?Grant $selectedGrant = null; // <- add this

    /**
     * View grant metadata in modal
     */
    public function viewMeta($id)
    {
        $grant = Grant::findOrFail($id);
        $this->selectedMeta = $grant->metadata ?? [];
        $this->dispatch('open-meta-modal');
    }

    public function selectGrant($grantId)
    {
        $this->selectedGrant = $this->grants->find($grantId);
        $this->dispatch('open-action-modal');
    }
    /**
     * Bulk Approve Grants
     */
    public function bulkApprove()
    {
        if (empty($this->selectedGrants)) {
            return;
        }

        try {
            // Resolve service and approve selected grants
            $count = app(AdminGrantService::class)->bulkApprove($this->selectedGrants, 'Approved via admin', true);
            $this->dispatch('success');
            // Notify user
            $this->dispatch('showToast', message: "$count grants approved successfully", type: 'success');
            $this->dispatch('notification-sent');

            // Reset selection
            $this->resetSelection();
        } catch (\Exception $e) {
            $this->dispatch('showToast', message: $e->getMessage(), type: 'error');
        }
    }

    /**
     * Bulk Approve Grants
     */
    public function bulkHold()
    {
        if (empty($this->selectedGrants)) {
            return;
        }

        try {
            $count = app(AdminGrantService::class)->bulkHold($this->selectedGrants, 'hold via admin');
            $this->dispatch('success');
            $this->dispatch('showToast', message: "$count Grant put on hold", type: 'success');
            $this->dispatch('notification-sent');
            $this->resetSelection();
        } catch (\Exception $e) {
            $this->dispatch('showToast', message: $e->getMessage(), type: 'error');
        }
    }

    /**
     * Bulk Reject Grants
     */
    public function bulkReject()
    {
        if (empty($this->selectedGrants)) {
            return;
        }

        try {
            // Resolve service and reject selected grants
            $count = app(AdminGrantService::class)->bulkReject($this->selectedGrants, 'Rejected via admin');
            $this->dispatch('success');
            // Notify user
            $this->dispatch('showToast', message: "$count grants rejected successfully", type: 'success');
            $this->dispatch('notification-sent');

            // Reset selection
            $this->resetSelection();
        } catch (\Exception $e) {
            $this->dispatch('showToast', message: $e->getMessage(), type: 'error');
        }
    }

    /**
     * Approve a single grant
     */
    public function approveGrant($id)
    {
        try {
            $grant = Grant::findOrFail($id);

            // Resolve service and approve grant
            app(AdminGrantService::class)->approveGrant($grant, 'Approved individually', true);
            $this->dispatch('notification-sent');
            $this->dispatch('success');
            // Notify user
            $this->dispatch('showToast', message: 'Grant approved', type: 'success');
        } catch (\Exception $e) {
            $this->dispatch('showToast', message: $e->getMessage(), type: 'error');
        }
    }

    /**
     * Reject a single grant
     */
    public function rejectGrant($id)
    {
        try {
            $grant = Grant::findOrFail($id);

            // Resolve service and reject grant
            app(AdminGrantService::class)->rejectGrant($grant, 'Rejected individually');
            $this->dispatch('notification-sent');
            // Notify user
            $this->dispatch('success');
            $this->dispatch('showToast', message: 'Grant rejected', type: 'success');
        } catch (\Exception $e) {
            $this->dispatch('showToast', message: $e->getMessage(), type: 'error');
        }
    }

    /**
     * Put a grant on hold
     */
    public function holdGrant($id)
    {
        try {
            $grant = Grant::findOrFail($id);
            $this->dispatch('success');
            // Resolve service and hold grant
            app(AdminGrantService::class)->holdGrant($grant, 'On hold individually');
            $this->dispatch('notification-sent');
            // Notify user
            $this->dispatch('showToast', message: 'Grant put on hold', type: 'success');
        } catch (\Exception $e) {
            $this->dispatch('showToast', message: $e->getMessage(), type: 'error');
        }
    }

    public function delete($id)
    {
        try {
            $grant = Grant::findOrFail($id);
            app(AdminGrantService::class)->deleteGrant($grant);

            // Reset Livewire state BEFORE re-render
            $this->selectedGrant = null;
            $this->resetSelection();

            $this->dispatch('notification-sent');
            $this->dispatch('success');
            $this->dispatch('showToast', message: 'Grant successfully deleted', type: 'success');

            // Close modal
            $this->dispatch('close-action-modal');
        } catch (\Exception $e) {
            $this->dispatch('showToast', message: $e->getMessage(), type: 'error');
        }
    }

    public function bulkDelete()
    {
        if (empty($this->selectedGrants)) {
            return;
        }

        try {
            $count = app(AdminGrantService::class)->bulkDelete($this->selectedGrants);

            // Reset Livewire state BEFORE re-render
            $this->selectedGrant = null;
            $this->resetSelection();

            $this->dispatch('success');
            $this->dispatch('showToast', message: "$count grants deleted", type: 'success');

            // Close any modal if open
            $this->dispatch('close-action-modal');
        } catch (\Exception $e) {
            $this->dispatch('showToast', message: $e->getMessage(), type: 'error');
        }
    }

    /**
     * Reset selection checkboxes
     */
    protected function resetSelection()
    {
        $this->selectedGrants = [];
        $this->selectAll = false;
    }

    public function closeModal()
    {
        $this->resetSelection();
        $this->resetErrorBag();
        $this->selectedGrant = null;
        $this->dispatch('close-action-modal');
    }

    public function updatedPerPage()
    {
        $this->resetPage();
        $this->dispatch('perPageUpdated', $this->perPage);
    }

    protected function searchableFields(): array
    {
        return ['id', 'user.name', 'user.email', 'type', 'amount', 'status'];
    }

    #[Computed]
    public function grants()
    {
        /** @var \App\Models\Admin|null $admin */
        $admin = auth('admin')->user();

        $query = Grant::query()->with(['user']);

        // Apply visibility filter only if an admin is logged in
        if ($admin) {
            $query->visibleToAdmin($admin);
        } else {
            // No admin logged in, deny access
            $query->whereRaw('1 = 0');
        }

        $this->applySearch($query, $this->searchableFields());

        return $query->orderBy($this->sortField, $this->sortDirection)->paginate($this->perPage)->withQueryString();
    }
    #[Computed]
    public function getPendingSelectedGrantsProperty(): array
    {
        return Grant::whereIn('id', $this->selectedGrants)->where('status', 'pending')->pluck('id')->toArray();
    }

    public function updatedSelectAll($value)
    {
        if ($value) {
            $this->selectedGrants = $this->grants->pluck('id')->toArray();
        } else {
            $this->selectedGrants = [];
        }
    }
};
?>

<div class="space-y-5 py-5">
    <x-page-header title="Grants Management"
        subtitle="Overview of all user grants, their types, purposes, metadata, and status."
        back-url="{{ route('admin.dashboard') }}">
    </x-page-header>


    {{-- Bulk Actions --}}
    <div class="flex gap-2">

        @if (count($this->pendingSelectedGrants))
            <x-flux::button wire:click="bulkApprove" variant="primary" type="button" size="sm" color="green">
                Approve Selected
            </x-flux::button>

            <x-flux::button wire:click="bulkReject" variant="primary" type="button" size="sm" color="yellow">
                Reject Selected
            </x-flux::button>

            <x-flux::button wire:click="bulkHold" variant="primary" type="button" size="sm" color="blue">
                Hold Selected
            </x-flux::button>
        @endif

        {{-- Delete is always visible, but disabled if nothing is selected --}}
        <x-flux::button wire:click="bulkDelete" variant="primary"
            wire:confirm='are you sure you want to delete selected grants?' type="button" size="sm" color="red"
            :disabled="!count($this->selectedGrants)">
            Delete Selected
        </x-flux::button>

    </div>


    <x-table.wrapper :items="$this->grants">


        {{-- HEADERS --}}
        <x-slot name="head">
            <div class="flex items-center space-x-2">
                <label class="inline-flex items-center cursor-pointer">
                    <!-- Hidden native checkbox for accessibility -->
                    <input type="checkbox" wire:model.live="selectAll" class="sr-only peer">
                    <!-- Custom checkbox -->
                    <div
                        class="w-5 h-5 rounded-md border-2 
                    border-gray-300 dark:border-gray-500 
                    bg-white dark:bg-gray-800
                    flex items-center justify-center 
                    peer-checked:bg-blue-600 dark:peer-checked:bg-blue-500
                    peer-checked:border-blue-600 dark:peer-checked:border-blue-500
                    transition-colors duration-200">
                        <!-- Checkmark -->

                    </div>
                    <!-- Label -->
                    <span class="ml-2 text-gray-800 dark:text-gray-200 select-none">Select All</span>
                </label>
            </div>

            <x-table.head label="Selected" />
            <x-table.head label="Grant ID" field="id" sortable :sortField="$sortField" :sortDirection="$sortDirection" />
            <x-table.head label="User" />
            <x-table.head label="Type" field="type" sortable :sortField="$sortField" :sortDirection="$sortDirection" />
            <x-table.head label="Amount" field="amount" sortable :sortField="$sortField" :sortDirection="$sortDirection" />
            <x-table.head label="Status" field="status" sortable :sortField="$sortField" :sortDirection="$sortDirection" />
            <x-table.head label="Actions" />
        </x-slot>

        {{-- BODY (DESKTOP) --}}
        <x-slot name="body">
            @forelse ($this->grants as $grant)
                @php
                    $user = $grant->user;
                    $currencySymbol = $this->currencySymbol;
                @endphp

                <x-table.row wire:key="row-{{ $grant->id }}">
                    {{-- Select Checkbox --}}
                    <x-table.cell>
                        <input type="checkbox" wire:model="selectedGrants" value="{{ $grant->id }}"
                            class="rounded border-gray-300">
                    </x-table.cell>

                    <x-table.cell>{{ $grant->id }}</x-table.cell>

                    <x-table.cell>
                        <a href="{{ route('admin.users.show', $user) }}" class="text-sm font-medium hover:underline">
                            {{ $user->name }} ({{ $user->email }})
                        </a>
                    </x-table.cell>

                    <x-table.cell>{{ ucfirst($grant->type) }}</x-table.cell>

                    @php
                        $userCurrency = $grant->user?->profile?->currency ?? 'USD';
                        $currencySymbol = \App\Support\Currency::symbol($userCurrency);
                    @endphp
                    <x-table.cell>{{ $currencySymbol }}{{ number_format($grant->amount, 2) }}</x-table.cell>

                    <x-table.cell>
                        <span class="px-2 py-1 rounded-full text-xs {{ $grant->statusColor }}">
                            {{ $grant->statusLabel }}
                        </span>
                    </x-table.cell>


                    {{-- Actions Dropdown --}}
                    <x-table.cell>
                        <x-flux::button type="button" variant="primary" size="sm" color="green"
                            wire:click="selectGrant({{ $grant->id }})">
                            Action
                        </x-flux::button>

                        @if (!empty($grant->metadata))
                            <x-button type="button" variant="primary" size="sm" color="sky"
                                wire:click="viewMeta({{ $grant->id }})">
                                View Details
                            </x-button>
                        @endif
                    </x-table.cell>


                </x-table.row>
            @empty
                <tr>
                    <td colspan="7" class="px-6 py-10 text-center text-gray-400">
                        No grants found
                    </td>
                </tr>
            @endforelse
        </x-slot>

        {{-- MOBILE --}}
        <x-slot name="mobile">
            @forelse ($this->grants as $grant)
                @php
                    $user = $grant->user;
                    $currencySymbol = $this->currencySymbol;
                @endphp

                <x-table.mobile-card class="rounded-xl shadow-md p-4 mb-4">
                    <div class="flex items-center justify-between">
                        <label class="inline-flex items-center gap-2">
                            <input type="checkbox" wire:model="selectedGrants" value="{{ $grant->id }}"
                                class="rounded border-gray-300">
                            <span class="text-sm font-medium">{{ $grant->id }}</span>
                        </label>
                        <span class="px-2 py-1 rounded-full text-xs {{ $grant->statusColor }}">
                            {{ $grant->statusLabel }}
                        </span>

                    </div>

                    <div class="mt-2 space-y-1 text-sm">
                        <div><strong>User:</strong> {{ $user->name }} ({{ $user->email }})</div>
                        <div><strong>Type:</strong> {{ ucfirst($grant->type) }}</div>
                        @php
                            $userCurrency = $grant->user?->profile?->currency ?? 'USD';
                            $currencySymbol = \App\Support\Currency::symbol($userCurrency);
                        @endphp
                        <div><strong>Amount:</strong> {{ $currencySymbol }}{{ number_format($grant->amount, 2) }}
                        </div>

                    </div>

                    <div class="mt-3">
                        <x-flux::button type="button" variant="primary" size="sm" color="green"
                            wire:click="selectGrant({{ $grant->id }})">
                            Action
                        </x-flux::button>

                        @if (!empty($grant->metadata))
                            <x-button type="button" variant="primary" size="sm" color="sky"
                                wire:click="viewMeta({{ $grant->id }})">
                                View Details
                            </x-button>
                        @endif
                    </div>

                </x-table.mobile-card>
            @empty
                <div class="px-6 py-6 text-center text-gray-400">
                    No grants found
                </div>
            @endforelse
        </x-slot>

        {{-- FOOTER --}}
        <x-slot name="footer">
            <div class="flex justify-center mt-6">
                {{ $this->grants->links() }}
            </div>
        </x-slot>

    </x-table.wrapper>



    <x-modal maxWidth="max-w-2xl" @open-meta-modal.window="openModal()" @close-meta-modal.window="close()">

        {{-- Header --}}
        <div class="flex items-center justify-between px-6 py-4 border-b border-gray-200 dark:border-gray-700">
            <h2 class="text-lg font-semibold text-gray-900 dark:text-white">
                Grant Metadata
            </h2>

            <button @click="close()" class="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition">
                ✕
            </button>
        </div>

        {{-- Body --}}
        <div class="p-6 max-h-[60vh] overflow-y-auto space-y-6">

            {{-- Metadata Sections --}}
            @forelse ($selectedMeta as $section => $data)
                <h3 class="text-md font-semibold text-gray-700 dark:text-gray-200 border-b pb-1 mb-2">
                    {{ ucwords(str_replace('_', ' ', $section)) }}
                </h3>

                <div class="overflow-x-auto">
                    <table
                        class="w-full text-sm text-left text-gray-600 dark:text-gray-300 border border-gray-200 dark:border-gray-700 rounded-lg">
                        <tbody>
                            @foreach ($data as $key => $value)
                                <tr
                                    class="border-b border-gray-200 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-800 transition">
                                    <td class="px-3 py-2 font-medium bg-gray-50 dark:bg-gray-800 w-1/3 capitalize">
                                        {{ ucwords(str_replace('_', ' ', $key)) }}
                                    </td>
                                    <td class="px-3 py-2 wrap-break-word">{{ $value ?? '-' }}</td>
                                </tr>
                            @endforeach
                        </tbody>
                    </table>
                </div>
            @empty
                <div
                    class="flex items-center justify-center h-32 rounded-xl bg-gray-50 dark:bg-gray-800 border border-dashed border-gray-300 dark:border-gray-600 text-gray-500 dark:text-gray-400 text-sm">
                    No metadata available.
                </div>
            @endforelse

            {{-- Purposes --}}
            @if (!empty($selectedGrant?->purposes))
                <div class="mt-4">
                    <h4 class="text-sm font-semibold text-gray-700 dark:text-gray-200 mb-1">Purposes:</h4>
                    <div class="flex flex-wrap gap-2">
                        @foreach ($selectedGrant->purposes as $purpose)
                            <span
                                class="px-3 py-1 text-xs rounded-full bg-sky-100 dark:bg-sky-700 text-sky-800 dark:text-white">
                                {{ ucwords(str_replace('_', ' ', $purpose)) }}
                            </span>
                        @endforeach
                    </div>
                </div>
            @endif

        </div>

        {{-- Footer --}}
        <div
            class="flex justify-end px-6 py-4 border-t border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800">
            <button @click="close()"
                class="px-4 py-2 text-sm font-medium rounded-lg bg-gray-200 dark:bg-gray-700 text-gray-700 dark:text-gray-200 hover:bg-gray-300 dark:hover:bg-gray-600 transition">
                Close
            </button>
        </div>

    </x-modal>


    <x-modal maxWidth="max-w-2xl" x-on:success.window="close()" @open-action-modal.window="openModal()"
        @close-action-modal.window="close()">

        {{-- Header --}}
        <div class="flex items-center justify-between px-6 py-4 border-b border-gray-200 dark:border-gray-700">
            <h2 class="text-lg font-semibold text-gray-900 dark:text-white">
                Actions for Grant #{{ $selectedGrant?->id }}
            </h2>

            <button wire:click="closeModal"
                class="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition text-xl font-bold">
                ✕
            </button>
        </div>

        @if ($selectedGrant)
            {{-- Content --}}
            <div class="px-6 py-4 space-y-2">
                <p><strong>User:</strong> {{ $selectedGrant?->user->name }} ({{ $selectedGrant?->user->email }})</p>
                <p><strong>Amount:</strong> {{ $currencySymbol }}{{ number_format($selectedGrant?->amount, 2) }}</p>
                <p><strong>Status:</strong>
                    <span class="px-2 py-1 rounded-full text-xs {{ $selectedGrant->statusColor }}">
                        {{ $selectedGrant->statusLabel }}
                    </span>

                </p>
            </div>

            {{-- Purposes --}}
            @if (!empty($selectedGrant?->purposes))
                <div class="my-4">
                    <h4 class="text-sm font-semibold text-gray-700 dark:text-gray-200 mb-1">Purposes:</h4>
                    <div class="flex flex-wrap gap-2">
                        @foreach ($selectedGrant->purposes as $purpose)
                            <span
                                class="px-3 py-1 text-xs rounded-full bg-sky-100 dark:bg-sky-700 text-sky-800 dark:text-white">
                                {{ ucwords(str_replace('_', ' ', $purpose)) }}
                            </span>
                        @endforeach
                    </div>
                </div>
            @endif

            @if ($selectedGrant->status === 'pending')
                <x-flux::button type="button" variant="primary" color="green"
                    wire:click="approveGrant({{ $selectedGrant->id }})">Approve</x-flux::button>

                <x-flux::button type="button" variant="danger"
                    wire:click="rejectGrant({{ $selectedGrant->id }})">Reject</x-flux::button>

                <x-flux::button type="button" variant="primary" color="sky"
                    wire:click="holdGrant({{ $selectedGrant->id }})">Hold</x-flux::button>
            @endif

            <x-flux::button type="button" wire:confirm='Are you sure you want to delete this grant request?'
                variant="danger" wire:click="delete({{ $selectedGrant->id }})">Delete</x-flux::button>

            <x-flux::button type="button" variant="ghost" wire:click="closeModal">Cancel</x-flux::button>
        @endif


    </x-modal>



</div>
