<?php

use Livewire\Component;
use App\Services\PinService;
use App\Traits\RequiresPin;
use Illuminate\Validation\ValidationException;

new class extends Component {
    use RequiresPin;

    public bool $updatingPin = false; // user already has a PIN
    public bool $enteringNewPin = false; // verified → entering new PIN

    public string $pin = '';
    public string $pin_confirmation = '';

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

        $this->updatingPin = $pinService->userHasPin($profile);
        $this->pinMissing = !$this->updatingPin;
    }

    public function submitPin(PinService $pinService)
    {
        $profile = auth()->user()->profile;

        /**
         * 1. No PIN → create PIN
         */
        if ($this->pinMissing) {
            $this->validatePinConfirmation();

            $pinService->setPin($profile, $this->pin);

            $this->resetPinState();

            $this->dispatch('pin-success');
            $this->dispatch('showToast', message: 'PIN created successfully!', type: 'success');
            return;
        }

        /**
         * 2. Has PIN, not verified yet → verify current PIN
         */
        if (!$this->enteringNewPin) {
            if (!$this->verifyPin($pinService)) {
                $this->addError('pin', 'Invalid PIN.');
                $this->pin = '';
                return;
            }

            $this->enteringNewPin = true;
            $this->pin = '';
            return;
        }

        /**
         * 3. Verified → set new PIN
         */
        try {
            $this->validatePinConfirmation();

            $pinService->setPin($profile, $this->pin);
        } catch (ValidationException $e) {
            $this->addError('pin', $e->getMessage());
            return;
        }

        $this->resetPinState();

        $this->dispatch('pin-success');
        $this->dispatch('showToast', message: 'PIN updated successfully!', type: 'success');
    }

    protected function validatePinConfirmation(): void
    {
        $this->validate(
            [
                'pin' => ['required', 'digits:4'],
                'pin_confirmation' => ['required', 'same:pin'],
            ],
            [
                'pin_confirmation.same' => 'PIN confirmation does not match.',
            ],
        );
    }

    protected function resetPinState(): void
    {
        $this->pin = '';
        $this->pin_confirmation = '';
        $this->enteringNewPin = false;
        $this->pinMissing = false;
    }
};

?>
<x-slot:title>
    {{ config('app.name') }} || Manage Transaction Pin
</x-slot:title>
<section class="w-full py-5">
    <x-settings.layout :heading="__('Transaction PIN')" :subheading="__('Secure your transactions with a 4-digit PIN')">
        <div class="grid grid-cols-1 gap-4">
            <div class="bg-white/80 dark:bg-gray-800/80 backdrop-blur-xl rounded-2xl shadow-lg border overflow-hidden">

                <!-- Header -->
                <div class="border-b px-4 py-3 flex items-center">
                    <div class="w-6 h-6 bg-sky-500 rounded-lg flex items-center justify-center mr-2">
                        <x-flux::icon.shield-check variant="solid" class="text-white w-4 h-4" />
                    </div>
                    <div>
                        <h2 class="text-sm font-bold">
                            {{ $pinMissing ? 'Create Transaction PIN' : ($enteringNewPin ? 'Update Transaction PIN' : 'Verify Current PIN') }}
                        </h2>
                        <p class="text-xs text-gray-500">
                            {{ $pinMissing
                                ? 'Set up a new 4-digit PIN.'
                                : ($enteringNewPin
                                    ? 'Enter and confirm your new PIN.'
                                    : 'Enter your current PIN to continue.') }}
                        </p>
                    </div>
                </div>

                <div class="p-4 space-y-4">

                    <!-- PIN -->
                    <x-flux::input wire:model.defer="pin" type="password" inputmode="numeric" pattern="[0-9]*"
                        maxlength="4" autocomplete="one-time-code" icon="key" viewable :label="$pinMissing || $enteringNewPin ? 'PIN' : 'Current PIN'"
                        placeholder="••••" />

                    <!-- Confirm PIN -->
                    @if ($pinMissing || $enteringNewPin)
                        <x-flux::input wire:model.defer="pin_confirmation" type="password" inputmode="numeric"
                            pattern="[0-9]*" maxlength="4" icon="key" viewable label="Confirm PIN"
                            placeholder="••••" />
                    @endif

                    <!-- Security Notice -->
                    <div class="bg-yellow-50 rounded-xl p-3 border">
                        <p class="text-xs text-yellow-800">
                            Never share your PIN. It will be required for all secure transactions.
                        </p>
                    </div>

                    <!-- Action Button -->
                    <x-button type="button" wire:click="submitPin" wire:loading.attr="disabled" class="w-full"
                        icon="cloud-arrow-down">
                        {{ $pinMissing ? 'Create PIN' : ($enteringNewPin ? 'Save New PIN' : 'Verify PIN') }}
                    </x-button>

                </div>
            </div>
        </div>
    </x-settings.layout>
</section>
