<?php

namespace App\Filament\Tenant\Pages;

use App\Models\Tenant\Part;
use App\Models\Tenant\Vehicle;
use App\Services\VinDecoder;
use Filament\Pages\Page;

class VinSearch extends Page
{
    protected static string|\BackedEnum|null $navigationIcon = 'heroicon-o-magnifying-glass';

    protected static ?string $navigationLabel = 'VIN-căutare';

    protected static string|\UnitEnum|null $navigationGroup = 'Depozit';

    protected static ?int $navigationSort = 41;

    protected static ?string $title = 'VIN căutare & piese';

    protected string $view = 'filament.tenant.pages.vin-search';

    public string $vin = '';

    public ?array $decoded = null;

    public string $partsQuery = '';

    public function decode(): void
    {
        if (! $this->vin) return;
        $this->decoded = app(VinDecoder::class)->decode($this->vin);
    }

    public function vehicleMatches(): \Illuminate\Support\Collection
    {
        if (! $this->vin) return collect();
        return Vehicle::with('client')
            ->where('vin', 'like', '%' . $this->vin . '%')
            ->limit(10)->get();
    }

    public function partsResults(): \Illuminate\Support\Collection
    {
        $q = trim($this->partsQuery);
        if ($q === '') return collect();
        return Part::where('is_active', true)
            ->where(function ($query) use ($q) {
                $query->where('name', 'like', "%{$q}%")
                    ->orWhere('article', 'like', "%{$q}%")
                    ->orWhere('brand', 'like', "%{$q}%");
            })
            ->limit(20)->get();
    }
}
