<?php

namespace App\Livewire;

use App\Models\SchoolSession;
use App\Services\SchoolSessionService;
use App\Traits\HasNotifications;
use Illuminate\Support\Str;
use Livewire\Component;

class SchoolSessionForm extends Component
{
    use HasNotifications;

    public $sessionId = null;
    public $name = '';
    public $start_year = '';
    public $end_year = '';
    public $start_date = '';
    public $end_date = '';
    public $next_session_start_date = '';
    public $is_active = false;
    public $description = '';
    public $ca_max_score = 40;
    public $exam_max_score = 60;
    public $ca_pass_mark = 20;
    public $exam_pass_mark = 30;

    // Grading system
    public $grade_a_min = 80;
    public $grade_b_min = 70;
    public $grade_c_min = 60;
    public $grade_d_min = 50;
    public $grade_e_min = 40;
    public $grade_f_min = 0;
    public $overall_pass_percentage = 50;

    protected $rules = [
        'name' => 'required|string|max:255',
        'start_year' => 'required|integer|min:2000|max:2100',
        'end_year' => 'required|integer|min:2000|max:2100|gt:start_year',
        'start_date' => 'nullable|date',
        'end_date' => 'nullable|date|after_or_equal:start_date',
        'next_session_start_date' => 'required|date|after:end_date',
        'is_active' => 'boolean',
        'description' => 'nullable|string',
        'ca_max_score' => 'required|integer|min:1|max:99',
        'exam_max_score' => 'required|integer|min:1|max:99',
        'ca_pass_mark' => 'required|integer|min:1',
        'exam_pass_mark' => 'required|integer|min:1',
        'grade_a_min' => 'required|integer|min:0|max:100',
        'grade_b_min' => 'required|integer|min:0|max:100',
        'grade_c_min' => 'required|integer|min:0|max:100',
        'grade_d_min' => 'required|integer|min:0|max:100',
        'grade_e_min' => 'required|integer|min:0|max:100',
        'grade_f_min' => 'required|integer|min:0|max:100',
        'overall_pass_percentage' => 'required|integer|min:1|max:100',
    ];

    public function mount($sessionId = null)
    {
        if ($sessionId) {
            $this->sessionId = $sessionId;
            $this->loadSession();
        }
    }

    public function loadSession()
    {
        $session = SchoolSession::findOrFail($this->sessionId);
        $this->name = $session->name;
        $this->start_year = $session->start_year;
        $this->end_year = $session->end_year;
        $this->start_date = $session->start_date?->format('Y-m-d');
        $this->end_date = $session->end_date?->format('Y-m-d');
        $this->next_session_start_date = $session->next_session_start_date?->format('Y-m-d');
        $this->is_active = $session->is_active;
        $this->description = $session->description;
        $this->ca_max_score = $session->ca_max_score;
        $this->exam_max_score = $session->exam_max_score;
        $this->ca_pass_mark = $session->ca_pass_mark;
        $this->exam_pass_mark = $session->exam_pass_mark;
        $this->grade_a_min = $session->grade_a_min ?? 80;
        $this->grade_b_min = $session->grade_b_min ?? 70;
        $this->grade_c_min = $session->grade_c_min ?? 60;
        $this->grade_d_min = $session->grade_d_min ?? 50;
        $this->grade_e_min = $session->grade_e_min ?? 40;
        $this->grade_f_min = $session->grade_f_min ?? 0;
        $this->overall_pass_percentage = $session->overall_pass_percentage ?? 50;
    }

    public function updatedCaMaxScore()
    {
        $this->ca_max_score = max(0, (int)$this->ca_max_score);
        $this->exam_max_score = max(0, 100 - $this->ca_max_score);
        $this->validateOnly('ca_max_score');
        $this->validateOnly('exam_max_score');
    }

    public function updatedExamMaxScore()
    {
        $this->exam_max_score = max(0, (int)$this->exam_max_score);
        $this->ca_max_score = max(0, 100 - $this->exam_max_score);
        $this->validateOnly('ca_max_score');
        $this->validateOnly('exam_max_score');
    }

    public function save()
    {
        $this->validate();

        // Additional validation
        if ((int)$this->ca_max_score + (int)$this->exam_max_score !== 100) {
            $this->addError('ca_max_score', 'C.A and Exam scores must sum to 100');
            $this->addError('exam_max_score', 'C.A and Exam scores must sum to 100');
            return;
        }

        if ((int)$this->ca_pass_mark > (int)$this->ca_max_score) {
            $this->addError('ca_pass_mark', 'C.A pass mark cannot exceed C.A maximum score');
            return;
        }

        if ((int)$this->exam_pass_mark > (int)$this->exam_max_score) {
            $this->addError('exam_pass_mark', 'Exam pass mark cannot exceed Exam maximum score');
            return;
        }

        // Validate grading system
        $grades = [
            'A' => (int)$this->grade_a_min,
            'B' => (int)$this->grade_b_min,
            'C' => (int)$this->grade_c_min,
            'D' => (int)$this->grade_d_min,
            'E' => (int)$this->grade_e_min,
            'F' => (int)$this->grade_f_min
        ];

        $previous = 100;
        foreach ($grades as $grade => $min) {
            if ($min >= $previous) {
                $this->addError('grade_' . strtolower($grade) . '_min', 'Grade ' . $grade . ' minimum must be less than the previous grade');
                return;
            }
            $previous = $min;
        }

        $sessionService = app(SchoolSessionService::class);
        $data = [
            'name' => $this->name,
            'start_year' => $this->start_year,
            'end_year' => $this->end_year,
            'start_date' => $this->start_date ?: null,
            'end_date' => $this->end_date ?: null,
            'next_session_start_date' => $this->next_session_start_date ?: null,
            'is_active' => $this->is_active,
            'description' => $this->description,
            'ca_max_score' => $this->ca_max_score,
            'exam_max_score' => $this->exam_max_score,
            'ca_pass_mark' => $this->ca_pass_mark,
            'exam_pass_mark' => $this->exam_pass_mark,
            'grade_a_min' => $this->grade_a_min,
            'grade_b_min' => $this->grade_b_min,
            'grade_c_min' => $this->grade_c_min,
            'grade_d_min' => $this->grade_d_min,
            'grade_e_min' => $this->grade_e_min,
            'grade_f_min' => $this->grade_f_min,
            'overall_pass_percentage' => $this->overall_pass_percentage,
        ];
        
        // Only add slug for new sessions
        if (!$this->sessionId) {
            $data['slug'] = Str::slug($this->name) . '-' . Str::random(3);
        }

        if ($this->sessionId) {
            $session = SchoolSession::findOrFail($this->sessionId);
            $sessionService->updateSession($session, $data);
            session()->flash('toast', ['type' => 'success', 'message' => 'School session updated successfully!']);
        } else {
            $sessionService->createSession($data);
            session()->flash('toast', ['type' => 'success', 'message' => 'School session created successfully!']);
        }

        return redirect()->route('school-sessions.index');
    }

    public function render()
    {
        return view('livewire.school-session-form');
    }
}
