<?php

namespace App\Livewire\People;

use App\Domain\Identity\Models\Person;
use App\Domain\Identity\Services\NationalIdService;
use App\Domain\Identity\Services\PersonService;
use App\Domain\Shared\Exceptions\DomainException;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Component;

#[Layout('layouts.app')]
#[Title('بيانات الشخص')]
class PersonForm extends Component
{
    public ?Person $person = null;
    public bool $editing = false;

    // Personal info
    public string $name = '';
    public string $name_ar = '';
    public string $national_id = '';
    public ?string $date_of_birth = null;
    public string $gender = 'male';

    // Contact
    public string $phone = '';
    public string $phone_secondary = '';
    public string $email = '';
    public string $address = '';
    public string $city = '';
    public string $governorate = '';

    // Emergency contact
    public string $emergency_contact_name = '';
    public string $emergency_contact_phone = '';
    public string $emergency_contact_relation = '';

    // Additional
    public string $nationality = 'Egyptian';
    public string $blood_type = '';
    public string $medical_notes = '';
    public string $classification = 'regular';
    public string $source = '';
    public string $notes = '';

    public function mount(?Person $person = null): void
    {
        if ($person && $person->exists) {
            $this->person = $person;
            $this->editing = true;
            $this->name = $person->name;
            $this->name_ar = $person->name_ar;
            $this->national_id = $person->national_id ?? '';
            $this->date_of_birth = $person->date_of_birth?->format('Y-m-d');
            $this->gender = $person->gender ?? 'male';
            $this->phone = $person->phone ?? '';
            $this->phone_secondary = $person->phone_secondary ?? '';
            $this->email = $person->email ?? '';
            $this->address = $person->address ?? '';
            $this->city = $person->city ?? '';
            $this->governorate = $person->governorate ?? '';
            $this->emergency_contact_name = $person->emergency_contact_name ?? '';
            $this->emergency_contact_phone = $person->emergency_contact_phone ?? '';
            $this->emergency_contact_relation = $person->emergency_contact_relation ?? '';
            $this->nationality = $person->nationality ?? 'Egyptian';
            $this->blood_type = $person->blood_type ?? '';
            $this->medical_notes = $person->medical_notes ?? '';
            $this->classification = $person->classification ?? 'regular';
            $this->source = $person->source ?? '';
            $this->notes = $person->notes ?? '';
        }
    }

    public function updatedNationalId(): void
    {
        if (strlen($this->national_id) === 14) {
            $service = app(NationalIdService::class);
            $data = $service->parse($this->national_id);
            if ($data) {
                $this->date_of_birth = $data->birthDate->format('Y-m-d');
                $this->gender = $data->gender;
                $this->governorate = $data->governorate;
            }
        }
    }

    public function rules(): array
    {
        return [
            'name' => 'required|string|max:255',
            'name_ar' => 'required|string|max:255',
            'national_id' => 'nullable|string|size:14',
            'date_of_birth' => 'nullable|date|before:today',
            'gender' => 'required|in:male,female',
            'phone' => 'nullable|string|max:20',
            'phone_secondary' => 'nullable|string|max:20',
            'email' => 'nullable|email|max:255',
            'address' => 'nullable|string',
            'city' => 'nullable|string|max:255',
            'governorate' => 'nullable|string|max:255',
            'emergency_contact_name' => 'nullable|string|max:255',
            'emergency_contact_phone' => 'nullable|string|max:20',
            'emergency_contact_relation' => 'nullable|string|max:30',
            'nationality' => 'nullable|string|max:50',
            'blood_type' => 'nullable|string|max:5',
            'medical_notes' => 'nullable|string',
            'classification' => 'nullable|in:regular,vip,scholarship,staff_child,trial',
            'source' => 'nullable|string|max:50',
            'notes' => 'nullable|string',
        ];
    }

    public function messages(): array
    {
        return [
            'name.required' => 'الاسم بالإنجليزية مطلوب',
            'name_ar.required' => 'الاسم بالعربية مطلوب',
            'national_id.size' => 'الرقم القومي يجب أن يكون 14 رقم',
            'date_of_birth.before' => 'تاريخ الميلاد يجب أن يكون قبل اليوم',
            'gender.required' => 'الجنس مطلوب',
            'gender.in' => 'الجنس يجب أن يكون ذكر أو أنثى',
            'email.email' => 'صيغة البريد الإلكتروني غير صحيحة',
            'classification.in' => 'التصنيف غير صالح',
            'emergency_contact_phone.max' => 'رقم هاتف الطوارئ طويل جداً',
        ];
    }

    public function save(PersonService $personService): void
    {
        $this->validate();

        $data = [
            'name' => $this->name,
            'name_ar' => $this->name_ar,
            'national_id' => $this->national_id ?: null,
            'date_of_birth' => $this->date_of_birth ?: null,
            'gender' => $this->gender,
            'phone' => $this->phone ?: null,
            'phone_secondary' => $this->phone_secondary ?: null,
            'email' => $this->email ?: null,
            'address' => $this->address ?: null,
            'city' => $this->city ?: null,
            'governorate' => $this->governorate ?: null,
            'emergency_contact_name' => $this->emergency_contact_name ?: null,
            'emergency_contact_phone' => $this->emergency_contact_phone ?: null,
            'emergency_contact_relation' => $this->emergency_contact_relation ?: null,
            'nationality' => $this->nationality ?: null,
            'blood_type' => $this->blood_type ?: null,
            'medical_notes' => $this->medical_notes ?: null,
            'classification' => $this->classification ?: null,
            'source' => $this->source ?: null,
            'notes' => $this->notes ?: null,
        ];

        try {
            if ($this->editing) {
                $personService->update($this->person, $data, auth()->user());
                session()->flash('success', __('تم تحديث البيانات بنجاح'));
            } else {
                $personService->create($data, auth()->user());
                session()->flash('success', __('تم إضافة الشخص بنجاح'));
            }
            $this->redirect(route('people.list'), navigate: true);
        } catch (DomainException $e) {
            session()->flash('error', $e->getMessage());
        }
    }

    public function render()
    {
        return view('livewire.people.person-form');
    }
}
