<?php

namespace App\Livewire;

use App\Models\Batch;
use App\Services\BatchService;
use App\Traits\HasNotifications;
use Livewire\Component;
use Livewire\WithPagination;

class BatchesTable extends Component
{
    use HasNotifications, WithPagination;

    public $search = '';
    public $perPage = 10;
    public $classFilter = '';
    public $statusFilter = 'active'; // 'active', 'inactive', 'graduated', 'all'

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

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

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

    public function toggleStatus($batchId, BatchService $batchService)
    {
        try {
            $batch = Batch::findOrFail($batchId);
            $batchService->toggleStatus($batch);
            $this->showToast('success', 'Batch status updated successfully!');
        } catch (\Exception $e) {
            $this->showToast('error', 'An error occurred while updating the batch status.');
        }
    }

    public function toggleGraduation($batchId)
    {
        try {
            $batch = Batch::findOrFail($batchId);
            $newGraduatedStatus = !$batch->graduated;
            $batch->update([
                'graduated' => $newGraduatedStatus,
                'graduated_at' => $newGraduatedStatus ? now()->year : null
            ]);
            $status = $batch->graduated ? 'marked as graduated' : 'unmarked as graduated';
            session()->flash('toast', ['type' => 'success', 'message' => "Batch {$status} successfully!"]);
        } catch (\Exception $e) {
            session()->flash('toast', ['type' => 'error', 'message' => 'An error occurred while updating graduation status.']);
        }
    }

    public function deleteBatch($batchId, BatchService $batchService)
    {
        try {
            $batch = Batch::findOrFail($batchId);
            $batchService->delete($batch);
            session()->flash('toast', ['type' => 'success', 'message' => 'Batch deleted successfully!']);
            return redirect()->route('batches.index');
        } catch (\Exception $e) {
            $this->showToast('error', 'An error occurred while deleting the batch.');
        }
    }

    public function render(BatchService $batchService)
    {
        $batches = Batch::with(['schoolClass', 'students'])
            ->when($this->search, function ($query) {
                $query->where('name', 'like', '%' . $this->search . '%')
                    ->orWhereHas('schoolClass', function ($q) {
                        $q->where('name', 'like', '%' . $this->search . '%');
                    });
            })
            ->when($this->classFilter, function ($query) {
                $query->where('school_class_id', $this->classFilter);
            })
            ->when($this->statusFilter === 'active', function ($query) {
                $query->where('graduated', false)->where('is_active', true);
            })
            ->when($this->statusFilter === 'inactive', function ($query) {
                $query->where('is_active', false);
            })
            ->when($this->statusFilter === 'graduated', function ($query) {
                $query->where('graduated', true);
            })
            ->orderBy('name')
            ->paginate($this->perPage);

        $classes = \App\Models\SchoolClass::orderBy('alias')->get();

        return view('livewire.batches-table', compact('batches', 'classes'));
    }
}
