<?php

namespace App\Livewire\Auth;

use App\Jobs\StorePushNotification;
use App\Livewire\Forms\Auth\RegisterForm;
use App\Models\PushNotification;
use App\Models\User;
use App\Traits\Components\WithToast;
use App\Traits\Utilities\WithUpdatedData;
use Illuminate\Support\Str;
use Illuminate\View\View;
use Livewire\Attributes\Layout;
use Livewire\Component;

#[Layout('components.layouts.auth', [
    'title' => 'Daftar Akun',
])]
class Register extends Component
{
    use WithToast, WithUpdatedData;

    public RegisterForm $form;

    public array $steps = [];

    public int $currentStep = 1;

    public int $totalSteps = 2;

    public function mount(): void
    {
        $this->steps = [
            ['id' => 1, 'name' => 'Kredensial'],
            ['id' => 2, 'name' => 'Informasi'],
        ];
    }

    public function updateStep(int $value): void
    {
        if ($this->shouldValidateBeforeChangingStep()) {
            $this->form->validateStep1();
        }

        $this->currentStep = $value;
    }

    public function nextStep(): void
    {
        match ($this->currentStep) {
            1 => $this->form->validateStep1(),
            2 => $this->form->validateStep2(),
            default => null,
        };

        if ($this->currentStep < $this->totalSteps) {
            $this->currentStep++;
        }
    }

    public function prevStep(): void
    {
        if ($this->currentStep > 1) {
            $this->currentStep--;
        }
    }

    public function updated(string $propertyName, mixed $value): void
    {
        $this->validateUpdatedField($propertyName);
    }

    public function register(): void
    {
        $this->form->auth();

        $this->sendRegistrationSuccessToast();
        $this->notifyPrivilegedUsersAboutNewMember();
        $this->redirectAfterRegistration();
    }

    public function render(): View
    {
        return view('livewire.auth.register');
    }

    /**
     * Determine whether validation is required before changing step.
     */
    protected function shouldValidateBeforeChangingStep(): bool
    {
        return $this->currentStep === 1;
    }

    /**
     * Validate updated field based on current form step rules.
     */
    protected function validateUpdatedField(string $propertyName): void
    {
        $field = Str::replace('form.', '', $propertyName);

        if (array_key_exists($field, $this->form->rulesStep1())) {
            $this->validateOnly($propertyName, $this->form->rulesStep1());
        }

        if (array_key_exists($field, $this->form->rulesStep2())) {
            $this->validateOnly($propertyName, $this->form->rulesStep2());
        }
    }

    /**
     * Show success toast after registration.
     */
    protected function sendRegistrationSuccessToast(): void
    {
        $this->toast('Selamat, akun Anda berhasil didaftarkan. Silakan periksa email Anda untuk melakukan verifikasi.');
    }

    /**
     * Dispatch notification to privileged users when a new member registers.
     */
    protected function notifyPrivilegedUsersAboutNewMember(): void
    {
        $userIds = User::role(['Developer', 'Owner'])->pluck('id')->toArray();

        StorePushNotification::dispatch(
            PushNotification::whereIn('user_id', $userIds)->get(),
            [
                'title' => '🎉Member Baru Bergabung!',
                'body' => 'Ada member baru saja bergabung. Cek profil lengkapnya di aplikasi! 🌟',
                'url' => route('studio.loyalty.customer.index'),
            ],
        );
    }

    /**
     * Redirect user after successful registration.
     */
    protected function redirectAfterRegistration(): void
    {
        $this->redirectIntended('/member/overview', navigate: true);
    }
}
