<?php

namespace App\Livewire\Evaluations;

use App\Domain\Training\Models\EvaluationCriterion;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Component;
use Livewire\WithPagination;

#[Layout('layouts.app')]
#[Title('معايير التقييم')]
class EvaluationCriteriaList extends Component
{
    use WithPagination;

    public string $search = '';

    // Form fields for create/edit
    public bool $showForm = false;
    public ?int $editingId = null;
    public string $name_ar = '';
    public string $name = '';
    public string $description_ar = '';
    public string $category = '';
    public int $max_score = 10;
    public int $sort_order = 0;
    public bool $is_active = true;

    public function mount(): void
    {
        $this->authorize('evaluations.manage');
    }

    public function updatedSearch(): void
    {
        $this->resetPage();
    }

    public function openForm(?int $id = null): void
    {
        $this->resetForm();
        if ($id) {
            $criterion = EvaluationCriterion::findOrFail($id);
            $this->editingId = $criterion->id;
            $this->name_ar = $criterion->name_ar;
            $this->name = $criterion->name ?? '';
            $this->description_ar = $criterion->description_ar ?? '';
            $this->category = $criterion->category ?? '';
            $this->max_score = $criterion->max_score;
            $this->sort_order = $criterion->sort_order ?? 0;
            $this->is_active = $criterion->is_active;
        }
        $this->showForm = true;
    }

    public function closeForm(): void
    {
        $this->showForm = false;
        $this->resetForm();
    }

    private function resetForm(): void
    {
        $this->editingId = null;
        $this->name_ar = '';
        $this->name = '';
        $this->description_ar = '';
        $this->category = '';
        $this->max_score = 10;
        $this->sort_order = 0;
        $this->is_active = true;
    }

    public function save(): void
    {
        $this->validate([
            'name_ar' => 'required|string|max:255',
            'name' => 'nullable|string|max:255',
            'description_ar' => 'nullable|string|max:500',
            'category' => 'nullable|string|max:100',
            'max_score' => 'required|integer|min:1|max:100',
            'sort_order' => 'required|integer|min:0',
        ], [
            'name_ar.required' => __('اسم المعيار بالعربية مطلوب'),
            'max_score.required' => __('الدرجة القصوى مطلوبة'),
            'max_score.min' => __('الدرجة القصوى يجب أن تكون 1 على الأقل'),
        ]);

        $data = [
            'academy_id' => app('current_academy')->id,
            'name_ar' => $this->name_ar,
            'name' => $this->name ?: null,
            'description_ar' => $this->description_ar ?: null,
            'category' => $this->category ?: null,
            'max_score' => $this->max_score,
            'sort_order' => $this->sort_order,
            'is_active' => $this->is_active,
        ];

        if ($this->editingId) {
            EvaluationCriterion::where('id', $this->editingId)->update($data);
            session()->flash('success', __('تم تحديث المعيار بنجاح'));
        } else {
            EvaluationCriterion::create($data);
            session()->flash('success', __('تم إنشاء المعيار بنجاح'));
        }

        $this->closeForm();
    }

    public function toggleActive(int $id): void
    {
        $criterion = EvaluationCriterion::findOrFail($id);
        $criterion->update(['is_active' => !$criterion->is_active]);
    }

    public function delete(int $id): void
    {
        EvaluationCriterion::findOrFail($id)->delete();
        session()->flash('success', __('تم حذف المعيار بنجاح'));
    }

    public function render()
    {
        $query = EvaluationCriterion::query()
            ->when($this->search, fn ($q) => $q->where('name_ar', 'ilike', "%{$this->search}%"))
            ->orderBy('sort_order')
            ->orderBy('name_ar');

        return view('livewire.evaluations.evaluation-criteria-list', [
            'criteria' => $query->paginate(20),
        ]);
    }
}
