<?php

namespace App\Livewire\Participants;

use App\Domain\Participant\Models\Participant;
use Livewire\Attributes\Layout;
use Livewire\Component;

#[Layout('layouts.app')]
class BulkStatusChange extends Component
{
    public array $selectedIds = [];
    public string $targetStatus = '';
    public string $reason = '';
    public string $currentFilter = 'active';
    public bool $confirmModal = false;

    private const VALID_TRANSITIONS = [
        'active' => ['frozen', 'suspended', 'inactive', 'graduated', 'withdrawn'],
        'frozen' => ['active', 'withdrawn', 'inactive'],
        'suspended' => ['active', 'withdrawn'],
        'inactive' => ['active', 'withdrawn'],
    ];

    public function mount(): void
    {
        $this->authorize('participants.update');
    }

    public function getAvailableTargets(): array
    {
        return self::VALID_TRANSITIONS[$this->currentFilter] ?? [];
    }

    public function selectAll(): void
    {
        $this->selectedIds = Participant::where('status', $this->currentFilter)
            ->pluck('id')
            ->map(fn ($id) => (string) $id)
            ->toArray();
    }

    public function deselectAll(): void
    {
        $this->selectedIds = [];
    }

    public function openConfirm(): void
    {
        if (empty($this->selectedIds) || empty($this->targetStatus)) {
            return;
        }
        $this->confirmModal = true;
    }

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

        $allowed = self::VALID_TRANSITIONS[$this->currentFilter] ?? [];
        if (!in_array($this->targetStatus, $allowed)) {
            session()->flash('error', __('انتقال غير مسموح'));
            return;
        }

        $updated = Participant::whereIn('id', $this->selectedIds)
            ->where('status', $this->currentFilter)
            ->update(['status' => $this->targetStatus]);

        $this->selectedIds = [];
        $this->confirmModal = false;
        session()->flash('success', __('تم تحديث :count مشترك', ['count' => $updated]));
    }

    public function render()
    {
        $participants = Participant::where('status', $this->currentFilter)
            ->orderBy('created_at', 'desc')
            ->limit(100)
            ->get();

        return view('livewire.participants.bulk-status-change', [
            'participants' => $participants,
            'availableTargets' => $this->getAvailableTargets(),
        ]);
    }
}
