<?php

namespace App\Filament\Pages;

use App\Models\User;
use BackedEnum;
use Filament\Facades\Filament;
use Filament\Notifications\Notification;
use Filament\Pages\Page;
use Filament\Support\Enums\Width;
use Filament\Support\Icons\Heroicon;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules\Password;
use Illuminate\Validation\ValidationException;

class ChangeAdminPassword extends Page
{
    protected static string|BackedEnum|null $navigationIcon = Heroicon::Key;

    protected static bool $shouldRegisterNavigation = false;

    protected static ?string $slug = 'change-password';

    protected string $view = 'filament.pages.change-admin-password';

    protected Width|string|null $maxContentWidth = Width::TwoExtraLarge;

    public ?string $current_password = null;

    public ?string $password = null;

    public ?string $password_confirmation = null;

    public static function canAccess(): bool
    {
        $user = Filament::auth()->user();

        return $user instanceof User && $user->isAdmin();
    }

    public function savePassword(): mixed
    {
        $data = $this->validate([
            'current_password' => ['nullable', 'string'],
            'password' => ['required', 'confirmed', Password::default()],
        ]);

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

        if (! $user instanceof User) {
            abort(403);
        }

        if (filled($user->password) && ! Hash::check((string) $data['current_password'], $user->password)) {
            throw ValidationException::withMessages([
                'current_password' => 'The current password is incorrect.',
            ]);
        }

        $user->forceFill([
            'password' => (string) $data['password'],
            'password_set_at' => now(),
            'must_change_password' => false,
        ])->save();

        $this->reset(['current_password', 'password', 'password_confirmation']);

        Notification::make()
            ->success()
            ->title('Admin password updated')
            ->body('The default password warning has been cleared.')
            ->send();

        return redirect()->to('/admin');
    }
}
