<?php

namespace App\Livewire\Facilities;

use App\Domain\Facility\Enums\FacilityStatus;
use App\Domain\Facility\Enums\FacilityType;
use App\Domain\Facility\Models\Facility;
use App\Domain\Facility\Services\FacilityService;
use App\Domain\Identity\Models\Branch;
use App\Domain\Shared\Exceptions\DomainException;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Component;

#[Layout('layouts.app')]
#[Title('إدارة المنشأة')]
class FacilityForm extends Component
{
    public ?Facility $facility = null;
    public bool $editing = false;

    public string $name = '';
    public string $name_ar = '';
    public string $code = '';
    public string $type = 'field';
    public string $status = 'active';
    public string $description = '';
    public string $description_ar = '';
    public ?int $capacity = null;
    public string $surface_type = '';
    public ?string $area_sqm = null;
    public ?string $length_m = null;
    public ?string $width_m = null;
    public bool $is_indoor = false;
    public bool $has_lighting = true;
    public bool $has_ac = false;
    public string $operating_start = '';
    public string $operating_end = '';
    public ?string $rental_cost_display = null;
    public ?string $monthly_rental_cost_display = null;
    public string $address = '';
    public ?string $latitude = null;
    public ?string $longitude = null;
    public int $sort_order = 0;
    public string $branch_id = '';

    public function mount(?Facility $facility = null): void
    {
        $this->authorize($facility?->exists ? 'facilities.update' : 'facilities.create');

        if ($facility && $facility->exists) {
            $this->facility = $facility;
            $this->editing = true;
            $this->name = $facility->name ?? '';
            $this->name_ar = $facility->name_ar;
            $this->code = $facility->code ?? '';
            $this->type = $facility->type->value ?? $facility->type;
            $this->status = $facility->status->value ?? $facility->status;
            $this->description = $facility->description ?? '';
            $this->description_ar = $facility->description_ar ?? '';
            $this->capacity = $facility->capacity;
            $this->surface_type = $facility->surface_type ?? '';
            $this->area_sqm = $facility->area_sqm;
            $this->length_m = $facility->length_m;
            $this->width_m = $facility->width_m;
            $this->is_indoor = $facility->is_indoor;
            $this->has_lighting = $facility->has_lighting;
            $this->has_ac = $facility->has_ac;
            $this->operating_start = $facility->operating_start ?? '';
            $this->operating_end = $facility->operating_end ?? '';
            $this->rental_cost_display = $facility->rental_cost_per_hour ? (string) ($facility->rental_cost_per_hour / 100) : null;
            $this->monthly_rental_cost_display = $facility->monthly_rental_cost ? (string) ($facility->monthly_rental_cost / 100) : null;
            $this->address = $facility->address ?? '';
            $this->latitude = $facility->latitude;
            $this->longitude = $facility->longitude;
            $this->sort_order = $facility->sort_order;
            $this->branch_id = (string) $facility->branch_id;
        }
    }

    public function rules(): array
    {
        return [
            'name' => 'nullable|string|max:255',
            'name_ar' => 'required|string|max:255',
            'code' => 'nullable|string|max:20',
            'type' => 'required|in:field,court,pool,gym,track,hall,room,outdoor,other',
            'status' => 'required|in:active,maintenance,closed,reserved,unavailable',
            'description' => 'nullable|string',
            'description_ar' => 'nullable|string',
            'capacity' => 'nullable|integer|min:1',
            'surface_type' => 'nullable|string|max:50',
            'area_sqm' => 'nullable|numeric|min:0',
            'length_m' => 'nullable|numeric|min:0',
            'width_m' => 'nullable|numeric|min:0',
            'is_indoor' => 'boolean',
            'has_lighting' => 'boolean',
            'has_ac' => 'boolean',
            'operating_start' => 'nullable|date_format:H:i',
            'operating_end' => 'nullable|date_format:H:i|after:operating_start',
            'rental_cost_display' => 'nullable|numeric|min:0',
            'monthly_rental_cost_display' => 'nullable|numeric|min:0',
            'address' => 'nullable|string|max:255',
            'latitude' => 'nullable|numeric|between:-90,90',
            'longitude' => 'nullable|numeric|between:-180,180',
            'sort_order' => 'integer|min:0',
            'branch_id' => 'required|exists:branches,id',
        ];
    }

    public function messages(): array
    {
        return [
            'name_ar.required' => 'اسم المنشأة بالعربية مطلوب',
            'name_ar.max' => 'اسم المنشأة يجب ألا يتجاوز 255 حرف',
            'type.required' => 'نوع المنشأة مطلوب',
            'type.in' => 'نوع المنشأة غير صالح',
            'status.required' => 'حالة المنشأة مطلوبة',
            'status.in' => 'حالة المنشأة غير صالحة',
            'capacity.integer' => 'السعة يجب أن تكون رقم صحيح',
            'capacity.min' => 'السعة يجب أن تكون 1 على الأقل',
            'area_sqm.numeric' => 'المساحة يجب أن تكون رقم',
            'area_sqm.min' => 'المساحة لا يمكن أن تكون سالبة',
            'length_m.numeric' => 'الطول يجب أن يكون رقم',
            'width_m.numeric' => 'العرض يجب أن يكون رقم',
            'operating_start.date_format' => 'وقت البداية يجب أن يكون بصيغة ساعة:دقيقة',
            'operating_end.date_format' => 'وقت النهاية يجب أن يكون بصيغة ساعة:دقيقة',
            'operating_end.after' => 'وقت النهاية يجب أن يكون بعد وقت البداية',
            'rental_cost_display.numeric' => 'تكلفة الإيجار بالساعة يجب أن تكون رقم',
            'rental_cost_display.min' => 'تكلفة الإيجار بالساعة لا يمكن أن تكون سالبة',
            'monthly_rental_cost_display.numeric' => 'تكلفة الإيجار الشهري يجب أن تكون رقم',
            'monthly_rental_cost_display.min' => 'تكلفة الإيجار الشهري لا يمكن أن تكون سالبة',
            'branch_id.required' => 'الفرع مطلوب',
            'branch_id.exists' => 'الفرع غير موجود',
            'sort_order.integer' => 'الترتيب يجب أن يكون رقم صحيح',
            'sort_order.min' => 'الترتيب يجب أن يكون 0 أو أكثر',
            'latitude.between' => 'خط العرض يجب أن يكون بين -90 و 90',
            'longitude.between' => 'خط الطول يجب أن يكون بين -180 و 180',
        ];
    }

    public function save(FacilityService $service): void
    {
        $this->validate();

        try {
            $data = [
                'name' => $this->name ?: $this->name_ar,
                'name_ar' => $this->name_ar,
                'code' => $this->code ?: null,
                'type' => $this->type,
                'status' => $this->status,
                'description' => $this->description ?: null,
                'description_ar' => $this->description_ar ?: null,
                'capacity' => $this->capacity,
                'surface_type' => $this->surface_type ?: null,
                'area_sqm' => $this->area_sqm,
                'length_m' => $this->length_m,
                'width_m' => $this->width_m,
                'is_indoor' => $this->is_indoor,
                'has_lighting' => $this->has_lighting,
                'has_ac' => $this->has_ac,
                'operating_start' => $this->operating_start ?: null,
                'operating_end' => $this->operating_end ?: null,
                'rental_cost_per_hour' => $this->rental_cost_display ? (int) round((float) $this->rental_cost_display * 100) : null,
                'monthly_rental_cost' => $this->monthly_rental_cost_display ? (int) round((float) $this->monthly_rental_cost_display * 100) : null,
                'address' => $this->address ?: null,
                'latitude' => $this->latitude,
                'longitude' => $this->longitude,
                'sort_order' => $this->sort_order,
                'branch_id' => $this->branch_id,
            ];

            if ($this->editing) {
                $service->update($this->facility, $data);
                session()->flash('success', __('تم تحديث المنشأة بنجاح'));
            } else {
                $service->create($data, auth()->user());
                session()->flash('success', __('تم إنشاء المنشأة بنجاح'));
            }

            $this->redirect(route('facilities.list'), navigate: true);
        } catch (DomainException $e) {
            session()->flash('error', $e->getMessage());
        }
    }

    public function render()
    {
        return view('livewire.facilities.facility-form', [
            'branches' => Branch::orderBy('name_ar')->get(['id', 'name_ar']),
            'typeOptions' => collect(FacilityType::cases())->mapWithKeys(fn ($t) => [$t->value => $t->label()]),
            'statusOptions' => collect(FacilityStatus::cases())->mapWithKeys(fn ($s) => [$s->value => $s->label()]),
        ]);
    }
}
