<?php

namespace App\Livewire\Works;

use App\Enums\NocTrackingStatus;
use App\Livewire\Forms\WorkCoordinatorForm;
use App\Livewire\Works\Concerns\HasCoordinatorSearchablePickers;
use App\Models\Site;
use App\Models\Work;
use App\Models\WorkType;
use Illuminate\Contracts\View\View;
use Illuminate\Support\Collection;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Component;
use Throwable;

#[Layout('layouts.app', ['title' => 'Nueva OT', 'header' => 'Nueva orden de trabajo'])]
#[Title('Nueva OT')]
class WorkCreate extends Component
{
    use HasCoordinatorSearchablePickers;

    public WorkCoordinatorForm $form;

    public function mount(): void
    {
        $this->authorize('create', Work::class);
        $this->coordinatorSitePickerRequiresProject = true;
        $this->form->resetForCreate();
        $this->syncCoordinatorPickerLabelsFromForm();
    }

    public function updatedFormSiteId(): void
    {
        $this->form->work_type_id = null;
    }

    /** @return Collection<int, WorkType> */
    #[Computed]
    public function workTypes(): Collection
    {
        if ($this->form->site_id === null) {
            return collect();
        }

        $site = Site::query()->select(['id', 'project_id'])->find($this->form->site_id);
        if ($site === null || $site->project_id === null) {
            return collect();
        }

        return WorkType::query()
            ->active()
            ->where('project_id', $site->project_id)
            ->orderBy('name')
            ->get(['id', 'name']);
    }

    public function save(): void
    {
        $this->authorize('create', Work::class);
        $this->form->validate($this->form->rules(null), $this->form->validationMessages());

        try {
            Work::query()->create(array_merge(
                $this->form->persistenceAttributesForCoordinator(),
                [
                    'noc_tracking_status' => NocTrackingStatus::PENDIENTE->value,
                    'noc_comment' => null,
                ],
            ));

            session()->flash('status', 'Orden de trabajo creada correctamente.');

            $this->redirect(route('works.index'), navigate: true);
        } catch (Throwable $e) {
            report($e);
            $this->dispatch('notify-error', message: 'No se pudo guardar la OT.');
        }
    }

    public function render(): View
    {
        return view('livewire.works.create');
    }
}
