<?php

namespace App\Livewire\Participants;

use App\Domain\Participant\Models\Participant;
use App\Domain\Shared\Exceptions\InvalidStatusTransitionException;
use Livewire\Component;

class FreezeParticipant extends Component
{
    public Participant $participant;
    public bool $showModal = false;
    public string $reason = '';
    public string $action = '';

    public function mount(Participant $participant): void
    {
        $this->participant = $participant;
    }

    public function openFreeze(): void
    {
        $this->action = 'freeze';
        $this->reason = '';
        $this->showModal = true;
    }

    public function openUnfreeze(): void
    {
        $this->action = 'unfreeze';
        $this->reason = '';
        $this->showModal = true;
    }

    public function confirm(): void
    {
        $this->validate(['reason' => 'required|min:3']);

        $validTransitions = [
            'active' => ['frozen'],
            'frozen' => ['active'],
        ];

        $targetStatus = $this->action === 'freeze' ? 'frozen' : 'active';
        $allowed = $validTransitions[$this->participant->status] ?? [];

        if (!in_array($targetStatus, $allowed)) {
            session()->flash('error', __('لا يمكن تنفيذ هذا الإجراء'));
            $this->showModal = false;
            return;
        }

        $this->participant->update([
            'status' => $targetStatus,
            'notes' => ($this->participant->notes ? $this->participant->notes . "\n" : '')
                . now()->format('Y-m-d') . " - " . ($this->action === 'freeze' ? 'تجميد' : 'إلغاء تجميد') . ": {$this->reason}",
        ]);

        $this->showModal = false;
        session()->flash('success', $this->action === 'freeze'
            ? __('تم تجميد المشترك بنجاح')
            : __('تم إلغاء التجميد بنجاح'));

        $this->dispatch('participant-updated');
    }

    public function render()
    {
        return view('livewire.participants.freeze-participant');
    }
}
