<?php

namespace App\Components\Claim\Application;

use App\Models\Claim\CareSetting;
use App\Models\Claim\CareSettingStatementHistory;
use App\Models\Client\Client;
use App\Services\HistoryService;
use Livewire\Component;

class Statements extends Component
{
    public Client $client;

    /** @var array<int, string> Statement text keyed by care_setting_id */
    public array $statements = [];

    public function mount(Client $client): void
    {
        $this->client = $client;
        $this->loadStatements();
    }

    protected function loadStatements(): void
    {
        if (!$this->client->claim) {
            return;
        }

        foreach ($this->client->claim->careSettings as $cs) {
            $this->statements[$cs->id] = $cs->statement ?? '';
        }
    }

    public function saveStatement(HistoryService $history, int $careSettingId): void
    {
        $cs = CareSetting::findOrFail($careSettingId);

        $newStatement = $this->statements[$careSettingId] ?? '';
        $oldStatement = $cs->statement ?? '';

        if ($newStatement === $oldStatement) {
            $this->dispatch('toast', type: 'info', message: 'No changes to save.');
            return;
        }

        // Record the outgoing version before overwriting
        CareSettingStatementHistory::create([
            'care_setting_id' => $careSettingId,
            'statement'       => $oldStatement,
            'user_id'         => auth()->id(),
        ]);

        $cs->update(['statement' => $newStatement]);

        $event = 'Care setting statement updated for "' . ($cs->institution?->display_name ?? 'Unknown') . '"';
        $context = [
            'care_setting_id' => $careSettingId,
            'institution' => $cs->institution?->display_name,
        ];

        if ($claim = $this->client->claim) {
            $history->addForClaim($claim, $event, $context);
        } else {
            $history->add($this->client, $event, $context);
        }

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

    public function render()
    {
        $careSettings = $this->client->claim
            ? $this->client->claim
                ->careSettings()
                ->with('institution', 'statementHistory.user')
                ->get()
            : collect();

        return view('components.claim.application.statements', [
            'careSettings' => $careSettings,
        ]);
    }
}
