<?php

namespace App\Livewire;

use Livewire\Component;
use App\Models\Customer;
use App\Models\Vehicle;
use App\Models\JobCard;
use App\Models\Appointment;

class GlobalSearch extends Component
{
    public string $search = '';
    public array $results = [];
    public bool $showResults = false;

    public function updatedSearch()
    {
        if (strlen($this->search) < 2) {
            $this->results = [];
            $this->showResults = false;
            return;
        }

        $this->showResults = true;
        $this->searchAll();
    }

    public function searchAll()
    {
        $this->results = [];

        // Search Customers
        $customers = Customer::where('first_name', 'like', "%{$this->search}%")
            ->orWhere('last_name', 'like', "%{$this->search}%")
            ->orWhere('email', 'like', "%{$this->search}%")
            ->orWhere('phone', 'like', "%{$this->search}%")
            ->limit(5)
            ->get()
            ->map(function ($customer) {
                return [
                    'type' => 'customer',
                    'title' => $customer->full_name,
                    'subtitle' => $customer->email ?? $customer->phone,
                    'url' => route('customers.show', $customer),
                    'icon' => 'user'
                ];
            })
            ->toArray();

        // Search Vehicles
        $vehicles = Vehicle::where('license_plate', 'like', "%{$this->search}%")
            ->orWhere('make', 'like', "%{$this->search}%")
            ->orWhere('model', 'like', "%{$this->search}%")
            ->orWhere('vin', 'like', "%{$this->search}%")
            ->with('customer')
            ->limit(5)
            ->get()
            ->map(function ($vehicle) {
                return [
                    'type' => 'vehicle',
                    'title' => "{$vehicle->make} {$vehicle->model} - {$vehicle->license_plate}",
                    'subtitle' => $vehicle->customer?->full_name ?? 'No customer assigned',
                    'url' => "/vehicles/{$vehicle->id}",
                    'icon' => 'truck'
                ];
            })
            ->toArray();

        // Search Job Cards
        $jobCards = JobCard::where('job_card_number', 'like', "%{$this->search}%")
            ->orWhereHas('customer', function ($query) {
                $query->where('first_name', 'like', "%{$this->search}%")
                      ->orWhere('last_name', 'like', "%{$this->search}%");
            })
            ->orWhereHas('vehicle', function ($query) {
                $query->where('license_plate', 'like', "%{$this->search}%");
            })
            ->with(['customer', 'vehicle'])
            ->limit(5)
            ->get()
            ->map(function ($jobCard) {
                return [
                    'type' => 'job_card',
                    'title' => "Job #{$jobCard->job_card_number}",
                    'subtitle' => "{$jobCard->customer->full_name} - {$jobCard->vehicle->license_plate}",
                    'url' => route('job-cards.show', $jobCard),
                    'icon' => 'clipboard-document-list'
                ];
            })
            ->toArray();

        // Search Appointments (if the table exists)
        try {
            $appointments = Appointment::whereHas('customer', function ($query) {
                $query->where('first_name', 'like', "%{$this->search}%")
                      ->orWhere('last_name', 'like', "%{$this->search}%");
            })
            ->orWhereHas('vehicle', function ($query) {
                $query->where('license_plate', 'like', "%{$this->search}%");
            })
            ->with(['customer', 'vehicle'])
            ->limit(5)
            ->get()
            ->map(function ($appointment) {
                return [
                    'type' => 'appointment',
                    'title' => "Appointment - {$appointment->scheduled_date}",
                    'subtitle' => "{$appointment->customer->full_name} - {$appointment->vehicle->license_plate}",
                    'url' => "/appointments/{$appointment->id}",
                    'icon' => 'calendar'
                ];
            })
            ->toArray();
        } catch (\Exception $e) {
            $appointments = [];
        }

        // Combine all results and limit to 10
        $this->results = array_slice(
            array_merge($customers, $vehicles, $jobCards, $appointments),
            0,
            10
        );
    }

    public function clearSearch()
    {
        $this->search = '';
        $this->results = [];
        $this->showResults = false;
    }

    public function render()
    {
        return view('livewire.global-search');
    }
}
