<?php

namespace App\Components\Workboard;

use App\Facades\Workboard;
use App\Models\WorkboardCategory as WorkboardCategoryModel;
use App\Models\WorkboardItem;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Livewire\Attributes\Computed;
use Livewire\Component;

class WorkboardCategory extends Component
{
    use AuthorizesRequests;

    public WorkboardCategoryModel $category;

    // Add-item form
    public string $title = '';
    public string $description = '';
    public string $due_at = '';
    public string $ownerType = '';
    public string $ownerId = '';
    public bool $showAddForm = false;

    public function mount(WorkboardCategoryModel $category): void
    {
        $this->authorize('workboard.view');
        $this->category = $category;
    }

    #[Computed]
    public function items()
    {
        return $this->category->availableItems()->with('owner')->orderByRaw('due_at IS NULL, due_at ASC')->get();
    }

    public function claimItem(int $itemId): void
    {
        $this->authorize('workboard.view');

        try {
            $item = WorkboardItem::withoutGlobalScope('incomplete')
                ->whereNull('claimed_by_user_id')
                ->whereNull('completed_at')
                ->findOrFail($itemId);

            Workboard::claim($item, auth()->user());

            $this->dispatch('toast', type: 'success', message: 'Item picked up — check your tasks.');
            unset($this->items);
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException) {
            $this->dispatch('toast', type: 'error', message: 'This item has already been claimed by someone else.');
            unset($this->items);
        }
    }

    public function addItem(): void
    {
        $this->authorize('workboard.manage');

        $this->validate([
            'title'       => 'required|string|max:255',
            'description' => 'nullable|string|max:2000',
            'due_at'      => 'nullable|date',
            'ownerType'   => 'nullable|string',
            'ownerId'     => 'nullable|integer',
        ]);

        Workboard::addItem($this->category, [
            'title'       => $this->title,
            'description' => $this->description ?: null,
            'due_at'      => $this->due_at ?: null,
            'owner_type'  => $this->ownerType ?: null,
            'owner_id'    => $this->ownerId ?: null,
        ]);

        $this->reset(['title', 'description', 'due_at', 'ownerType', 'ownerId', 'showAddForm']);
        $this->dispatch('toast', type: 'success', message: 'Item added to queue.');
        unset($this->items);
    }

    public function render()
    {
        return view('components.workboard.workboard-category');
    }
}
