<?php

namespace App\Imports;

use App\Models\Question;
use Illuminate\Validation\Rule;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithStartRow;
use Maatwebsite\Excel\Concerns\WithValidation;
use Maatwebsite\Excel\Concerns\SkipsEmptyRows;
use Maatwebsite\Excel\Concerns\SkipsOnFailure;
use Maatwebsite\Excel\Concerns\SkipsFailures;

/**
 * Struktur template Excel:
 *   Baris 1 : Header kolom  (dibaca sebagai heading)
 *   Baris 2 : Baris instruksi / keterangan  <-- DILEWATI (startRow = 4)
 *   Baris 3 : Baris kosong pemisah          <-- DILEWATI (startRow = 4)
 *   Baris 4+ : Data soal sebenarnya
 */
class QuestionBankImport implements ToModel, WithHeadingRow, WithStartRow, WithValidation, SkipsOnFailure, SkipsEmptyRows
{
    use SkipsFailures;

    protected int $rowsImported = 0;

    public function __construct(
        protected array $allowedLessonIds = []
    ) {
    }

    /**
     * Baris header (judul kolom) ada di baris 1.
     */
    public function headingRow(): int
    {
        return 1;
    }

    /**
     * Data soal dimulai dari baris 4
     * (baris 2 = instruksi, baris 3 = kosong — keduanya dilewati).
     */
    public function startRow(): int
    {
        return 4;
    }

    public function prepareForValidation($data, $index)
    {
        // Normalisasi lesson_id: Excel sering membaca angka sebagai float (1.0)
        if (isset($data['lesson_id'])) {
            $data['lesson_id'] = is_numeric($data['lesson_id'])
                ? (int) $data['lesson_id']
                : $data['lesson_id'];
        }

        // Mapping difficulty Inggris → Indonesia (sesuai ENUM di database)
        $difficultyMap = [
            'easy'   => 'mudah',
            'medium' => 'sedang',
            'hard'   => 'sulit',
        ];
        if (isset($data['difficulty'])) {
            $diff = strtolower(trim((string) $data['difficulty']));
            $data['difficulty'] = $difficultyMap[$diff] ?? $diff;
        }

        return $data;
    }

    /**
     * @param array $row
     * @return \Illuminate\Database\Eloquent\Model|null
     */
    public function model(array $row)
    {
        // Lewati baris jika soal kosong
        if (empty(trim((string) ($row['question'] ?? '')))) {
            return null;
        }

        // Konversi answer ke array agar sesuai dengan cast 'array' di model
        $answer = $row['answer'] ?? null;
        if ($answer !== null && !is_array($answer)) {
            $answer = array_map('trim', explode(',', (string) $answer));
        }

        // difficulty: jika kosong/null di Excel → simpan NULL ke DB
        $difficulty = isset($row['difficulty']) && $row['difficulty'] !== '' && $row['difficulty'] !== null
            ? $row['difficulty']
            : null;

        $this->rowsImported++;

        return new Question([
            'lesson_id'  => $row['lesson_id']  ?? null,
            'type'       => $row['type']        ?? 'pg',
            'difficulty' => $difficulty,
            'kompetensi' => isset($row['kompetensi']) && $row['kompetensi'] !== '' ? $row['kompetensi'] : null,
            'question'   => $row['question'],
            'option_1'   => $row['option_1']    ?? null,
            'option_2'   => $row['option_2']    ?? null,
            'option_3'   => $row['option_3']    ?? null,
            'option_4'   => $row['option_4']    ?? null,
            'option_5'   => $row['option_5']    ?? null,
            'answer'     => $answer,
        ]);
    }

    public function getRowsImported(): int
    {
        return $this->rowsImported;
    }

    public function rules(): array
    {
        $lessonRules = ['required', 'integer', 'exists:lessons,id'];

        if (!empty($this->allowedLessonIds)) {
            $lessonRules[] = Rule::in($this->allowedLessonIds);
        }

        return [
            '*.lesson_id'  => $lessonRules,
            '*.question'   => ['required'],
            '*.type'       => ['nullable', Rule::in(['pg', 'pg_kompleks', 'menjodohkan', 'isian', 'uraian'])],
            '*.difficulty' => ['nullable', Rule::in(['mudah', 'sedang', 'sulit'])],
        ];
    }

    public function customValidationMessages()
    {
        return [
            '*.lesson_id.required' => 'ID Mata Pelajaran (lesson_id) tidak boleh kosong.',
            '*.lesson_id.integer'  => 'ID Mata Pelajaran (lesson_id) harus berupa angka (integer).',
            '*.lesson_id.exists'   => 'ID Mata Pelajaran (lesson_id) tidak ditemukan di database.',
            '*.lesson_id.in'       => 'File import memuat lesson_id yang tidak diizinkan untuk akun ini.',
            '*.question.required'  => 'Soal (question) tidak boleh kosong.',
            '*.type.in'            => 'Tipe soal tidak valid. Pilihan: pg, pg_kompleks, menjodohkan, isian, uraian.',
            '*.difficulty.in'      => 'Tingkat kesulitan tidak valid. Pilihan: mudah, sedang, sulit (atau kosongkan).',
        ];
    }

    public function customValidationAttributes()
    {
        return [
            '*.lesson_id'  => 'ID Mata Pelajaran',
            '*.question'   => 'Soal',
            '*.type'       => 'Tipe Soal',
            '*.difficulty' => 'Tingkat Kesulitan',
        ];
    }
}
