<?php

namespace App\Livewire\Admin;

use App\Models\User;
use App\Services\FlashMessageService;
use Livewire\Component;
use Illuminate\Support\Facades\Hash;
use Spatie\Permission\Models\Role;

class UserForm extends Component
{
    // Properties for form data
    public $name = '';
    public $email = '';
    public $password = '';
    public $password_confirmation = '';
    public $role = '';
    public $phone = '';
    public $address = '';
    public $date_of_birth = '';
    public $is_active = true;

    // Properties for component state
    public $editMode = false;
    public $userId = null;
    public $availableRoles = [];

    protected $rules = [
        'name' => 'required|string|max:255',
        'email' => 'required|email|unique:users,email',
        'password' => 'required|min:8|confirmed',
        'role' => 'required|string',
        'phone' => 'nullable|string|max:20',
        'address' => 'nullable|string|max:500',
        'date_of_birth' => 'nullable|date|before_or_equal:today',
        'is_active' => 'boolean',
    ];

    protected $messages = [
        'name.required' => 'Name is required.',
        'email.required' => 'Email is required.',
        'email.email' => 'Please enter a valid email address.',
        'email.unique' => 'This email is already taken.',
        'password.required' => 'Password is required.',
        'password.min' => 'Password must be at least 8 characters.',
        'password.confirmed' => 'Password confirmation does not match.',
        'role.required' => 'Role is required.',
    ];

    public function mount($userId = null)
    {
        $this->availableRoles = Role::all();
        
        if ($userId) {
            $this->editMode = true;
            $this->userId = $userId;
            $user = User::findOrFail($userId);
            
            $this->name = $user->name;
            $this->email = $user->email;
            $this->role = $user->roles->first()?->name ?? '';
            $this->phone = $user->phone ?? '';
            $this->address = $user->address ?? '';
            $this->date_of_birth = $user->date_of_birth ? $user->date_of_birth->format('Y-m-d') : '';
            $this->is_active = $user->is_active;
        }
    }

    public function updated($propertyName)
    {
        if ($this->editMode) {
            $this->rules['email'] = 'required|email|unique:users,email,' . $this->userId;
            $this->rules['password'] = 'nullable|min:8|confirmed';
        }

        // Handle empty date values
        if ($propertyName === 'date_of_birth' && empty($this->date_of_birth)) {
            $this->date_of_birth = null;
        }

        $this->validateOnly($propertyName);
    }

    public function save()
    {
        // Check permissions
        if ($this->editMode && !auth()->user()->can('users.edit')) {
            FlashMessageService::insufficientPermissions();
            
            // Dispatch flash message event
            $this->dispatch('flashMessage', 'error', 'You do not have permission to edit users.', 'Insufficient Permissions', 8000);
            
            return;
        } elseif (!$this->editMode && !auth()->user()->can('users.create')) {
            FlashMessageService::insufficientPermissions();
            
            // Dispatch flash message event
            $this->dispatch('flashMessage', 'error', 'You do not have permission to create users.', 'Insufficient Permissions', 8000);
            
            return;
        }

        if ($this->editMode) {
            $this->rules['email'] = 'required|email|unique:users,email,' . $this->userId;
            $this->rules['password'] = 'nullable|min:8|confirmed';
        }

        $this->validate();
        

        $userData = [
            'name' => $this->name,
            'email' => $this->email,
            'phone' => $this->phone ?: null,
            'address' => $this->address ?: null,
            'date_of_birth' => $this->date_of_birth ?: null,
            'is_active' => $this->is_active,
        ];
        

        try {
            if ($this->editMode) {
                if (!empty($this->password)) {
                    $userData['password'] = Hash::make($this->password);
                }
                
                $user = User::findOrFail($this->userId);
                $user->update($userData);
                
                // Update role
                if ($this->role) {
                    $user->syncRoles([$this->role]);
                }
                
                FlashMessageService::userUpdated();
                
                // Dispatch flash message event
                $this->dispatch('flashMessage', 'success', 'User updated successfully!', 'Success', 5000);
            } else {
                $userData['password'] = Hash::make($this->password);
                $user = User::create($userData);
                
                // Assign role
                if ($this->role) {
                    $user->assignRole($this->role);
                }
                
                FlashMessageService::userCreated();
                
                // Dispatch flash message event
                $this->dispatch('flashMessage', 'success', 'User created successfully!', 'Success', 5000);
            }

            return redirect()->route('admin.users');
            
        } catch (\Exception $e) {
            if ($this->editMode) {
                FlashMessageService::userUpdateFailed();
                
                // Dispatch flash message event
                $this->dispatch('flashMessage', 'error', 'Failed to update user. Please try again.', 'Error', 8000);
            } else {
                FlashMessageService::userCreateFailed();
                
                // Dispatch flash message event
                $this->dispatch('flashMessage', 'error', 'Failed to create user. Please try again.', 'Error', 8000);
            }
            
            // Log the error for debugging
            \Log::error('User form save error: ' . $e->getMessage());
        }
    }

    public function cancel()
    {
        return redirect()->route('admin.users');
    }

    public function render()
    {
        return view('livewire.admin.user-form');
    }
}