<?php

namespace App\Components\Institution;

use App\Models\Institution\Institution;
use App\Services\HistoryService;
use Livewire\Component;
use Livewire\WithPagination;

class RelationManager extends Component {
    public Institution $institution;
    public $search = '';
    public $selectedIds = [];

    use WithPagination;

    public function attachSelected(HistoryService $history) {
        if (empty($this->selectedIds)) {
            $this->dispatch('toast', type: 'error', message: 'No institutions selected.');
            return;
        }

        $names = Institution::whereIn('id', $this->selectedIds)->pluck('display_name')->toArray();

        $this->institution->relatedInstitutions()->syncWithoutDetaching($this->selectedIds);

        $history->add($this->institution, count($this->selectedIds) . ' related institution(s) linked', [
            'related_ids'   => array_values($this->selectedIds),
            'related_names' => $names,
        ]);

        $this->selectedIds = [];

        $this->dispatch('toast', type: 'success', message: 'Institutions attached successfully.');
    }

    public function detach($id, HistoryService $history)
    {
        $related = Institution::find($id);

        $this->institution->relatedInstitutions()->detach($id);

        $history->add($this->institution, 'Related institution "' . ($related?->display_name ?? 'Unknown') . '" unlinked', [
            'related_id'   => $id,
            'related_name' => $related?->display_name,
        ]);

        $this->dispatch('toast', type: 'success', message: 'Institutions detached successfully.');
    }

    public function render() {
        $alreadyAttachedIds = $this->institution->relatedInstitutions->pluck('id')->toArray();

        $query = Institution::where('id', '!=', $this->institution->id)
            ->whereNotIn('id', $alreadyAttachedIds);

        if ($this->search) {
            $query->where('display_name', 'like', '%' . $this->search . '%');
        }

        return view('components.institution.relation-manager', [
            'availableInstitutions' => $query->paginate(10),
            'mainInstitution' => $this->institution
        ]);
    }
}
