<?php

namespace App\Components\Client;

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

class HandlerManager extends Component {
    use AuthorizesRequests;

    public Client $client;
    public ?Claim $claim = null;

    /**
     * Array of selected user IDs keyed by handler_type_id
     */
    public array $selectedHandlers = [];

    public function mount(Client $client) {
        $this->client = $client;

        $existing = $this->client->handlers()
            ->pluck('user_id', 'handler_type_id')
            ->toArray();

        foreach (HandlerType::all() as $type) {
            $this->selectedHandlers[$type->id] = $existing[$type->id] ?? '';
        }
    }

    public function save(HistoryService $history) {
        $this->authorize('clients.handlers.manage');

        $this->validate([
            'selectedHandlers.*' => 'nullable|exists:users,id',
        ]);

        $changes = [];
        $handlerTypes = HandlerType::all()->keyBy('id');

        foreach ($this->selectedHandlers as $typeId => $userId) {
            $type = $handlerTypes->get($typeId);

            $current = $this->client->handlers()
                ->where('handler_type_id', $typeId)
                ->first();

            if (empty($userId)) {
                if ($current) {
                    $changes[$type->display_name] = [
                        'from' => $current->user->name,
                        'to' => 'Unassigned'
                    ];
                    $current->delete();
                }
                continue;
            }

            $handler = $this->client->handlers()->updateOrCreate(
                ['handler_type_id' => $typeId],
                ['user_id' => $userId]
            );

            if ($handler->wasRecentlyCreated || $handler->wasChanged('user_id')) {
                $user = User::find($userId);
                $changes[$type->display_name] = [
                    'from' => $current ? $current->user->name : 'Unassigned',
                    'to' => $user->name
                ];
            }
        }

        if (!empty($changes)) {
            $logTarget = $this->claim ?? $this->client;

            $history->add(
                $this->client,
                'Case handlers updated',
                ['changed' => $changes]
            );
        }

        $this->dispatch('toast',
            title: 'Handlers Updated',
            message: 'Handlers have been successfully assigned to the client.',
            type: 'success'
        );
    }

    public function render() {
        return view('components.client.handler-manager', [
            'handlerTypes' => HandlerType::all(),
            'users' => User::all(),
        ]);
    }
}