<?php

namespace App\Livewire\Auth;

use App\Enums\UserStatus;
use App\Livewire\Forms\Auth\LoginForm;
use App\Models\User;
use App\Traits\Components\WithToast;
use Illuminate\Support\Facades\Auth;
use Illuminate\View\View;
use Livewire\Attributes\Layout;
use Livewire\Component;

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

    public LoginForm $form;

    public function mount(): void
    {
        if (! request()->has('message')) {
            return;
        }

        $this->toast(request('message'));

        $this->js(<<<'JS'
            const url = new URL(window.location);
            url.search = '';
            window.history.replaceState({}, '', url);
        JS);
    }

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

        if (! $this->attemptLogin()) {
            $this->toast('Oops! Nama pengguna, email, atau kata sandi tidak sesuai.', 'Gagal', 'danger');

            return;
        }

        $user = auth()->user();

        if (! $this->userIsActive($user)) {
            Auth::logout();

            $this->toast(
                'Akun Anda belum aktif. Mohon periksa email untuk mengaktifkan akun, dan hubungi kami jika memerlukan bantuan lebih lanjut.',
                'Gagal',
                'danger'
            );

            return;
        }

        session()->regenerate();

        $this->toast('Hai, '.($user?->employee?->full_name ?? $user->customer?->name).'! Semoga harimu menyenangkan 😊');

        $this->redirectByRole($user->roles->pluck('name')->toArray());
    }

    protected function attemptLogin(): bool
    {
        $field = filter_var($this->form->login, FILTER_VALIDATE_EMAIL) ? 'email' : 'username';

        return Auth::attempt([
            $field => $this->form->login,
            'password' => $this->form->password,
        ]);
    }

    protected function userIsActive(?User $user): bool
    {
        return $user?->status === UserStatus::ACTIVE;
    }

    protected function redirectByRole(array $roles): void
    {
        if (array_intersect($roles, ['Developer', 'Owner', 'Leader', 'Admin'])) {
            $this->redirectIntended('/studio/dashboard/overview', navigate: true);

            return;
        }

        if (in_array('Partner', $roles, true)) {
            $this->redirectIntended('/partner/overview', navigate: true);

            return;
        }

        if (in_array('Customer', $roles, true)) {
            $this->redirectIntended('/member/overview', navigate: true);

            return;
        }

        $this->redirectIntended('/login', navigate: true);
    }

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