<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Client;
use App\Models\Installation;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class InstallationController extends Controller
{
    private array $statuses = [
        'pending' => 'Pendente',
        'active' => 'Ativa',
        'inactive' => 'Inativa',
    ];

    public function index()
    {
        $installations = Installation::with('client')->latest()->paginate(10);

        return view('admin.shared.index', [
            'title' => 'Instalações',
            'subtitle' => 'Locais monitorados e estado de instalação.',
            'createRoute' => route('admin.installations.create'),
            'createLabel' => 'Nova Instalação',
            'columns' => ['Cliente', 'Morada', 'Estado', 'Data', 'Criado em'],
            'rows' => $installations->map(fn (Installation $installation) => [
                'values' => [
                    $installation->client->name ?? 'Sem cliente',
                    $installation->address,
                    $this->statuses[$installation->status] ?? $installation->status,
                    optional($installation->installation_date)->format('d/m/Y') ?? 'Por definir',
                    $installation->created_at->format('d/m/Y'),
                ],
                'editRoute' => route('admin.installations.edit', $installation),
                'deleteRoute' => route('admin.installations.destroy', $installation),
            ]),
            'paginator' => $installations,
            'emptyLabel' => 'Nenhuma instalação registada.',
        ]);
    }

    public function create()
    {
        return $this->form(new Installation(), route('admin.installations.store'), 'Nova Instalação');
    }

    public function store(Request $request)
    {
        Installation::create($this->validated($request));

        return redirect()->route('admin.installations.index')->with('success', 'Instalação cadastrada com sucesso.');
    }

    public function show(Installation $installation)
    {
        return redirect()->route('admin.installations.edit', $installation);
    }

    public function edit(Installation $installation)
    {
        return $this->form($installation, route('admin.installations.update', $installation), 'Editar Instalação', 'PUT');
    }

    public function update(Request $request, Installation $installation)
    {
        $installation->update($this->validated($request));

        return redirect()->route('admin.installations.index')->with('success', 'Instalação atualizada com sucesso.');
    }

    public function destroy(Installation $installation)
    {
        $installation->delete();

        return redirect()->route('admin.installations.index')->with('success', 'Instalação removida com sucesso.');
    }

    private function form(Installation $installation, string $action, string $title, string $method = 'POST')
    {
        return view('admin.shared.form', [
            'title' => $title,
            'subtitle' => 'Associe o local a um cliente e acompanhe o estado da instalação.',
            'backRoute' => route('admin.installations.index'),
            'action' => $action,
            'method' => $method,
            'submitLabel' => $method === 'POST' ? 'Cadastrar Instalação' : 'Guardar Alterações',
            'fields' => [
                ['name' => 'client_id', 'label' => 'Cliente *', 'type' => 'select', 'value' => $installation->client_id, 'options' => Client::orderBy('name')->pluck('name', 'id')],
                ['name' => 'address', 'label' => 'Morada *', 'type' => 'textarea', 'value' => $installation->address],
                ['name' => 'status', 'label' => 'Estado *', 'type' => 'select', 'value' => $installation->status ?: 'pending', 'options' => $this->statuses],
                ['name' => 'installation_date', 'label' => 'Data de Instalação', 'type' => 'date', 'value' => optional($installation->installation_date)->format('Y-m-d')],
            ],
        ]);
    }

    private function validated(Request $request): array
    {
        return $request->validate([
            'client_id' => ['required', 'exists:clients,id'],
            'address' => ['required', 'string', 'max:255'],
            'status' => ['required', Rule::in(array_keys($this->statuses))],
            'installation_date' => ['nullable', 'date'],
        ]);
    }
}
