<?php

namespace App\Filament\Pages\Auth;

use Filament\Auth\Pages\EditProfile as BaseEditProfile;
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\Rule;
use Illuminate\Validation\Rules\Password;
use Illuminate\Validation\ValidationException;

class Profile extends BaseEditProfile
{
    protected static ?string $title = 'Edit Profile';
    protected static ?string $navigationLabel = 'Edit Profile';
    protected static bool $shouldRegisterNavigation = false;

    public static function getLabel(): string
    {
        return self::$title ?? parent::getLabel();
    }

    public function form(Schema $schema): Schema
    {
        $user = $this->getUser();

        return $schema->components([
            Section::make('User Information')
                ->schema([
                    TextInput::make('name')
                        ->label('Name')
                        ->required()
                        ->maxLength(255),
                    TextInput::make('email')
                        ->label('Email')
                        ->email()
                        ->required()
                        ->rules([
                            Rule::unique($user->getTable(), 'email')->ignore($user->getKey(), $user->getKeyName()),
                        ]),
                ]),
            Section::make('Change Password')
                ->description('To change your password, enter your current password first.')
                ->schema([
                    TextInput::make('password')
                        ->label('New Password')
                        ->password()
                        ->revealable()
                        ->dehydrated(fn (?string $state): bool => filled($state))
                        ->rules([
                            Password::min(8)->letters()->numbers(),
                        ]),
                    TextInput::make('passwordConfirmation')
                        ->label('Confirm New Password')
                        ->password()
                        ->same('password')
                        ->dehydrated(fn (?string $state): bool => filled($state)),
                    TextInput::make('currentPassword')
                        ->label('Current Password')
                        ->password()
                        ->revealable()
                        ->required(fn (Get $get): bool => filled($get('password')))
                        ->dehydrated(true),
                ]),
        ]);
    }

    protected function mutateFormDataBeforeSave(array $data): array
    {
        unset($data['passwordConfirmation']);

        return $data;
    }

    protected function handleRecordUpdate(Model $record, array $data): Model
    {
        if (filled($data['password'] ?? null)) {
            if (empty($data['currentPassword']) || ! Hash::check($data['currentPassword'], $record->password)) {
                throw ValidationException::withMessages([
                    'data.currentPassword' => 'The current password is incorrect.',
                ]);
            }

            $record->password = Hash::make($data['password']);
        }

        $record->name = $data['name'];
        $record->email = $data['email'];
        $record->save();

        return $record;
    }

    protected function getSavedNotification(): ?Notification
    {
        return Notification::make()
            ->success()
            ->title('Changes saved');
    }
}
