<?php

namespace App\Livewire;

use App\Models\Subject;
use App\Services\SubjectService;
use App\Traits\HasNotifications;
use Livewire\Component;
use Livewire\WithPagination;

class SubjectsList extends Component
{
    use WithPagination, HasNotifications;

    public $search = '';
    public $editingSubject = null;
    public $name = '';

    protected $subjectService;
    protected $listeners = ['action-confirmed' => 'handleConfirmedAction', 'subjectRestored' => '$refresh', 'subjectCreated' => '$refresh'];
    public $pendingAction = null;
    public $pendingSubjectId = null;

    public function boot(SubjectService $subjectService)
    {
        $this->subjectService = $subjectService;
    }

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

    public function edit(Subject $subject)
    {
        $this->editingSubject = $subject->fresh();
        $this->name = $this->editingSubject->name;
    }

    public function update()
    {
        $this->validate(['name' => 'required|string|max:255']);
        
        $this->subjectService->updateSubject($this->editingSubject, ['name' => $this->name]);
        
        $this->reset(['editingSubject', 'name']);
        $this->showToast('success', 'Subject updated successfully!');
        $this->dispatch('$refresh');
    }

    public function cancelEdit()
    {
        $this->reset(['editingSubject', 'name']);
    }

    public function confirmDelete($subjectId)
    {
        $this->pendingAction = 'delete';
        $this->pendingSubjectId = $subjectId;
        $this->confirmAction('Delete Subject?', 'This action cannot be undone!');
    }

    public function handleConfirmedAction()
    {
        if ($this->pendingAction === 'delete') {
            $this->deleteSubject($this->pendingSubjectId);
        }
        
        $this->pendingAction = null;
        $this->pendingSubjectId = null;
    }

    public function deleteSubject($subjectId)
    {
        $subject = Subject::find($subjectId);
        $this->subjectService->deleteSubject($subject);
        $this->showToast('success', 'Subject deleted successfully!');
        $this->dispatch('subjectDeleted');
    }

    public function render()
    {
        $subjects = Subject::where('name', 'like', '%' . $this->search . '%')
                          ->orderBy('name')
                          ->paginate(10);

        return view('livewire.subjects-list', compact('subjects'));
    }
}
