<?php

namespace App\Filament\Pages;

use App\Filament\Support\SystemNotification;
use Filament\Auth\Pages\EditProfile;
use Filament\Facades\Filament;
use Filament\Forms\Components\TextInput;
use Filament\Notifications\Notification;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Schemas\Schema;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules\Password;

class Profile extends EditProfile
{
    protected bool $hasPasswordChanged = false;

    public function form(Schema $schema): Schema
    {
        return $schema
            ->components([
                Section::make('Akun')
                    ->schema([
                        TextInput::make('name')
                            ->label('Nama')
                            ->placeholder('John Doe')
                            ->autocomplete(false)
                            ->autofocus()
                            ->required()
                            ->maxLength(100),

                        TextInput::make('email')
                            ->label('Alamat Surel')
                            ->placeholder('johndoe@puskesmas.com')
                            ->autocomplete(false)
                            ->required()
                            ->maxLength(254)
                            ->unique(ignoreRecord: true)
                            ->email()
                            ->live(),

                        TextInput::make('username')
                            ->label('Nama Pengguna')
                            ->placeholder('johndoe')
                            ->autocomplete(false)
                            ->required()
                            ->minLength(5)
                            ->maxLength(20)
                            ->regex('/^[a-zA-Z0-9_.-]+$/')
                            ->unique(ignoreRecord: true),
                    ]),

                Section::make('Kata Sandi')
                    ->schema([
                        TextInput::make('new_password')
                            ->label(__('filament-panels::auth/pages/edit-profile.form.password.label'))
                            ->validationAttribute(__('filament-panels::auth/pages/edit-profile.form.password.validation_attribute'))
                            ->password()
                            ->revealable(filament()->arePasswordsRevealable())
                            ->rule(Password::default())
                            ->showAllValidationMessages()
                            ->autocomplete('new-password')
                            ->dehydrated(fn ($state): bool => filled($state))
                            ->dehydrateStateUsing(fn ($state): string => Hash::make($state))
                            ->live(debounce: 500)
                            ->same('passwordConfirmation')
                            ->placeholder('********'),

                        TextInput::make('passwordConfirmation')
                            ->label(__('filament-panels::auth/pages/edit-profile.form.password_confirmation.label'))
                            ->validationAttribute(__('filament-panels::auth/pages/edit-profile.form.password_confirmation.validation_attribute'))
                            ->password()
                            ->autocomplete('new-password')
                            ->revealable(filament()->arePasswordsRevealable())
                            ->required()
                            ->visible(fn (Get $get): bool => filled($get('new_password')))
                            ->dehydrated(false)
                            ->placeholder('********'),

                        TextInput::make('currentPassword')
                            ->label(__('filament-panels::auth/pages/edit-profile.form.current_password.label'))
                            ->validationAttribute(__('filament-panels::auth/pages/edit-profile.form.current_password.validation_attribute'))
                            ->belowContent(__('filament-panels::auth/pages/edit-profile.form.current_password.below_content'))
                            ->password()
                            ->autocomplete('current-password')
                            ->currentPassword(guard: Filament::getAuthGuard())
                            ->revealable(filament()->arePasswordsRevealable())
                            ->required()
                            ->visible(fn (Get $get): bool => filled($get('new_password')) || ($get('email') !== $this->getUser()->getAttributeValue('email')))
                            ->dehydrated(false)
                            ->placeholder('********'),
                    ]),
            ]);
    }

    protected function getSavedNotification(): ?Notification
    {
        return SystemNotification::update();
    }

    protected function handleRecordUpdate(Model $record, array $data): Model
    {
        $shouldLogout = false;
        if (isset($data['new_password'])) {
            $data['password'] = $data['new_password'];
            unset($data['new_password']);
            $shouldLogout = true;
            $this->hasPasswordChanged = true;
        }

        $record->update($data);

        if ($shouldLogout) {
            auth()->logout();
        }

        return $record;
    }
}
