<?php

namespace App\Livewire\Forms;

use Illuminate\Support\Facades\Auth;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Storage;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Rules\Password as PasswordRule;
use Illuminate\Validation\ValidationException;
use Livewire\Attributes\Validate;
use Livewire\Component;
use Livewire\WithFileUploads;

class UserProfile extends Component
{
    use WithFileUploads;
    // Profile info
    public string $name = '';
    public string $email = '';
    public ?string $preferred_username = null;
    public ?string $avatar = null;
    public bool $auto_approve_apps = false;
    #[Validate('image|max:10000')]
    public $avatarUpload;
    // Password
    public string $current_password = '';
    public string $password = '';
    public string $password_confirmation = '';

    public function mount(): void
    {
        $this->name = Auth::user()->name;
        $this->email = Auth::user()->email;
        $this->preferred_username = Auth::user()->preferred_username;
        $this->avatar = Auth::user()->avatar;
        $this->auto_approve_apps = Auth::user()->auto_approve_apps;
    }

    /**
     * Update the profile information for the currently authenticated user.
     */
    public function updateProfileInformation(): void
    {
        $user = Auth::user();

        $validated = $this->validate([
            'name' => 'required|string|max:255',
            'email' => [
                'required',
                'string',
                'lowercase',
                'email',
                'max:255',
                Rule::unique(User::class)->ignore($user->id),
            ],
            'preferred_username' => 'string|max:255',
            'auto_approve_apps' => 'boolean'
        ]);

        $user->fill($validated);

        if (!empty($this->avatarUpload)) {
            if (!empty($user->avatar)) {
                Storage::disk('avatars')->delete($user->avatar);
            }
            $user->avatar = $this->avatarUpload->store(options: 'avatars');
        }

        $user->save();

        $this->dispatch('profile-updated', name: $user->name);
    }

    public function updatePassword(): void
    {
        try {
            $validated = $this->validate([
                'current_password' => ['required', 'string', 'current_password'],
                'password' => ['required', 'string', PasswordRule::defaults(), 'confirmed'],
            ]);
        } catch (ValidationException $e) {
            $this->reset('current_password', 'password', 'password_confirmation');

            throw $e;
        }

        Auth::user()->update([
            'password' => Hash::make($validated['password']),
        ]);

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

        $this->dispatch('password-updated');
    }

    public function render()
    {
        return view('livewire.forms.user-profile');
    }
}
