<?php

namespace App\Livewire\Admin;

use App\Models\Quiz;
use App\Models\QuizQuestion;
use Livewire\Component;
use Illuminate\Support\Facades\Auth;

class QuestionForm extends Component
{
    public $quiz;
    public $question;
    public $questionId;
    public $questionType;
    public $questionText;
    public $options = [];
    public $correctAnswer = [];
    public $scorePoints = 1;
    public $feedback = '';
    public $isRequired = true;
    public $isActive = true;
    public $order = 0;
    public $metadata = [];
    public $editMode = false;

    protected $rules = [
        'questionType' => 'required|string|in:MULTIPLE_CHOICE,TRUE_FALSE,FILL_BLANK,SHORT_ANSWER,ESSAY,MATCH,ORDER,MATRIX,FILE_UPLOAD,DATE,CODE,NUMERIC,RATING',
        'questionText' => 'required|string|max:5000',
        'scorePoints' => 'required|numeric|min:0.1|max:100',
        'isRequired' => 'boolean',
        'isActive' => 'boolean',
        'order' => 'required|integer|min:1',
    ];

    public function mount(Quiz $quiz, $question = null)
    {
        $this->quiz = $quiz;
        $this->question = $question;
        $this->editMode = $question !== null;

        if ($this->editMode) {
            $this->questionId = $question->id;
            $this->questionType = $question->type;
            $this->questionText = $question->question_text;
            $this->options = $question->question_data['options'] ?? [];
            $this->correctAnswer = $question->answer_data['correct'] ?? [];
            $this->scorePoints = $question->score_points;
            $this->feedback = $question->question_data['feedback'] ?? $question->metadata['feedback'] ?? '';
            $this->isRequired = $question->is_required ?? true;
            $this->isActive = $question->is_active ?? true;
            $this->order = $question->order ?? 0;
            $this->metadata = $question->metadata ?? [];
        } else {
            $this->questionType = 'MULTIPLE_CHOICE';
            $this->scorePoints = 1;
            $this->isRequired = true;
            $this->isActive = true;
            $this->order = ($this->quiz->allQuestions()->max('order') ?? 0) + 1;
            $this->initializeQuestionType();
        }
    }

    public function updatedQuestionType($value)
    {
        $this->initializeQuestionType();
    }

    protected function initializeQuestionType()
    {
        switch ($this->questionType) {
            case 'MULTIPLE_CHOICE':
                $this->options = [
                    ['id' => 1, 'text' => '', 'is_correct' => false],
                    ['id' => 2, 'text' => '', 'is_correct' => false],
                    ['id' => 3, 'text' => '', 'is_correct' => false],
                    ['id' => 4, 'text' => '', 'is_correct' => false],
                ];
                $this->correctAnswer = [];
                break;

            case 'TRUE_FALSE':
                $this->options = [
                    ['id' => 1, 'text' => 'True', 'value' => true],
                    ['id' => 2, 'text' => 'False', 'value' => false],
                ];
                $this->correctAnswer = ['value' => true];
                break;

            case 'FILL_BLANK':
            case 'SHORT_ANSWER':
            case 'ESSAY':
                $this->options = [];
                $this->correctAnswer = ['text' => ''];
                break;

            case 'MATCH':
                $this->options = [
                    'left_items' => [
                        ['id' => 1, 'text' => ''],
                        ['id' => 2, 'text' => ''],
                    ],
                    'right_items' => [
                        ['id' => 1, 'text' => ''],
                        ['id' => 2, 'text' => ''],
                    ],
                ];
                $this->correctAnswer = ['pairs' => []];
                break;

            case 'ORDER':
                $this->options = [
                    ['id' => 1, 'text' => ''],
                    ['id' => 2, 'text' => ''],
                    ['id' => 3, 'text' => ''],
                ];
                $this->correctAnswer = ['order' => [1, 2, 3]];
                break;

            case 'MATRIX':
                $this->options = [
                    'rows' => [
                        ['id' => 1, 'text' => ''],
                        ['id' => 2, 'text' => ''],
                    ],
                    'columns' => [
                        ['id' => 1, 'text' => ''],
                        ['id' => 2, 'text' => ''],
                    ],
                ];
                $this->correctAnswer = ['matrix' => []];
                break;

            case 'FILE_UPLOAD':
                $this->options = [
                    'allowed_types' => ['pdf', 'doc', 'docx', 'txt'],
                    'max_size' => 5, // MB
                ];
                $this->correctAnswer = [];
                break;

            case 'DATE':
                $this->options = [
                    'format' => 'Y-m-d',
                    'min_date' => null,
                    'max_date' => null,
                ];
                $this->correctAnswer = ['date' => ''];
                break;

            case 'CODE':
                $this->options = [
                    'language' => 'javascript',
                    'theme' => 'default',
                    'max_length' => 5000,
                ];
                $this->correctAnswer = ['code' => ''];
                break;

            case 'NUMERIC':
                $this->options = [
                    'min_value' => null,
                    'max_value' => null,
                    'decimal_places' => 2,
                ];
                $this->correctAnswer = ['value' => 0];
                break;

            case 'RATING':
                $this->options = [
                    'min_rating' => 1,
                    'max_rating' => 5,
                    'step' => 1,
                    'labels' => ['Poor', 'Fair', 'Good', 'Very Good', 'Excellent'],
                ];
                $this->correctAnswer = ['rating' => 3];
                break;
        }
    }

    public function addOption()
    {
        if (in_array($this->questionType, ['MULTIPLE_CHOICE', 'ORDER'])) {
            $maxId = max(array_column($this->options, 'id')) + 1;
            $this->options[] = ['id' => $maxId, 'text' => '', 'is_correct' => false];
        } elseif ($this->questionType === 'MATCH') {
            $maxLeftId = max(array_column($this->options['left_items'], 'id')) + 1;
            $maxRightId = max(array_column($this->options['right_items'], 'id')) + 1;
            $this->options['left_items'][] = ['id' => $maxLeftId, 'text' => ''];
            $this->options['right_items'][] = ['id' => $maxRightId, 'text' => ''];
        } elseif ($this->questionType === 'MATRIX') {
            $maxRowId = max(array_column($this->options['rows'], 'id')) + 1;
            $maxColId = max(array_column($this->options['columns'], 'id')) + 1;
            $this->options['rows'][] = ['id' => $maxRowId, 'text' => ''];
            $this->options['columns'][] = ['id' => $maxColId, 'text' => ''];
        }
    }

    public function removeOption($index)
    {
        if (in_array($this->questionType, ['MULTIPLE_CHOICE', 'ORDER'])) {
            unset($this->options[$index]);
            $this->options = array_values($this->options);
        } elseif ($this->questionType === 'MATCH') {
            unset($this->options['left_items'][$index]);
            unset($this->options['right_items'][$index]);
            $this->options['left_items'] = array_values($this->options['left_items']);
            $this->options['right_items'] = array_values($this->options['right_items']);
        } elseif ($this->questionType === 'MATRIX') {
            unset($this->options['rows'][$index]);
            unset($this->options['columns'][$index]);
            $this->options['rows'] = array_values($this->options['rows']);
            $this->options['columns'] = array_values($this->options['columns']);
        }
    }

    public function save()
    {
        try {
            $this->validate();
            $data = [
                'quiz_id' => $this->quiz->id,
                'type' => $this->questionType,
                'question_text' => $this->questionText,
                'question_data' => [
                    'options' => $this->options,
                    'feedback' => $this->feedback,
                ],
                'answer_data' => [
                    'correct' => $this->correctAnswer,
                ],
                'scoring_data' => [
                    'points' => $this->scorePoints,
                    'partial_scoring' => false,
                    'auto_grade' => true,
                ],
                'validation_rules' => [
                    'required' => $this->isRequired,
                    'min_length' => null,
                    'max_length' => null,
                ],
                'points' => $this->scorePoints,
                'is_required' => $this->isRequired,
                'is_active' => $this->isActive,
                'order' => $this->order,
                'metadata' => array_merge($this->metadata, [
                    'feedback' => $this->feedback,
                ]),
                'created_by' => Auth::id(),
                'updated_by' => Auth::id(),
            ];

            if ($this->editMode) {
                $question = QuizQuestion::findOrFail($this->questionId);
                $question->update($data);
                session()->flash('success', 'Question updated successfully.');
            } else {
                $question = QuizQuestion::create($data);
                session()->flash('success', 'Question created successfully.');
            }

            return redirect()->route('admin.quizzes.questions', $this->quiz);
        } catch (\Exception $e) {
            session()->flash('error', 'Failed to save question: ' . $e->getMessage());
        }
    }

    public function cancel()
    {
        return redirect()->route('admin.quizzes.questions', $this->quiz);
    }

    public function render()
    {
        $questionTypes = QuizQuestion::QUESTION_TYPES;
        
        return view('livewire.admin.question-form', [
            'questionTypes' => $questionTypes,
        ]);
    }
}