<?php

namespace App\Livewire\Auth;

use App\Livewire\Forms\Auth\RegisterForm;
use App\Traits\WithToast;
use App\Traits\WithUpdatedData;
use Illuminate\Support\Str;
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()
    {
        $this->steps = [
            ['id' => 1, 'name' => 'Kredensial'],
            ['id' => 2, 'name' => 'Informasi'],
        ];
    }

    public function updateStep(int $value)
    {
        if ($this->currentStep === 1) {
            $this->form->validateStep1();
        }

        $this->currentStep = $value;
    }

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

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

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

    public function updated(string $propertyName, $value)
    {
        $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());
        }
    }

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

        $this->toast('Selamat, akun Anda berhasil didaftarkan. Silakan periksa email Anda untuk melakukan verifikasi.');

        $this->redirectIntended('/customer/dashboard/overview', navigate: true);
    }

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