<?php

namespace App\Components\WillsCase;

use App\Models\Claim\Status;
use App\Models\WillsCase\WillsCase;
use App\Services\HistoryService;
use Livewire\Component;

class StatusController extends Component {

    public ?string $new_status_name        = '';
    public ?string $new_status_description = '';
    public ?string $new_status_color       = '';

    public bool $show    = false;
    public bool $editing = false;
    public $status;

    private array $rules = [
        'new_status_name'        => 'required|string|max:255',
        'new_status_description' => 'required|string|max:255',
        'new_status_color'       => 'required|string|max:255|regex:/^#(?:[0-9a-fA-F]{3}){1,2}$/',
    ];

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

    public function showAdd(): void {
        $this->show = true;
    }

    public function hideAdd(): void {
        $this->reset('new_status_name', 'new_status_description', 'new_status_color', 'editing', 'status');
        $this->show = false;
    }

    public function loadEdit(int $id): void {
        $status = Status::findOrFail($id);

        $this->status              = $status;
        $this->new_status_name     = $status->display_name;
        $this->new_status_description = $status->description;
        $this->new_status_color    = $status->colour;
        $this->editing             = true;

        $this->showAdd();
    }

    public function editStatus(): void {
        $this->authorize('statuses.edit');
        $this->validate($this->rules);

        $this->status->update([
            'display_name' => $this->new_status_name,
            'description'  => $this->new_status_description,
            'colour'       => $this->new_status_color,
        ]);

        $this->hideAdd();
    }

    public function addStatus(HistoryService $service): void {
        $this->authorize('statuses.create');
        $data = $this->validate($this->rules);

        try {
            $status = new Status([
                'display_name' => $data['new_status_name'],
                'description'  => $data['new_status_description'],
                'colour'       => $data['new_status_color'],
                'type'         => 'wills',
            ]);

            $status->save();

            $service->add(auth()->user(), "Created W&T status '{$data['new_status_name']}'");

            $this->hideAdd();
        } catch (\Throwable $th) {}
    }

    public function deleteStatus(HistoryService $service, int $id): void {
        $this->authorize('statuses.delete');
        $status = Status::findOrFail($id);

        if (WillsCase::where('status_id', $id)->exists()) {
            $this->dispatch('toast', message: 'Cannot delete: status is in use by one or more W&T cases.', type: 'danger');
            return;
        }

        $status->delete();
        $service->add(auth()->user(), "Deleted W&T status '{$status->display_name}'");
    }

    public function updateOrder(HistoryService $service, array $orderedIds): void {
        $this->authorize('statuses.edit');

        foreach ($orderedIds as $index => $id) {
            Status::where('id', $id)->update(['sort_order' => $index]);
        }

        $service->add(auth()->user(), 'Reordered W&T statuses');
    }

    public function render(): \Illuminate\View\View {
        return view('components.wills-case.status-controller', [
            'statuses' => Status::forType('wills')->orderBy('sort_order')->get(),
        ]);
    }
}
