<?php

namespace App\Livewire;

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

class AssignSubjectsToClasses extends Component
{
    use HasNotifications;

    public $selectedClass = '';
    public $selectedSubject = '';
    public $alias = '';
    public $assignedSubjects = [];
    public $editingAlias = [];
    public $newAlias = [];

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

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

    public function updatedSelectedClass()
    {
        if ($this->selectedClass) {
            $this->loadAssignedSubjects();
        }
    }

    public function loadAssignedSubjects()
    {
        $this->assignedSubjects = $this->subjectService->getSubjectsForClass($this->selectedClass);
    }

    public function assign()
    {
        $this->validate([
            'selectedClass' => 'required|exists:school_classes,id',
            'selectedSubject' => 'required|exists:subjects,id',
            'alias' => 'nullable|string|max:255'
        ]);

        $subject = Subject::find($this->selectedSubject);
        $this->subjectService->attachSubjectToClass($subject, $this->selectedClass, $this->alias);
        
        $this->reset(['selectedSubject', 'alias']);
        $this->loadAssignedSubjects();
        
        $this->showToast('success', 'Subject assigned successfully!');
    }

    public function confirmRemove($subjectId)
    {
        $this->pendingAction = 'remove';
        $this->pendingSubjectId = $subjectId;
        $this->confirmAction('Remove Subject?', 'This will remove the subject from this class.');
    }

    public function confirmRemoveAlias($subjectId)
    {
        $this->pendingAction = 'removeAlias';
        $this->pendingSubjectId = $subjectId;
        $this->confirmAction('Remove Alias?', 'This will remove the custom alias for this subject.');
    }

    public function handleConfirmedAction()
    {
        if ($this->pendingAction === 'remove') {
            $this->removeSubject($this->pendingSubjectId);
        } elseif ($this->pendingAction === 'removeAlias') {
            $this->removeAlias($this->pendingSubjectId);
        }
        
        $this->pendingAction = null;
        $this->pendingSubjectId = null;
    }

    public function removeAlias($subjectId)
    {
        $subject = Subject::find($subjectId);
        $this->subjectService->removeAliasFromClass($subject, $this->selectedClass);
        
        $this->loadAssignedSubjects();
        $this->showToast('success', 'Subject alias removed successfully!');
    }

    public function removeSubject($subjectId)
    {
        $subject = Subject::find($subjectId);
        $this->subjectService->detachSubjectFromClass($subject, $this->selectedClass);
        
        $this->loadAssignedSubjects();
        $this->showToast('success', 'Subject removed successfully!');
    }
    
    public function editAlias($subjectId)
    {
        $this->editingAlias[$subjectId] = true;
        $subject = collect($this->assignedSubjects)->firstWhere('id', $subjectId);
        $this->newAlias[$subjectId] = $subject->schoolClasses->first()->pivot->alias ?? '';
    }
    
    public function saveAlias($subjectId, $alias = null)
    {
        $subject = Subject::find($subjectId);
        $aliasValue = $alias ?? ($this->newAlias[$subjectId] ?? '');
        $this->subjectService->updateAliasForClass($subject, $this->selectedClass, $aliasValue);
        
        $this->editingAlias[$subjectId] = false;
        unset($this->newAlias[$subjectId]);
        $this->loadAssignedSubjects();
        $this->showToast('success', 'Alias updated successfully!');
    }
    
    public function cancelEditAlias($subjectId)
    {
        $this->editingAlias[$subjectId] = false;
        unset($this->newAlias[$subjectId]);
    }

    public function render()
    {
        $classes = SchoolClass::orderBy('order')->get();
        
        $subjects = Subject::orderBy('name');
        if ($this->selectedClass) {
            $assignedSubjectIds = collect($this->assignedSubjects)->pluck('id');
            $subjects = $subjects->whereNotIn('id', $assignedSubjectIds);
        }
        $subjects = $subjects->get();
        
        return view('livewire.assign-subjects-to-classes', compact('classes', 'subjects'));
    }
}
