<?php

declare(strict_types=1);

namespace App\Livewire\Admin\Profile;

use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Storage;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Rule;
use Livewire\Component;
use Livewire\WithFileUploads;

#[Layout('layouts.admin')]
final class Edit extends Component
{
    use WithFileUploads;

    public User $user;

    #[Rule('required|string|max:255')]
    public string $name = '';

    #[Rule('required|email|max:255')]
    public string $email = '';

    #[Rule('nullable|string|max:255')]
    public ?string $phone = null;

    #[Rule('nullable|string|max:1000')]
    public ?string $bio = null;

    public $profilePicture;

    // Password change fields
    #[Rule('nullable|string|min:8|confirmed')]
    public string $currentPassword = '';

    #[Rule('nullable|string|min:8')]
    public string $newPassword = '';

    #[Rule('nullable|string|min:8')]
    public string $newPasswordConfirmation = '';

    public function mount(): void
    {
        $this->user = auth()->user();
        $this->name = $this->user->name;
        $this->email = $this->user->email;
        $this->phone = $this->user->phone;
        $this->bio = $this->user->bio;
    }

    public function updateProfile(): void
    {
        $this->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email|max:255|unique:users,email,'.$this->user->id,
            'phone' => 'nullable|string|max:255',
            'bio' => 'nullable|string|max:1000',
            'profilePicture' => 'nullable|image|max:2048',
        ]);

        $updateData = [
            'name' => $this->name,
            'email' => $this->email,
            'phone' => $this->phone,
            'bio' => $this->bio,
        ];

        // Handle profile picture upload
        if ($this->profilePicture) {
            // Delete old profile picture if it exists
            if ($this->user->profile_picture && Storage::disk('public')->exists($this->user->profile_picture)) {
                Storage::disk('public')->delete($this->user->profile_picture);
            }

            // Store new profile picture
            $path = $this->profilePicture->store('profile-pictures', 'public');
            $updateData['profile_picture'] = $path;
        }

        $this->user->update($updateData);

        activity()
            ->causedBy($this->user)
            ->performedOn($this->user)
            ->withProperties([
                'user_id' => $this->user->id,
                'changes' => $updateData,
            ])
            ->log('profile_updated');

        session()->flash('success', 'Profile updated successfully!');
    }

    public function changePassword(): void
    {
        $this->validate([
            'currentPassword' => 'required|string',
            'newPassword' => 'required|string|min:8|confirmed',
            'newPasswordConfirmation' => 'required|string|min:8',
        ]);

        // Verify current password
        if (! Hash::check($this->currentPassword, $this->user->password)) {
            $this->addError('currentPassword', 'The current password is incorrect.');

            return;
        }

        // Update password
        $this->user->update([
            'password' => Hash::make($this->newPassword),
        ]);

        activity()
            ->causedBy($this->user)
            ->performedOn($this->user)
            ->withProperties([
                'user_id' => $this->user->id,
                'action' => 'password_changed',
            ])
            ->log('password_changed');

        // Clear password fields
        $this->currentPassword = '';
        $this->newPassword = '';
        $this->newPasswordConfirmation = '';

        session()->flash('success', 'Password changed successfully!');
    }

    public function removeProfilePicture(): void
    {
        if ($this->user->profile_picture && Storage::disk('public')->exists($this->user->profile_picture)) {
            Storage::disk('public')->delete($this->user->profile_picture);
        }

        $this->user->update(['profile_picture' => null]);

        activity()
            ->causedBy($this->user)
            ->performedOn($this->user)
            ->withProperties([
                'user_id' => $this->user->id,
                'action' => 'profile_picture_removed',
            ])
            ->log('profile_picture_removed');

        session()->flash('success', 'Profile picture removed successfully!');
    }

    public function render()
    {
        return view('livewire.admin.profile.edit');
    }
}
