<?php

namespace App\Components\PensionCase;

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

class StatusController extends Component {

    public string $activeType = 'bank';

    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 setType(string $type): void {
        if (in_array($type, ['bank', 'fscs', 'fos'], true)) {
            $this->activeType = $type;
            $this->hideAdd();
        }
    }

    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(HistoryService $service): void {
        $this->authorize('statuses.edit');
        $this->validate($this->rules);

        $before = $this->status->only(['display_name', 'description', 'colour']);

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

        $changed = [];
        foreach ($this->status->getChanges() as $field => $newValue) {
            if (in_array($field, ['updated_at', 'created_at'])) {
                continue;
            }
            $changed[$field] = ['from' => $before[$field] ?? null, 'to' => $newValue];
        }

        $service->addForActor("Edited CPF status '{$this->status->display_name}'", [
            'status_id' => $this->status->id,
            'changed'   => $changed,
        ]);

        $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'         => 'pension-' . $this->activeType,
            ]);

            $status->save();

            $service->add(auth()->user(), "Created CPF status '{$data['new_status_name']}' for type {$this->activeType}");

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

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

        // Check if any pension cases use this status
        if (\App\Models\PensionCase\PensionCase::where('status_id', $id)->exists()) {
            $this->dispatch('toast', message: 'Cannot delete: status is in use by one or more pension cases.', type: 'danger');
            return;
        }

        $status->delete();
        $service->add(auth()->user(), "Deleted CPF 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 CPF statuses for type {$this->activeType}");
    }

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