<?php

use Livewire\Component;
use Livewire\WithPagination;
use Livewire\Attributes\Computed;
use App\Traits\WithTableHelpers;
use App\Models\GrantLog;
use App\Support\Currency;
use Illuminate\Pagination\LengthAwarePaginator;
use App\Services\ExportService;

new class extends Component {
    use WithPagination, WithTableHelpers;

    // Pagination
    public int $perPage = 10;
    public int $page = 1;

    // Track selected transaction
    public ?GrantLog $selectedLog = null;
    public string $exportFormat = 'csv'; // csv | xlsx | pdf
    public string $exportDelivery = 'download'; // download | email
    public string $exportScope = 'all'; // all | page

    // Modal message
    public ?string $modalMessage = null;
    public $currencySymbol;

    protected function exportService(): ExportService
    {
        return app(ExportService::class);
    }
    /**
     * Searchable fields
     */
    protected function searchableFields(): array
    {
        return ['id', 'type', 'amount', 'grant.status'];
    }

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

    public function mount()
    {
        $user = auth()->user();

        $this->currencySymbol = $user->profile ? Currency::symbol($user->profile->currency) : '$';
    }

    public function viewLogDetails($logId)
    {
        $this->selectedLog = GrantLog::with('user')->findOrFail($logId);
        $this->dispatch('open-log-modal');
    }

    /**
     * Base query for logged-in user
     */
    protected function baseQuery()
    {
        $userId = auth()->id();

        return GrantLog::query()
            ->where('user_id', $userId) // only current user's logs
            ->with(['user', 'grant'])
            ->tap(fn($q) => $this->applySearch($q, $this->searchableFields()))
            ->orderBy($this->sortField, $this->sortDirection);
    }
    public function clearModalMessage()
    {
        $this->modalMessage = null;
    }

    #[Computed]
    public function getGrantLogsProperty(): LengthAwarePaginator
    {
        return $this->baseQuery()->paginate($this->perPage);
    }

    /**
     * Explicit getter for IDE/static analysis
     */
    public function grantLogs(): LengthAwarePaginator
    {
        return $this->getGrantLogsProperty();
    }

    /**
     * Export handler
     */

    public function export()
    {
        // Get grant logs based on scope
        $logs = $this->exportScope === 'page' ? $this->grantLogs->getCollection() : $this->baseQuery()->get();

        // Prevent full PDF export if needed
        if ($this->exportFormat === 'pdf' && $this->exportScope === 'all') {
            $this->exportScope = 'page';
        }

        // Show warning if no data
        if ($logs->isEmpty()) {
            $this->dispatch('showToast', message: 'No grant logs to export.', type: 'warning');
            return;
        }

        // Export via download
        if ($this->exportDelivery === 'download') {
            return $this->exportService()->download($logs, $this->exportFormat, 'grant_logs', pdfTitle: 'Grant Logs Export');
        }

        // Export via email
        $this->exportService()->email($logs, $this->exportFormat, 'grant_logs', auth()->user()->email, pdfTitle: 'Grant Logs Export');

        $this->dispatch('showToast', message: 'Grant logs exported via email successfully.', type: 'success');
        $this->dispatch('close-export-modal');
    }
};
?>

<x-slot:title>
    {{ config('app.name') }} || Logs
</x-slot:title>

<div class="py-5">
    <x-table.wrapper :items="$this->grantLogs">

        {{-- SEARCH --}}
        <x-slot name="search">
            <div class="flex items-center justify-between gap-4">

                <div class="w-full md:w-1/3">
                    <div class="relative">
                        <x-flux::icon.magnifying-glass
                            class="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400 dark:text-gray-500" />
                        <input type="text" wire:model.live="search" placeholder="Search by action or user"
                            class="w-full pl-10 pr-4 py-2 text-sm rounded-md bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-700 text-gray-900 dark:text-gray-100 placeholder-gray-400 dark:placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-sky-600 focus:border-sky-600 transition" />
                    </div>
                </div>

                <div class="relative block">
                    <button type="button" @click="$dispatch('open-export-modal')"
                        class="flex items-center gap-2 bg-linear-to-bl from-sky-500 to-sky-800 p-3 rounded-2xl">
                        <x-flux::icon.arrow-down-tray class="w-5 h-5 text-white" variant="solid" />
                        <span class="text-sm capitalize font-semibold text-white">export</span>
                    </button>

                    <!-- EXPORT MODAL -->
                    <x-modal @open-export-modal.window="openModal()" @close-export-modal.window="close()"
                        x-on:export-finished.window="close()">
                        <div class="space-y-6">
                            <div class="text-center space-y-2">
                                <div
                                    class="w-12 h-12 bg-linear-to-bl from-sky-500 to-sky-800 rounded-xl mx-auto flex items-center justify-center text-white">
                                    <x-flux::icon.arrow-down-tray variant="solid" class="w-5 h-5" />
                                </div>
                                <h2 class="text-base font-semibold tracking-wide capitalize">Export Grant Logs</h2>
                                <span class="text-sm text-gray-600 dark:text-sky-200">
                                    Download or receive your grant log data
                                </span>
                            </div>

                            <div>
                                <x-select wire:model.defer="exportScope" label="Export Scope">
                                    <option value="all">All Logs</option>
                                    <option value="page">Current Page</option>
                                </x-select>
                            </div>


                            <div>
                                <x-select wire:model.defer="exportFormat" label="Format"
                                    placeholder="===Select Format===">
                                    <option value="csv">CSV</option>
                                    <option value="xlsx">Excel</option>
                                    <option value="pdf">PDF</option>
                                </x-select>
                            </div>
                            <div>

                                <x-select wire:model.defer="exportDelivery" label="Send As"
                                    placeholder="===Select Export Type===">
                                    <option value="download">Download</option>
                                    <option value="email">Email</option>
                                </x-select>
                            </div>

                            <div x-show="$wire.modalMessage" x-text="$wire.modalMessage" x-init="$watch('$wire.modalMessage', v => v && setTimeout(() => $wire.clearModalMessage(), 3000))"
                                class="bg-sky-50 dark:bg-gray-700 p-3 rounded-md text-center text-sm text-sky-700 dark:text-sky-200">
                            </div>

                            <x-button wire:click="export" variant="primary" class="w-full bg-sky-600 hover:bg-sky-900"
                                type="button">
                                Export Grant Logs
                            </x-button>
                            <button type="button" @click="$dispatch('close-export-modal')"
                                class="w-full text-center text-sm text-red-600 hover:underline">
                                Cancel
                            </button>
                        </div>
                    </x-modal>

                    <!-- Custom Grant Log Modal -->
                    <div x-data="{ open: false }" x-show="open" x-cloak x-on:open-log-modal.window="open = true"
                        x-on:close-log-modal.window="open = false" x-transition:enter="transition ease-out duration-200"
                        x-transition:enter-start="opacity-0 scale-95" x-transition:enter-end="opacity-100 scale-100"
                        x-transition:leave="transition ease-in duration-150"
                        x-transition:leave-start="opacity-100 scale-100" x-transition:leave-end="opacity-0 scale-95"
                        class="fixed inset-0 z-50 flex items-center justify-center bg-black/30 backdrop-blur-md bg-opacity-50">

                        <!-- Modal content -->
                        <div
                            class="bg-white dark:bg-gray-800 rounded-xl shadow-lg w-full max-w-2xl
          max-h-[85vh] sm:max-h-[90vh] overflow-y-auto p-6 relative">

                            <!-- Close button -->
                            <button @click="open = false"
                                class="sticky top-4 ml-auto block text-gray-500 hover:text-gray-700 dark:hover:text-gray-300">
                                &times;
                            </button>


                            <h2 class="text-xl font-semibold mb-4 text-gray-900 dark:text-gray-100">Grant Log Details
                            </h2>

                            <div class="space-y-2 text-gray-700 dark:text-gray-300 text-sm">
                                <div
                                    class="mt-3 overflow-x-auto rounded-lg border border-gray-200 dark:border-gray-700">
                                    <table class="w-full text-sm">
                                        <tbody>

                                            <tr class="bg-white dark:bg-gray-800">
                                                <th
                                                    class="text-left px-4 py-2 font-semibold text-gray-900 dark:text-gray-100 whitespace-nowrap">
                                                    Log ID
                                                </th>
                                                <td class="px-4 py-2 text-gray-700 dark:text-gray-300">
                                                    {{ $selectedLog?->id ?? '-' }}
                                                </td>
                                            </tr>

                                            <tr class="bg-gray-50 dark:bg-gray-800/40">
                                                <th
                                                    class="text-left px-4 py-2 font-semibold text-gray-900 dark:text-gray-100 whitespace-nowrap">
                                                    Grant ID
                                                </th>
                                                <td class="px-4 py-2 text-gray-700 dark:text-gray-300">
                                                    {{ $selectedLog?->grant_id ?? '-' }}
                                                </td>
                                            </tr>

                                            <tr class="bg-white dark:bg-gray-800">
                                                <th
                                                    class="text-left px-4 py-2 font-semibold text-gray-900 dark:text-gray-100 whitespace-nowrap">
                                                    User
                                                </th>
                                                <td class="px-4 py-2 text-gray-700 dark:text-gray-300">
                                                    {{ $selectedLog?->user?->name ?? '-' }}
                                                </td>
                                            </tr>

                                            <tr class="bg-gray-50 dark:bg-gray-800/40">
                                                <th
                                                    class="text-left px-4 py-2 font-semibold text-gray-900 dark:text-gray-100 whitespace-nowrap">
                                                    Action
                                                </th>
                                                <td class="px-4 py-2 text-gray-700 dark:text-gray-300 capitalize">
                                                    {{ str_replace('_', ' ', $selectedLog?->action ?? '-') }}
                                                </td>
                                            </tr>

                                            <tr class="bg-white dark:bg-gray-800">
                                                <th
                                                    class="text-left px-4 py-2 font-semibold text-gray-900 dark:text-gray-100 whitespace-nowrap">
                                                    Status
                                                </th>
                                                <td class="px-4 py-2">
                                                    @php
                                                        $grant = $selectedLog?->grant;
                                                    @endphp

                                                    <span
                                                        class="px-2 py-1 rounded-full text-xs font-semibold {{ $grant?->statusColor }}">
                                                        {{ $grant?->statusLabel ?? '-' }}
                                                    </span>
                                                </td>
                                            </tr>


                                        </tbody>
                                    </table>
                                </div>


                                <div>
                                    <span class="font-semibold">Data:</span>

                                    @php
                                        // Flatten nested arrays into dot keys (same idea as email)
                                        $flatten = function (array $array, string $prefix = '') use (&$flatten) {
                                            $result = [];

                                            foreach ($array as $key => $value) {
                                                $fullKey = $prefix === '' ? $key : "{$prefix}.{$key}";

                                                if (is_array($value)) {
                                                    $result += $flatten($value, $fullKey);
                                                } else {
                                                    $result[$fullKey] = $value;
                                                }
                                            }

                                            return $result;
                                        };

                                        $logData = $selectedLog?->data;

                                        // Make sure it's an array
$logData = is_array($logData) ? $logData : [];

$flatLogData = $flatten($logData);

// Make keys human-readable
$pretty = function ($key) {
    // Remove "metadata." prefix if it exists
    $key = preg_replace('/^metadata\./i', '', $key);

    return ucwords(str_replace(['_', '.'], [' ', ' → '], $key));
                                        };

                                    @endphp

                                    @if (!empty($flatLogData))
                                        <div
                                            class="mt-2 overflow-x-auto rounded-lg border border-gray-200 dark:border-gray-700">
                                            <table class="w-full text-sm">
                                                <tbody>
                                                    @foreach ($flatLogData as $k => $v)
                                                        <tr
                                                            class="{{ $loop->even ? 'bg-gray-50 dark:bg-gray-800/40' : 'bg-white dark:bg-gray-800' }}">
                                                            <th
                                                                class="text-left px-4 py-2 font-semibold text-gray-900 dark:text-gray-100 whitespace-nowrap">
                                                                {{ $pretty($k) }}
                                                            </th>
                                                            <td
                                                                class="px-4 py-2 text-gray-700 dark:text-gray-300 break-words">
                                                                {{ is_null($v) || $v === '' ? '-' : (string) $v }}
                                                            </td>
                                                        </tr>
                                                    @endforeach
                                                </tbody>
                                            </table>
                                        </div>
                                    @else
                                        <div class="mt-2 text-gray-500 dark:text-gray-400">-</div>
                                    @endif
                                </div>


                                <div><span class="font-semibold">Created At:</span>
                                    {{ $selectedLog?->created_at?->toDayDateTimeString() ?? '-' }}</div>
                            </div>

                            <button @click="open = false"
                                class="mt-6 w-full py-2 px-4 rounded-lg bg-red-500 hover:bg-red-600 text-white font-semibold">
                                Close
                            </button>
                        </div>
                    </div>



                </div>
            </div>
        </x-slot>

        {{-- HEADERS --}}
        <x-slot name="head">
            <x-table.head label="ID" field="id" sortable :sortField="$sortField" :sortDirection="$sortDirection" />
            <x-table.head label="Grant ID" field="grant_id" sortable :sortField="$sortField" :sortDirection="$sortDirection" />
            <x-table.head label="User" field="user_id" sortable :sortField="$sortField" :sortDirection="$sortDirection" />
            <x-table.head label="Action" field="action" sortable :sortField="$sortField" :sortDirection="$sortDirection" />
            <x-table.head label="Status" />
            <x-table.head label="Created At" field="created_at" sortable :sortField="$sortField" :sortDirection="$sortDirection" />
            <x-table.head label="Action" />
        </x-slot>

        {{-- BODY --}}
        <x-slot name="body">
            @forelse ($this->grantLogs as $log)
                <x-table.row wire:key="log-{{ $log->id }}"
                    class="hover:shadow-lg transition-shadow duration-200 rounded-lg mb-2">

                    <x-table.cell class="font-semibold text-gray-900 dark:text-gray-200">
                        #{{ $log->id }}
                    </x-table.cell>

                    <x-table.cell class="text-gray-700 dark:text-gray-300">
                        #{{ $log->grant_id }}
                    </x-table.cell>

                    <x-table.cell class="text-gray-700 dark:text-gray-300">
                        {{ $log->user?->name ?? 'N/A' }}
                    </x-table.cell>

                    <x-table.cell class="capitalize text-gray-700 dark:text-gray-300">
                        {{ str_replace('_', ' ', $log->action) }}
                    </x-table.cell>

                    <x-table.cell class="text-xs font-semibold">
                        <span
                            class="px-2 py-1 rounded-full text-white text-xs 
        {{ $log->grant->status === 'submitted' ? 'bg-green-500' : '' }}
        {{ $log->grant->status === 'pending' ? 'bg-yellow-500' : '' }}
        {{ $log->grant->status === 'rejected' ? 'bg-red-500' : '' }}
        {{ $log->grant->status === 'approved' ? 'bg-blue-500' : '' }}
        {{ !$log->grant->status ? 'bg-gray-400' : '' }}">
                            {{ ucfirst(str_replace('_', ' ', $log->grant->status ?? 'N/A')) }}
                        </span>
                    </x-table.cell>


                    <x-table.cell class="text-gray-500 dark:text-gray-400 text-sm">
                        <span title="{{ $log->created_at->toDayDateTimeString() }}">
                            {{ $log->created_at->diffForHumans() }}
                        </span>
                    </x-table.cell>

                    <x-table.cell>
                        <button type="button" wire:click="viewLogDetails({{ $log->id }})"
                            class="inline-flex w-full items-center justify-center gap-2 px-4 py-2 font-medium rounded-lg bg-linear-to-r from-sky-500 to-sky-600 text-white shadow-md hover:from-sky-600 hover:to-sky-700 transition-all duration-200 capitalize text-xs">
                            <x-flux::icon.newspaper variant="solid" class="w-4 h-4" />
                            View Details
                        </button>

                    </x-table.cell>

                </x-table.row>
            @empty
                <tr>
                    <td colspan="7" class="px-6 py-10 text-center text-gray-400 dark:text-gray-500">
                        <div class="flex flex-col items-center justify-center gap-2">
                            <div
                                class="w-14 h-14 rounded-full flex items-center justify-center bg-linear-to-r from-sky-400 to-sky-600 text-white">
                                <flux:icon name="inbox" class="w-6 h-6" />
                            </div>
                            <p class="text-gray-700 dark:text-gray-300 text-lg font-medium">No grant logs found
                            </p>
                        </div>
                    </td>
                </tr>
            @endforelse
        </x-slot>

        {{-- MOBILE --}}
        <x-slot name="mobile">
            @forelse ($this->grantLogs as $log)
                <x-table.mobile-card
                    class="bg-white dark:bg-gray-800 rounded-xl shadow-md p-4 mb-4 hover:shadow-xl transition duration-200">

                    <div class="flex justify-between items-center mb-3">
                        <h3 class="text-sm font-semibold text-gray-900 dark:text-gray-200">Log #{{ $log->id }}
                        </h3>
                        <span
                            class="text-xs font-semibold px-3 py-1 rounded-full
                                {{ $log->action === 'submitted'
                                    ? 'bg-linear-to-r from-green-400 to-green-600 text-white'
                                    : 'bg-gray-300 text-gray-800' }}">
                            {{ str_replace('_', ' ', $log->action) }}
                        </span>
                    </div>

                    <div class="space-y-2 text-sm text-gray-700 dark:text-gray-300">
                        <div class="flex justify-between">
                            <span class="text-gray-500 dark:text-gray-400">Grant ID:</span>
                            <span>#{{ $log->grant_id }}</span>
                        </div>

                        <div class="flex justify-between">
                            <span class="text-gray-500 dark:text-gray-400">User:</span>
                            <span>{{ $log->user?->name ?? 'N/A' }}</span>
                        </div>

                        <div class="flex justify-between">
                            <span class="text-gray-500 dark:text-gray-400">Data:</span>
                            <span class="truncate max-w-xs">{{ json_encode($log->data) }}</span>
                        </div>

                        <div class="flex justify-between">
                            <span class="text-gray-500 dark:text-gray-400">Date:</span>
                            <span title="{{ $log->created_at->toDayDateTimeString() }}">
                                {{ $log->created_at->diffForHumans() }}
                            </span>
                        </div>
                    </div>

                    <button wire:click="viewLogDetails({{ $log->id }})"
                        class="mt-4 inline-flex w-full items-center justify-center gap-2 px-4 py-2 text-sm font-medium rounded-lg bg-linear-to-r from-sky-500 to-sky-600 text-white shadow-md hover:from-sky-600 hover:to-sky-700 transition-all duration-200 capitalize">
                        <x-flux::icon.newspaper variant="solid" class="w-5 h-5" />
                        View Details
                    </button>

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

        {{-- FOOTER --}}
        <x-slot name="footer">
            <div class="flex flex-col md:flex-row md:items-center md:justify-between w-full gap-4 mt-6"
                x-data="{
                    open: false,
                    options: [5, 10, 15, 20, 25, 50],
                    selected: @js($perPage)
                }" x-init="$watch('selected', value => $wire.set('perPage', value));
                Livewire.on('perPageUpdated', event => selected = event.value);">

                <div class="relative text-sm w-fit">
                    <label class="block text-gray-700 dark:text-gray-300 mb-1 text-xs font-medium">
                        Rows per page
                    </label>

                    <button @click="open = !open"
                        class="w-36 bg-white dark:bg-gray-800 text-gray-800 dark:text-white border border-gray-300 dark:border-gray-600 rounded-md px-4 py-2 flex justify-between items-center shadow-sm hover:border-gray-400 dark:hover:border-gray-500 focus:outline-none focus:ring-2 focus:ring-sky-500"
                        type="button" aria-haspopup="listbox" aria-expanded="open">
                        <span x-text="selected"></span>
                        <svg class="w-4 h-4 ml-2 transform transition-transform duration-200"
                            :class="{ 'rotate-180': open }" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                d="M19 9l-7 7-7-7" />
                        </svg>
                    </button>

                    <div x-show="open" @click.outside="open = false"
                        x-transition:enter="transition ease-out duration-100"
                        x-transition:enter-start="opacity-0 scale-95" x-transition:enter-end="opacity-100 scale-100"
                        x-transition:leave="transition ease-in duration-75"
                        x-transition:leave-start="opacity-100 scale-100" x-transition:leave-end="opacity-0 scale-95"
                        class="absolute bottom-0 mt-2 w-full z-50 bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-md shadow-lg">
                        <ul class="py-1 max-h-60 overflow-auto text-sm text-gray-800 dark:text-white">
                            <template x-for="option in options" :key="option">
                                <li>
                                    <a href="#" @click.prevent="selected = option; open = false"
                                        class="block px-4 py-2 cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-700"
                                        :class="{ 'bg-gray-100 dark:bg-gray-700 font-semibold': selected === option }"
                                        x-text="option"></a>
                                </li>
                            </template>
                        </ul>
                    </div>
                </div>

                <div class="w-full md:w-auto text-center">{{ $this->grantLogs->links() }}</div>
            </div>
        </x-slot>



    </x-table.wrapper>
</div>
