<?php

namespace App\Services\ImportExport\Handlers;

use App\Models\AcademicYear;
use App\Models\Student;
use App\Services\School\AdmissionNumberGenerator;

class StudentsHandler extends AbstractModuleHandler
{
    public function key(): string
    {
        return 'students';
    }

    public function label(): string
    {
        return 'Students';
    }

    public function permissionModule(): string
    {
        return 'school';
    }

    public function supportsImport(): bool
    {
        return true;
    }

    public function importColumns(): array
    {
        return [
            ['key' => 'admission_number', 'label' => 'Admission Number', 'required' => false, 'type' => 'string', 'example' => 'ADM-2026-001', 'notes' => 'Leave blank to auto-generate'],
            ['key' => 'first_name', 'label' => 'First Name', 'required' => true, 'type' => 'string', 'example' => 'Jane', 'notes' => 'Required'],
            ['key' => 'last_name', 'label' => 'Last Name', 'required' => true, 'type' => 'string', 'example' => 'Doe', 'notes' => 'Required'],
            ['key' => 'other_names', 'label' => 'Other Names', 'required' => false, 'type' => 'string', 'example' => 'Mary', 'notes' => 'Optional'],
            ['key' => 'gender', 'label' => 'Gender', 'required' => false, 'type' => 'string', 'example' => 'female', 'notes' => 'male, female, or other'],
            ['key' => 'email', 'label' => 'Email', 'required' => false, 'type' => 'email', 'example' => 'jane@example.com', 'notes' => 'Optional'],
            ['key' => 'phone', 'label' => 'Phone', 'required' => false, 'type' => 'string', 'example' => '+260971234567', 'notes' => 'Optional'],
            ['key' => 'date_of_birth', 'label' => 'Date of Birth', 'required' => false, 'type' => 'date', 'example' => '2010-05-15', 'notes' => 'YYYY-MM-DD'],
            ['key' => 'admission_date', 'label' => 'Admission Date', 'required' => false, 'type' => 'date', 'example' => '2026-01-10', 'notes' => 'YYYY-MM-DD'],
            ['key' => 'status', 'label' => 'Status', 'required' => false, 'type' => 'string', 'example' => 'active', 'notes' => 'active, inactive, graduated, withdrawn'],
            ['key' => 'leadership_role', 'label' => 'Leadership Role', 'required' => false, 'type' => 'string', 'example' => 'prefect', 'notes' => 'Optional'],
        ];
    }

    public function exportData(array $filters): array
    {
        $query = Student::query()->with('academicYear')->orderBy('last_name');

        if ($status = ($filters['status'] ?? null)) {
            $query->where('status', $status);
        }

        $students = $query->get();

        return [
            'title' => 'Students Export',
            'sheet_name' => 'Students',
            'headings' => ['Admission #', 'First Name', 'Last Name', 'Other Names', 'Gender', 'Email', 'Phone', 'DOB', 'Admission Date', 'Academic Year', 'Status', 'Leadership Role'],
            'rows' => $students->map(fn (Student $s) => [
                $s->admission_number,
                $s->first_name,
                $s->last_name,
                $s->other_names,
                $s->gender,
                $s->email,
                $s->phone,
                optional($s->date_of_birth)->format('Y-m-d'),
                optional($s->admission_date)->format('Y-m-d'),
                $s->academicYear?->name,
                $s->status,
                $s->leadership_role,
            ])->all(),
            'filters' => $this->filterSummary($filters),
            'totals' => ['Total Students' => $students->count()],
        ];
    }

    public function validateImportRow(array $row, int $rowNumber): array
    {
        return array_merge(
            $this->validateRequired($row, $rowNumber, ['first_name', 'last_name']),
            $this->validateEmail($row, $rowNumber, 'email'),
            $this->validateDate($row, $rowNumber, 'date_of_birth'),
            $this->validateDate($row, $rowNumber, 'admission_date'),
        );
    }

    public function importRow(array $row): array
    {
        $yearId = AcademicYear::query()->where('is_current', true)->value('id');

        $attrs = [
            'first_name' => $row['first_name'],
            'last_name' => $row['last_name'],
            'other_names' => $row['other_names'] ?? null,
            'gender' => $row['gender'] ?? null,
            'email' => $row['email'] ?? null,
            'phone' => $row['phone'] ?? null,
            'date_of_birth' => filled($row['date_of_birth'] ?? null) ? $row['date_of_birth'] : null,
            'admission_date' => filled($row['admission_date'] ?? null) ? $row['admission_date'] : now()->toDateString(),
            'status' => $row['status'] ?? 'active',
            'leadership_role' => $row['leadership_role'] ?? null,
            'academic_year_id' => $yearId,
        ];

        if (filled($row['admission_number'] ?? null)) {
            $student = Student::query()->updateOrCreate(['admission_number' => $row['admission_number']], $attrs);

            return ['action' => $student->wasRecentlyCreated ? 'create' : 'updated', 'message' => null];
        }

        Student::query()->create(array_merge($attrs, [
            'admission_number' => app(AdmissionNumberGenerator::class)->generate(),
        ]));

        return ['action' => 'create', 'message' => null];
    }
}
