<?php

namespace App\Components\Institution;

use App\Models\Claim\Area;
use App\Models\Claim\Council;
use App\Models\Dsar\DsarType;
use App\Models\Institution\Institution;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Livewire\Component;

class Edit extends Component {
    use AuthorizesRequests;

    public Institution $institution;

    public $display_name;

    public $dsar_types;
    public $dsar_type_id;

    public $send_type;

    public bool $is_prioritised = false;

    public ?int $stated_sar_backlog = null;

    // Area / Local Authority (area drives the council).
    public $councils = [];
    public ?int $area_id = null;
    public string $area_name = '';
    public ?int $council_id = null;
    public string $local_authority = '';
    public array $area_search_results = [];


    public function mount() {
        $this->authorize('edit', $this->institution);

        $this->dsar_types = DsarType::pluck('display_name', 'id');
        $this->display_name = $this->institution->display_name;
        $this->dsar_type_id = $this->institution->dsar_type_id;
        $this->send_type = $this->institution->send_type;
        $this->is_prioritised = (bool) $this->institution->is_prioritised;
        $this->stated_sar_backlog = $this->institution->stated_sar_backlog;

        $this->councils = Council::orderBy('name')->get(['id', 'name'])->toArray();
        $this->institution->loadMissing('area.council');
        $this->area_id = $this->institution->area_id;
        $this->area_name = $this->institution->area?->name ?? '';
        $this->council_id = $this->institution->area?->council_id;
        $this->local_authority = $this->institution->area?->council?->name ?? '';
    }

    /** Search areas by name, optionally narrowed to the chosen council. */
    public function searchArea() {
        $this->area_search_results = [];

        if ($this->area_id) {
            return;
        }

        $term = trim($this->area_name);
        if (strlen($term) < 2) {
            return;
        }

        $query = Area::query()->with('council')->where('name', 'like', '%' . $term . '%');

        if ($this->council_id) {
            $query->where('council_id', $this->council_id);
        }

        $this->area_search_results = $query->orderBy('name')->limit(10)->get()
            ->map(fn (Area $a) => ['id' => $a->id, 'name' => $a->name, 'council' => $a->council?->name])
            ->values()->toArray();
    }

    /** Select an area — this fixes the Local Authority to the area's council. */
    public function setArea($areaId) {
        $area = Area::with('council')->find($areaId);
        if ($area) {
            $this->area_id = $area->id;
            $this->area_name = $area->name;
            $this->council_id = $area->council_id;
            $this->local_authority = $area->council?->name ?? '';
            $this->area_search_results = [];
        }
    }

    public function clearArea() {
        $this->area_id = null;
        $this->area_name = '';
        $this->local_authority = '';
        $this->area_search_results = [];
    }

    public function saveInstitution() {
        $this->authorize('edit', $this->institution);

        $this->validate([
            'dsar_type_id'       => 'required|integer|exists:dsar_types,id',
            'display_name'       => 'required|string|max:255',
            'area_id'            => 'nullable|exists:areas,id',
            'send_type'          => 'nullable|in:post,email,both',
            'stated_sar_backlog' => 'nullable|integer|min:0',
        ]);

        $backlogChanged = (int) $this->stated_sar_backlog !== (int) $this->institution->stated_sar_backlog
            || ($this->stated_sar_backlog === null) !== ($this->institution->stated_sar_backlog === null);

        $this->institution->update([
            'dsar_type_id'           => $this->dsar_type_id,
            'display_name'           => $this->display_name,
            'area_id'                => $this->area_id,
            'send_type'              => $this->send_type ?: null,
            'is_prioritised'         => $this->is_prioritised,
            'stated_sar_backlog'     => $this->stated_sar_backlog !== null && $this->stated_sar_backlog !== '' ? (int) $this->stated_sar_backlog : null,
            'sar_backlog_updated_at' => $backlogChanged ? now() : $this->institution->sar_backlog_updated_at,
        ]);

        return redirect()->route('institutions.show', $this->institution);
    }


    public function render() {
        return view('components.institution.edit');
    }
}
