<?php

namespace App\Livewire\Public;

use Illuminate\Support\Facades\Http;
use Illuminate\View\View;
use Livewire\Attributes\Validate;
use Livewire\Component;

class StationSearch extends Component
{
    #[Validate('required|string', message: 'Please enter a postcode, town or city.')]
    public string $search = '';

    #[Validate('required|string', message: 'Please select a fuel type.')]
    public string $fuelType = '';

    #[Validate('required|integer|min:1|max:20')]
    public int $radius = 5;

    public array $results = [];

    public array $meta = [];

    public ?string $apiError = null;

    public function findStations(): void
    {
        $this->validate();

        $this->results = [];
        $this->meta = [];
        $this->apiError = null;

        $radiusKm = round($this->radius * 1.60934, 2);

        $response = Http::timeout(10)
            ->withHeaders(['X-Api-Key' => config('services.fuelalert.api_key')])
            ->get(url('/api/stations'), [
                'postcode' => $this->search,
                'fuel_type' => $this->fuelType,
                'radius' => $radiusKm,
                'sort' => 'price',
            ]);

        if ($response->status() === 422) {
            $errors = $response->json('errors', []);
            $this->apiError = collect($errors)->flatten()->first()
                ?? $response->json('message', 'Validation error.');

            return;
        }

        if (! $response->successful()) {
            $this->apiError = 'Unable to fetch stations. Please try again.';

            return;
        }

        $this->results = $response->json('data', []);
        $this->meta = $response->json('meta', []);
    }

    public function render(): View
    {
        return view('livewire.public.station-search');
    }
}
