<?php

namespace App\Livewire\Admin;

use App\Models\LearnerForm;
use App\Services\FlashMessageService;
use Livewire\Component;
use Livewire\WithPagination;
use Illuminate\Support\Facades\Auth;

class LearnerFormManagement extends Component
{
    use WithPagination;

    public $search = '';
    public $statusFilter = '';
    public $sortBy = 'created_at';
    public $sortDirection = 'desc';
    public $perPage = 10;

    protected $queryString = [
        'search' => ['except' => ''],
        'statusFilter' => ['except' => ''],
        'sortBy' => ['except' => 'created_at'],
        'sortDirection' => ['except' => 'desc'],
        'perPage' => ['except' => 10],
    ];

    public function mount()
    {
        // Check permissions
        if (!Auth::user()->can('learners.view')) {
            abort(403, 'Unauthorized access to learner forms.');
        }
    }

    public function updatingSearch()
    {
        $this->resetPage();
    }

    public function updatingStatusFilter()
    {
        $this->resetPage();
    }

    public function sortBy($field)
    {
        if ($this->sortBy === $field) {
            $this->sortDirection = $this->sortDirection === 'asc' ? 'desc' : 'asc';
        } else {
            $this->sortDirection = 'asc';
        }
        $this->sortBy = $field;
    }

    public function toggleStatus($formId)
    {
        // Check permissions
        if (!Auth::user()->can('learners.edit')) {
            FlashMessageService::error('You do not have permission to edit learner forms.', 'Insufficient Permissions');
            $this->dispatch('flashMessage', 'error', 'You do not have permission to edit learner forms.', 'Insufficient Permissions', 8000);
            return;
        }

        try {
            $form = LearnerForm::findOrFail($formId);
            $form->is_active = !$form->is_active;
            $form->save();

            FlashMessageService::success('Form status updated successfully!', 'Status Updated');
            $this->dispatch('flashMessage', 'success', 'Form status updated successfully!', 'Status Updated', 5000);
        } catch (\Exception $e) {
            FlashMessageService::error('Failed to update form status. Please try again.', 'Update Failed');
            $this->dispatch('flashMessage', 'error', 'Failed to update form status. Please try again.', 'Update Failed', 8000);
            \Log::error('Form status update error: ' . $e->getMessage());
        }
    }

    public function deleteForm($formId)
    {
        // Check permissions
        if (!Auth::user()->can('learners.delete')) {
            FlashMessageService::error('You do not have permission to delete learner forms.', 'Insufficient Permissions');
            $this->dispatch('flashMessage', 'error', 'You do not have permission to delete learner forms.', 'Insufficient Permissions', 8000);
            return;
        }

        try {
            $form = LearnerForm::findOrFail($formId);
            $form->delete(); // Soft delete

            FlashMessageService::success('Form deleted successfully!', 'Form Deleted');
            $this->dispatch('flashMessage', 'success', 'Form deleted successfully!', 'Form Deleted', 5000);
        } catch (\Exception $e) {
            FlashMessageService::error('Failed to delete form. Please try again.', 'Delete Failed');
            $this->dispatch('flashMessage', 'error', 'Failed to delete form. Please try again.', 'Delete Failed', 8000);
            \Log::error('Form deletion error: ' . $e->getMessage());
        }
    }

    public function render()
    {
        $forms = LearnerForm::with('creator', 'fields')
            ->when($this->search, function ($query) {
                $query->where('name', 'like', '%' . $this->search . '%')
                      ->orWhere('description', 'like', '%' . $this->search . '%');
            })
            ->when($this->statusFilter, function ($query) {
                if ($this->statusFilter === 'active') {
                    $query->where('is_active', true);
                } elseif ($this->statusFilter === 'inactive') {
                    $query->where('is_active', false);
                }
            })
            ->orderBy($this->sortBy, $this->sortDirection)
            ->paginate($this->perPage);

        return view('livewire.admin.learner-form-management', [
            'forms' => $forms,
        ]);
    }
}