<?php

namespace App\Filament\User\Pages;

use App\Models\Profile;
use Exception;
use Filament\Actions\Action;
use Filament\Facades\Filament;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\FileUpload;
use Filament\Forms\Components\Section;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Concerns\InteractsWithForms;
use Filament\Forms\Contracts\HasForms;
use Filament\Forms\Form;
use Filament\Notifications\Notification;
use Filament\Pages\Page;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules\Password;
use Filament\Support\Enums\Alignment;

class EditProfile extends Page implements HasForms
{

    use InteractsWithForms;
    protected static string $view = 'edit-profile';
    protected static ?string $navigationIcon = 'heroicon-o-user';
    protected static ?int $navigationSort = 30;
    protected static ?string $navigationLabel = "Profil";
    public static string | Alignment $formActionsAlignment = Alignment::Right;


    // protected static bool $shouldRegisterNavigation = false;
    public ?array $profileData = [];
    public ?array $passwordData = [];
    public ?array $detailData = [];

    /**
     * Initializes the page by filling the forms with the user's current data.
     *
     * @return void
     */

    public function mount(): void
    {
        $this->fillForms();
    }
    /**
     * Get the forms for this page.
     *
     * @return array
     */
    protected function getForms(): array
    {
        return [
            'editProfileForm',
            'editPasswordForm',
        ];
    }

    /**
     * Form for editing the user's profile information.
     *
     * @param \Filament\Forms\Form $form
     * @return \Filament\Forms\Form
     */
    public function editProfileForm(Form $form): Form
    {
        return  $form
            ->schema([
                Section::make('Pengaturan Akun')
                    ->aside()
                    ->description('Perbarui informasi profil dan alamat email akun Anda.')
                    ->schema([
                        FileUpload::make('avatar_url')
                            ->label('Foto Profil')
                            ->image()
                            ->imageEditor()
                            ->avatar()
                            ->circleCropper(),
                        TextInput::make('name')
                            ->label('Nama')
                            ->required(),
                        TextInput::make('email')
                            ->email()
                            ->required()
                            ->unique(ignoreRecord: true),
                    ]),
            ])
            ->model($this->getUser())
            ->statePath('profileData');
    }
    /**
     * Form for editing the user's password.
     *
     * @param \Filament\Forms\Form $form
     * @return \Filament\Forms\Form
     */
    public function editPasswordForm(Form $form): Form
    {
        return  $form
            ->schema([
                Section::make('Ganti Kata Sandi')
                    ->aside()
                    ->description('Pastikan akun Anda menggunakan kata sandi minimal 8 karakter dan menggunakan kata sandi yang kuat tetap aman.')
                    ->schema([
                        TextInput::make('currentPassword')
                            ->label('Kata Sandi Sekarang')
                            ->password()
                            ->required()
                            ->currentPassword(),
                        TextInput::make('password')
                            ->label('Kata Sandi Baru')
                            ->password()
                            ->required()
                            ->rule(Password::default())
                            ->autocomplete('new-password')
                            ->dehydrateStateUsing(fn($state): string => Hash::make($state))
                            ->live(debounce: 500)
                            ->same('passwordConfirmation'),
                        TextInput::make('passwordConfirmation')
                            ->label('Konfirmasi Kata Sandi')
                            ->password()
                            ->required()
                            ->dehydrated(false),
                    ]),
            ])
            ->model($this->getUser())
            ->statePath('passwordData');
    }
    /**
     * Get the authenticated user as an Eloquent model.
     *
     * @return \Illuminate\Contracts\Auth\Authenticatable&\Illuminate\Database\Eloquent\Model
     *
     * @throws \Exception
     */
    protected function getUser(): Authenticatable & Model
    {
        $user = Filament::auth()->user();
        if (! $user instanceof Model) {
            throw new Exception('The authenticated user object must be an Eloquent model to allow the profile page to update it.');
        }
        return $user;
    }
    /**
     * Fill the forms with the user's current data.
     *
     * @return void
     */
    protected function fillForms(): void
    {
        $data = $this->getUser()->attributesToArray();
        $this->editProfileForm->fill($data);
        $this->editPasswordForm->fill();
    }
    /**
     * Returns the actions for the update profile form.
     *
     * @return array<int, \Filament\Actions\Action>
     */
    protected function getUpdateProfileFormActions(): array
    {
        return [
            Action::make('updateProfileAction')
                ->label(__('filament-panels::pages/auth/edit-profile.form.actions.save.label'))
                ->submit('updateProfile'),
        ];
    }
    /**
     * Returns the actions for the update profile form.
     *
     * @return array<int, \Filament\Actions\Action>
     */
    protected function getUpdateDetailFormActions(): array
    {
        return [
            Action::make('updateDetailAction')
                ->label(__('filament-panels::pages/auth/edit-profile.form.actions.save.label'))
                ->submit('updateDetail'),
        ];
    }
    /**
     * Returns the actions for the update password form.
     *
     * @return array<int, \Filament\Actions\Action>
     */
    protected function getUpdatePasswordFormActions(): array
    {
        return [
            Action::make('updatePasswordAction')
                ->label(__('filament-panels::pages/auth/edit-profile.form.actions.save.label'))
                ->submit('updatePassword'),
        ];
    }
    /**
     * Handle the user's profile information update request.
     *
     * @return void
     */
    public function updateProfile(): void
    {
        $data = $this->editProfileForm->getState();
        $this->handleRecordUpdate($this->getUser(), $data);
        $this->sendSuccessNotification();
    }
    /**
     * Handle the user's profile information update request.
     *
     * @return void
     */
    public function updatePassword(): void
    {
        $data = $this->editPasswordForm->getState();
        $this->handleRecordUpdate($this->getUser(), $data);
        if (request()->hasSession() && array_key_exists('password', $data)) {
            request()->session()->put(['password_hash_' . Filament::getAuthGuard() => $data['password']]);
        }
        $this->editPasswordForm->fill();
        $this->sendSuccessNotification();
    }
    /**
     * Update the given record with the given data.
     *
     * @param  \Illuminate\Database\Eloquent\Model  $record
     * @param  array  $data
     * @return \Illuminate\Database\Eloquent\Model
     */
    private function handleRecordUpdate(Model $record, array $data): Model
    {
        $record->update($data);
        return $record;
    }
    /**
     * Send a success notification that the user's profile has been saved.
     *
     * @return void
     */
    private function sendSuccessNotification(): void

    {
        Notification::make()
            ->success()
            ->title(__('filament-panels::pages/auth/edit-profile.notifications.saved.title'))
            ->send();
    }
}
