<?php

use Livewire\Component;
use Livewire\Attributes\Layout;
use App\Models\CryptoWallet;
use App\Traits\WithTableHelpers;
use Livewire\WithPagination;
use Livewire\Attributes\Computed;

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

    public $name,
        $address,
        $code,
        $fee_percent = 0,
        $is_active = true;
    public $editingWallet = null;
    public int $perPage = 10;

    public int $page = 1; // required for Livewire pagination
    protected function searchableFields(): array
    {
        return ['id', 'payment_method.type', 'address', 'name', 'code'];
    }
    protected $rules = [
        'name' => 'required|string|max:255|unique:crypto_wallets,name',
        'address' => 'required|string|max:255',
        'code' => 'required|string|max:255|unique:crypto_wallets,code',
        'fee_percent' => 'required|numeric|min:0',
        'is_active' => 'boolean',
    ];

    public function updatedPerPage(): void
    {
        $this->resetPage();
        $this->dispatch('perPageUpdated', $this->perPage);
    }
    public function delete($id)
    {
        CryptoWallet::findOrFail($id)->delete();
        $this->dispatch('showToast', 'Wallet successfully deleted', type: 'success');
    }
    public function resetForm()
    {
        $this->name = '';
        $this->address = '';
        $this->code = '';
        $this->fee_percent = 0;
        $this->is_active = true;
        $this->editingWallet = null;
        $this->resetValidation();
    }
    public function editWallet($id)
    {
        $wallet = CryptoWallet::findOrFail($id);
        $this->editingWallet = $wallet->id;
        $this->name = $wallet->name;
        $this->address = $wallet->address;
        $this->code = $wallet->code;
        $this->fee_percent = $wallet->fee_percent;
        $this->is_active = $wallet->is_active;
    }
    public function toggleActive($id)
    {
        $wallet = CryptoWallet::findOrFail($id);
        $wallet->is_active = !$wallet->is_active;
        $wallet->save();
        $this->dispatch('showToast', 'Wallet status updated', type: 'success');
    }
    public function saveWallet()
    {
        // Adjust validation for edit
        $rules = $this->rules;
        if ($this->editingWallet) {
            $rules['name'] .= ',' . $this->editingWallet;
            $rules['code'] .= ',' . $this->editingWallet;
        }

        $validated = $this->validate($rules);
        if ($this->editingWallet) {
            CryptoWallet::find($this->editingWallet)->update($validated);
            session()->flash('success', 'Wallet updated successfully!');
            $message = 'Wallet updated successfully!';
        } else {
            CryptoWallet::create($validated);
            $message = 'Wallet created successfully!';
        }
        $this->dispatch('showToast', message: $message, type: 'success');
        $this->resetForm();
    }
    #[Computed]
    public function wallets()
    {
        $query = CryptoWallet::query();
        $this->applySearch($query, $this->searchableFields());

        return $query->orderBy($this->sortField, $this->sortDirection)->paginate($this->perPage)->withQueryString();
    }
};
?>

<div class="min-h-screen bg-gray-50 dark:bg-gray-950 p-6 space-y-6">
    <!-- Dynamic Page Title -->
    <div class="mb-4">
        <h2 class="text-xl font-semibold text-gray-800 dark:text-gray-100">
            Manage Crypto Wallet
        </h2>
    </div>
    {{-- Form --}}
    <div class="mb-6 p-4 bg-gray-50 dark:bg-gray-800 rounded shadow">
        <h3 class="font-semibold text-lg mb-4">
            {{ $editingWallet ? 'Edit Wallet' : 'Add New Wallet' }}
        </h3>
        <div class="space-y-4">
            <flux:input wire:model.defer="name" label="Wallet Name" placeholder="Bitcoin" />

            <flux:input wire:model.defer="address" label="Wallet Address" placeholder="btc12ds22..." />
            <flux:input wire:model.defer="code" label="Wallet Code" placeholder="btc..." />

            <flux:input wire:model.defer="fee_percent" label="Fee %" type="number" placeholder="0" />

            {{-- Active Toggle --}}
            <div class="flex items-center gap-3 m">
                <button wire:click="$toggle('is_active')"
                    class="relative w-20 h-8 rounded-full cursor-pointer transition-all duration-300 ease-in-out
        {{ $is_active
            ? 'bg-linear-to-r from-green-400 to-green-600 hover:from-green-500 hover:to-green-700'
            : 'bg-linear-to-r from-red-400 to-red-600 hover:from-red-500 hover:to-red-700' }}">

                    {{-- Sliding Circle --}}
                    <span
                        class="absolute top-0.5 left-0.5 w-7 h-7 rounded-full shadow-md transform transition-all duration-300
            {{ $is_active ? 'translate-x-12 bg-white dark:bg-white' : 'translate-x-0 bg-white dark:bg-white' }}">
                    </span>

                    {{-- Text Inside Toggle --}}
                    <span
                        class="absolute inset-0 flex items-center justify-center text-xs font-semibold text-white pointer-events-none select-none">
                        {{ $is_active ? 'Active' : 'Inactive' }}
                    </span>
                </button>
            </div>

            <flux:button wire:click="saveWallet" variant="primary" color="indigo" class="w-full text-center py-3">
                {{ $editingWallet ? 'Update Wallet' : 'Add Wallet' }}
            </flux:button>
            @if ($editingWallet)
                <x-flux::button type="button" variant="danger" wire:click="resetForm">
                    Cancel
                </x-flux::button>
            @endif
        </div>

    </div>

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

        {{-- SEARCH --}}
        <x-slot name="search">
            <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 model or title"
                        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-blue-600 focus:border-blue-600 transition" />
                </div>
            </div>
        </x-slot>

        {{-- HEADERS --}}
        <x-slot name="head">
            <x-table.head label="Wallet ID" field="id" sortable :sortField="$sortField" :sortDirection="$sortDirection" />

            <x-table.head label="Name" field="name" sortable :sortField="$sortField" :sortDirection="$sortDirection" />
            <x-table.head label="Address" field="address" sortable :sortField="$sortField" :sortDirection="$sortDirection" />
            <x-table.head label="Fee %" field="fee_percent" sortable :sortField="$sortField" :sortDirection="$sortDirection" />
            <x-table.head label="Code" field="code" sortable :sortField="$sortField" :sortDirection="$sortDirection" />
            <x-table.head label="Status" field="is_active" sortable :sortField="$sortField" :sortDirection="$sortDirection" />
            <x-table.head label="Created At" field="created_at" sortable :sortField="$sortField" :sortDirection="$sortDirection" />
            <x-table.head label="Action" />
        </x-slot>

        <x-slot name="body">
            @forelse ($this->wallets as $wallet)
                <x-table.row wire:key="row-{{ $wallet->id }}">

                    {{-- Wallet ID --}}
                    <x-table.cell class="font-medium">
                        #{{ $wallet->id }}
                    </x-table.cell>

                    {{-- Name --}}
                    <x-table.cell>
                        {{ $wallet->name }}
                    </x-table.cell>

                    {{-- Address --}}
                    <x-table.cell>
                        {{ $wallet->address }}
                    </x-table.cell>

                    {{-- Fee % --}}
                    <x-table.cell>
                        {{ $wallet->fee_percent }} %
                    </x-table.cell>

                    {{-- Code --}}
                    <x-table.cell>
                        {{ $wallet->code }}
                    </x-table.cell>

                    {{-- Status --}}
                    <x-table.cell>
                        <div class="flex items-center gap-3">
                            <button wire:click="toggleActive({{ $wallet->id }})"
                                class="relative w-20 h-8 rounded-full cursor-pointer transition-all duration-300 ease-in-out
        {{ $wallet->is_active
            ? 'bg-linear-to-r from-green-400 to-green-600 hover:from-green-500 hover:to-green-700'
            : 'bg-linear-to-r from-red-400 to-red-600 hover:from-red-500 hover:to-red-700' }}">

                                {{-- Sliding Circle --}}
                                <span
                                    class="absolute top-0.5 left-0.5 w-7 h-7 rounded-full shadow-md transform transition-all duration-300
            {{ $wallet->is_active ? 'translate-x-12 bg-white dark:bg-white' : 'translate-x-0 bg-white dark:bg-white' }}">
                                </span>

                                {{-- Text Inside Toggle --}}
                                <span
                                    class="absolute inset-0 flex items-center justify-center text-xs font-semibold text-white pointer-events-none select-none">
                                    {{ $wallet->is_active ? 'Active' : 'Inactive' }}
                                </span>
                            </button>
                        </div>
                    </x-table.cell>

                    {{-- Created At --}}
                    <x-table.cell>
                        {{ $wallet->created_at->diffForHumans() }}
                    </x-table.cell>

                    {{-- Action --}}
                    <x-table.cell>
                        <button wire:click="editWallet({{ $wallet->id }})"
                            class="inline-flex items-center px-3 py-1.5 text-sm font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700">
                            Edit
                        </button>

                        <button wire:click="deleteWallet({{ $wallet->id }})"
                            class="px-2 py-1 bg-red-500 text-white rounded"
                            onclick="confirm('Are you sure?') || event.stopImmediatePropagation()">
                            Delete
                        </button>
                    </x-table.cell>

                </x-table.row>

                @empty
                <tr>
                    <td colspan="8" class="px-6 py-6 text-center text-gray-400">
                        No wallets found.
                    </td>
                </tr>
            @endforelse
        </x-slot>

        {{-- MOBILE --}}
        <x-slot name="mobile">
            @foreach ($this->wallets as $wallet)
                <x-table.mobile-card>

                    <div class="flex justify-between border-b pb-2 mb-3">
                        <span class="font-semibold">#{{ $wallet->id }}</span>
                        <span class="text-gray-500 text-sm">{{ $wallet->created_at->diffForHumans() }}</span>
                    </div>

                    <div class="text-sm space-y-2">
                        <div class="flex justify-between">
                            <span class="text-gray-500">Name</span>
                            <span>{{ $wallet->name }}</span>
                        </div>

                        <div class="flex justify-between">
                            <span class="text-gray-500">Address</span>
                            <span>{{ $wallet->address }}</span>
                        </div>

                        <div class="flex justify-between">
                            <span class="text-gray-500">Fee %</span>
                            <span>{{ $wallet->fee_percent }}%</span>
                        </div>

                        <div class="flex justify-between">
                            <span class="text-gray-500">Code</span>
                            <span>{{ $wallet->code }}</span>
                        </div>

                        <div class="flex justify-between">
                            <span class="text-gray-500">Status</span>
                            <span class="{{ $wallet->is_active ? 'text-green-600' : 'text-red-600' }}">
                                {{ $wallet->is_active ? 'Active' : 'Inactive' }}
                            </span>
                        </div>

                        {{-- Actions --}}
                        <div class="mt-3 flex space-x-2">
                            <button wire:click="editWallet({{ $wallet->id }})"
                                class="inline-flex items-center px-3 py-1.5 text-sm font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-1 transition">
                                Edit
                            </button>

                            <button wire:click="deleteWallet({{ $wallet->id }})"
                                class="inline-flex items-center px-3 py-1.5 text-sm font-medium rounded-md text-white bg-red-600 hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-offset-1 transition"
                                onclick="confirm('Are you sure?') || event.stopImmediatePropagation()">
                                Delete
                            </button>
                        </div>
                    </div>

                </x-table.mobile-card>
            @endforeach
        </x-slot>

        {{-- Footer (pagination + perPage dropdown) --}}
        <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);"
                x-transition:enter="transition-opacity ease-out duration-500" x-transition:enter-start="opacity-0"
                x-transition:enter-end="opacity-100" x-transition:leave="transition-opacity ease-in duration-300"
                x-transition:leave-start="opacity-100" x-transition:leave-end="opacity-0">

                <!-- Rows Per Page Selector -->
                <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-blue-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>

                    <!-- Dropdown -->
                    <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>

                <!-- Pagination Links -->
                <div class="w-full md:w-auto text-center">{{ $this->wallets->links() }}
                </div>

            </div>

        </x-slot>

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