<?php

namespace App\Components\Client;

use App\Models\Client\Client;
use App\Models\Relation;
use App\Services\HistoryService;
use Livewire\Component;

class RelationManager extends Component {
    public Client $client;

    // Boolean flag to control the UI state
    public bool $showOffcanvas = false;

    public array $form = [
        'id' => null,
        'type' => 'Spouse',
        'first_name' => '',
        'last_name' => '',
        'email' => '',
        'phone' => '',
        'notes' => '',
    ];

    protected $rules = [
        'form.type' => 'required|string|max:50',
        'form.first_name' => 'required|string|max:255',
        'form.last_name' => 'required|string|max:255',
        'form.email' => 'nullable|email|max:255',
        'form.phone' => 'nullable|string|max:20',
        'form.notes' => 'nullable|string|max:500',
    ];

    public function mount() {
        $this->resetForm();
    }

    public function resetForm() {
        $this->form = [
            'id' => null,
            'type' => 'Spouse',
            'first_name' => '',
            'last_name' => '',
            'email' => '',
            'phone' => '',
            'notes' => '',
        ];
        $this->resetValidation();
    }

    public function create() {
        $this->authorize('clients.relations.create');
        $this->resetForm();
        $this->showOffcanvas = true;
    }

    public function edit($id) {
        $this->authorize('clients.relations.view');
        $this->resetValidation();
        $relation = $this->client->relations()->findOrFail($id);

        $this->form = [
            'id' => $relation->id,
            'type' => $relation->type,
            'first_name' => $relation->first_name,
            'last_name' => $relation->last_name,
            'email' => (string)$relation->email,
            'phone' => $relation->phone,
            'notes' => $relation->notes,
        ];

        $this->showOffcanvas = true;
    }

    public function delete($id, HistoryService $history) {
        $this->authorize('clients.relations.delete');
        $relation = $this->client->relations()->findOrFail($id);
        $name = trim($relation->first_name . ' ' . $relation->last_name);
        $relation->delete();

        $history->add($this->client, 'Family relation "' . $name . '" (' . $relation->type . ') removed', [
            'relation_id' => $id,
            'type'        => $relation->type,
            'name'        => $name,
        ]);

        $this->dispatch('toast', message: "Family member removed.");
    }

    public function save(HistoryService $history) {
        $this->authorize($this->form['id'] ? 'clients.relations.edit' : 'clients.relations.create');
        $this->validate();

        $isNew = empty($this->form['id']);

        $relation = Relation::updateOrCreate(
            ['id' => $this->form['id'] ?? null],
            [
                'client_id' => $this->client->id,
                'type' => $this->form['type'],
                'first_name' => $this->form['first_name'],
                'last_name' => $this->form['last_name'],
                'email' => $this->form['email'],
                'phone' => $this->form['phone'],
                'notes' => $this->form['notes'] ?? '',
            ]
        );

        $name = trim($this->form['first_name'] . ' ' . $this->form['last_name']);
        $history->add(
            $this->client,
            'Family relation "' . $name . '" (' . $this->form['type'] . ')' . ($isNew ? ' added' : ' updated'),
            [
                'relation_id' => $relation->id,
                'type'        => $this->form['type'],
                'name'        => $name,
            ]
        );

        $this->showOffcanvas = false;
        $this->dispatch('toast', message: "Family relations saved.");
        $this->resetForm();
    }

    public function render() {
        return view('components.client.relation-manager', [
            'relations' => $this->client->relations()->get()
        ]);
    }
}