<?php

namespace App\Livewire\Parent;

use App\Domain\Identity\Models\Guardian;
use App\Domain\Participant\Models\Participant;
use App\Domain\Training\Models\TrainingSession;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Component;
use Livewire\WithFileUploads;

#[Layout('layouts.parent')]
#[Title('تقديم عذر غياب - بوابة ولي الأمر')]
class ParentExcuseForm extends Component
{
    use WithFileUploads;

    public ?int $participantId = null;

    public ?int $sessionId = null;

    public string $excuseType = '';

    public string $description = '';

    public $attachment = null;

    public function mount(?int $participantId = null, ?int $sessionId = null): void
    {
        $childrenIds = $this->getChildrenIds();

        if ($participantId) {
            if (! in_array($participantId, $childrenIds)) {
                abort(403, __('ليس لديك صلاحية تقديم عذر لهذا المشترك'));
            }
            $this->participantId = $participantId;
        } else {
            $this->participantId = session('active_child_id', $childrenIds[0] ?? null);
        }

        if ($sessionId) {
            $this->sessionId = $sessionId;
        }
    }

    public function rules(): array
    {
        return [
            'participantId' => 'required|integer|exists:participants,id',
            'sessionId' => 'nullable|integer|exists:training_sessions,id',
            'excuseType' => 'required|in:medical,family,travel,academic,other',
            'description' => 'required|string|min:10|max:500',
            'attachment' => 'nullable|file|max:5120|mimes:pdf,jpg,jpeg,png',
        ];
    }

    public function messages(): array
    {
        return [
            'participantId.required' => 'يجب اختيار المشترك',
            'participantId.exists' => 'المشترك غير موجود',
            'sessionId.exists' => 'الحصة غير موجودة',
            'excuseType.required' => 'يجب اختيار نوع العذر',
            'excuseType.in' => 'نوع العذر غير صالح',
            'description.required' => 'يجب كتابة وصف العذر',
            'description.min' => 'الوصف يجب أن يكون 10 أحرف على الأقل',
            'description.max' => 'الوصف يجب ألا يتجاوز 500 حرف',
            'attachment.max' => 'حجم المرفق يجب ألا يتجاوز 5 ميجابايت',
            'attachment.mimes' => 'المرفق يجب أن يكون PDF أو صورة',
        ];
    }

    public function submit(): void
    {
        $this->validate();

        // Verify participant belongs to guardian
        $childrenIds = $this->getChildrenIds();
        if (! in_array($this->participantId, $childrenIds)) {
            session()->flash('error', __('ليس لديك صلاحية تقديم عذر لهذا المشترك'));
            return;
        }

        // Verify session belongs to participant's group (if specified)
        if ($this->sessionId) {
            $participant = Participant::find($this->participantId);
            $groupIds = $participant->activeEnrollments()->pluck('training_group_id')->toArray();
            $session = TrainingSession::find($this->sessionId);

            if (! $session || ! in_array($session->training_group_id, $groupIds)) {
                session()->flash('error', __('الحصة غير مرتبطة بمجموعات هذا المشترك'));
                return;
            }
        }

        // Store attachment if provided
        $attachmentPath = null;
        if ($this->attachment) {
            $attachmentPath = $this->attachment->store('excuses', 'public');
        }

        // For now, flash success. When an Excuse model exists, create the record here.
        // TODO: Create excuse record when model is available
        // Excuse::create([...])

        session()->flash('success', __('تم تقديم العذر بنجاح. سيتم مراجعته من قبل الإدارة.'));

        $this->reset(['excuseType', 'description', 'attachment', 'sessionId']);
    }

    public function render()
    {
        $childrenIds = $this->getChildrenIds();

        $children = Participant::whereIn('id', $childrenIds)
            ->with('person')
            ->get();

        // Get recent sessions for the selected child (for session selector)
        $recentSessions = collect();
        if ($this->participantId) {
            $participant = Participant::find($this->participantId);
            if ($participant) {
                $groupIds = $participant->activeEnrollments()->pluck('training_group_id')->toArray();
                $recentSessions = TrainingSession::whereIn('training_group_id', $groupIds)
                    ->where('session_date', '>=', now()->subDays(14)->toDateString())
                    ->where('session_date', '<=', now()->toDateString())
                    ->with('group')
                    ->orderByDesc('session_date')
                    ->limit(20)
                    ->get();
            }
        }

        $excuseTypes = [
            'medical' => __('طبي'),
            'family' => __('عائلي'),
            'travel' => __('سفر'),
            'academic' => __('دراسي'),
            'other' => __('أخرى'),
        ];

        return view('livewire.parent.parent-excuse-form', [
            'children' => $children,
            'recentSessions' => $recentSessions,
            'excuseTypes' => $excuseTypes,
        ]);
    }

    private function getGuardian(): Guardian
    {
        $user = auth()->user();

        return Guardian::where('person_id', $user->person_id)->first()
            ?? Guardian::where('user_id', $user->id)->firstOrFail();
    }

    private function getChildrenIds(): array
    {
        return $this->getGuardian()->participants()->pluck('participants.id')->toArray();
    }
}
