<?php

namespace App\Components\Claim\Application;

use App\Models\Claim\Claim;
use App\Models\Client\Client;
use App\Rules\PhoneNumber;
use App\Services\HistoryService;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Livewire\Component;

class PersonalDetails extends Component {
    use AuthorizesRequests;
    public Claim $claim;

    // Form properties
    public $title = '';
    public $firstName = '';
    public $middleName = '';
    public $lastName = '';
    public $preferredName = '';
    public $email = '';
    public $phone = '';
    public $dob = '';
    public $address1 = '';
    public $address2 = '';
    public $address3 = '';
    public $postcode = '';

    public function mount() {
        $client = $this->claim->client;
        // Initialize from model
        $this->title = $client->title ?? 'Miss';
        $this->firstName = $client->name_first;
        $this->middleName = $client->name_middle;
        $this->lastName = $client->name_last;
        $this->preferredName = $client->name_preferred;
        $this->email = (string)$client->email_address;
        $this->phone = (string)$client->phone_number;
        $this->dob = $client->date_of_birth?->format('Y-m-d');

        $address = $client->currentAddress;
        $this->address1 = $address?->line_1;
        $this->address2 = $address?->line_2;
        $this->address3 = $address?->line_3;
        $this->postcode = $address?->postcode;
    }

    public function save(HistoryService $history) {
        $this->authorize('claims.edit');
        $this->validate([
            'firstName' => ['required', 'string', 'min:2', 'max:50', 'regex:/^[a-zA-Z\'\-\s]+$/'],
            'middleName' => ['nullable', 'string', 'min:2', 'max:50', 'regex:/^[a-zA-Z\'\-\s]+$/'],
            'lastName' => ['required', 'string', 'min:2', 'max:50', 'regex:/^[a-zA-Z\'\-\s]+$/'],
            'preferredName' => ['nullable', 'string', 'min:2', 'max:50', 'regex:/^[a-zA-Z\'\-\s]+$/'],
            'dob' => ['required', 'date', 'before:-18 years', 'after:-120 years'],
            'email' => [
                'required',
                'email:rfc,dns',
                'unique:clients,email_address,' . $this->claim->client->id . ',id',
            ],
            'phone' => ['required', new PhoneNumber],
            'address1' => 'required|string|min:1|max:255',
            'address2' => 'nullable|string|min:1|max:255',
            'address3' => 'nullable|string|min:1|max:255',
            'postcode' => [
                'required',
                'string',
                'regex:^[A-Za-z]{1,2}\d[A-Za-z\d]? ?\d[A-Za-z]{2}$^',
            ],
        ]);

        $this->claim->client->update([
            'title' => $this->standardiseName($this->title),
            'name_first' => $this->standardiseName($this->firstName),
            'name_middle' => $this->standardiseName($this->middleName),
            'name_last' => $this->standardiseName($this->lastName),
            'name_preferred' => $this->standardiseName($this->preferredName),
            'email_address' => $this->email,
            'phone_number' => $this->phone,
            'date_of_birth' => $this->dob,
        ]);

        $this->claim->client->currentAddress()->updateOrCreate(
            [],
            [
                'is_current' => true,
                'line_1'   => $this->address1,
                'line_2'   => $this->address2,
                'line_3'   => $this->address3,
                'postcode' => $this->postcode,
            ]
        );

        $history->add($this->claim->client, 'Personal details updated.', [
            'claim_id' => $this->claim->id,
        ]);

        $this->dispatch('toast', type: 'success', message: 'Personal Details saved.');
    }

    protected function standardiseName(?string $value): ?string
    {
        if (!$value) {
            return null;
        }

        $value = trim($value);

        $value = preg_replace('/\s+/', ' ', $value);

        $value = mb_convert_case($value, MB_CASE_TITLE, 'UTF-8');

        return $value;
    }

    public function render() {
        return view('components.claim.application.personal-details');
    }
}
