<?php

namespace App\Livewire\Notifications;

use App\Domain\Notification\Enums\NotificationChannel;
use App\Domain\Notification\Models\NotificationTemplate;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Component;

#[Layout('layouts.app')]
#[Title('قالب إشعار')]
class NotificationTemplateForm extends Component
{
    public ?NotificationTemplate $template = null;

    public string $event_type = '';
    public string $channel = '';
    public string $subject = '';
    public string $body = '';
    public string $variables_text = '';
    public bool $is_active = true;
    public string $locale = 'ar';

    /**
     * Predefined event types available in the system.
     */
    public array $eventTypes = [
        'enrollment.created' => 'تسجيل جديد',
        'enrollment.cancelled' => 'إلغاء تسجيل',
        'payment.received' => 'دفعة مستلمة',
        'payment.overdue' => 'دفعة متأخرة',
        'invoice.created' => 'فاتورة جديدة',
        'invoice.overdue' => 'فاتورة متأخرة',
        'attendance.absent' => 'غياب',
        'attendance.threshold' => 'حد الحضور',
        'participant.frozen' => 'تجميد مشترك',
        'participant.suspended' => 'إيقاف مشترك',
        'session.cancelled' => 'إلغاء حصة',
        'session.rescheduled' => 'إعادة جدولة حصة',
        'wallet.low_balance' => 'رصيد منخفض',
        'wallet.recharged' => 'شحن محفظة',
    ];

    /**
     * Available variables per event type.
     */
    public array $eventVariables = [
        'enrollment.created' => ['participant_name', 'program_name', 'group_name', 'start_date'],
        'enrollment.cancelled' => ['participant_name', 'program_name', 'reason'],
        'payment.received' => ['participant_name', 'amount', 'invoice_number', 'payment_method'],
        'payment.overdue' => ['participant_name', 'amount', 'due_date', 'invoice_number'],
        'invoice.created' => ['participant_name', 'invoice_number', 'total_amount', 'due_date'],
        'invoice.overdue' => ['participant_name', 'invoice_number', 'total_amount', 'days_overdue'],
        'attendance.absent' => ['participant_name', 'session_date', 'group_name', 'consecutive_count'],
        'attendance.threshold' => ['participant_name', 'attendance_rate', 'minimum_rate'],
        'participant.frozen' => ['participant_name', 'reason', 'freeze_date'],
        'participant.suspended' => ['participant_name', 'reason'],
        'session.cancelled' => ['group_name', 'session_date', 'session_time', 'reason'],
        'session.rescheduled' => ['group_name', 'old_date', 'new_date', 'new_time'],
        'wallet.low_balance' => ['participant_name', 'balance', 'threshold'],
        'wallet.recharged' => ['participant_name', 'amount', 'new_balance'],
    ];

    public function mount(?NotificationTemplate $template = null): void
    {
        $this->authorize('notifications.manage');

        if ($template && $template->exists) {
            $this->template = $template;
            $this->event_type = $template->event_type;
            $this->channel = $template->channel->value;
            $this->subject = $template->subject ?? '';
            $this->body = $template->body;
            $this->variables_text = implode(', ', $template->variables ?? []);
            $this->is_active = $template->is_active;
            $this->locale = $template->locale ?? 'ar';
        }
    }

    public function rules(): array
    {
        return [
            'event_type' => 'required|string|max:100',
            'channel' => 'required|in:' . implode(',', array_column(NotificationChannel::cases(), 'value')),
            'subject' => 'nullable|string|max:255',
            'body' => 'required|string|max:5000',
            'variables_text' => 'nullable|string|max:500',
            'is_active' => 'boolean',
            'locale' => 'required|in:ar,en',
        ];
    }

    public function messages(): array
    {
        return [
            'event_type.required' => __('نوع الحدث مطلوب'),
            'channel.required' => __('القناة مطلوبة'),
            'channel.in' => __('قيمة القناة غير صالحة'),
            'body.required' => __('نص الإشعار مطلوب'),
            'body.max' => __('نص الإشعار يجب أن لا يتجاوز 5000 حرف'),
            'locale.required' => __('اللغة مطلوبة'),
        ];
    }

    public function save(): void
    {
        $validated = $this->validate();

        $variables = array_filter(
            array_map('trim', explode(',', $this->variables_text))
        );

        $data = [
            'event_type' => $this->event_type,
            'channel' => $this->channel,
            'subject' => $this->subject ?: null,
            'body' => $this->body,
            'variables' => array_values($variables),
            'is_active' => $this->is_active,
            'locale' => $this->locale,
            'academy_id' => app('current_academy')?->id,
        ];

        if ($this->template && $this->template->exists) {
            $this->template->update($data);
            session()->flash('success', __('تم تحديث القالب بنجاح'));
        } else {
            NotificationTemplate::create($data);
            session()->flash('success', __('تم إنشاء القالب بنجاح'));
        }

        $this->redirect(route('notifications.templates'), navigate: true);
    }

    public function getAvailableVariablesProperty(): array
    {
        return $this->eventVariables[$this->event_type] ?? [];
    }

    public function render()
    {
        return view('livewire.notifications.notification-template-form', [
            'channels' => NotificationChannel::cases(),
        ]);
    }
}
