<?php

namespace App\Livewire\Vehicles;

use Livewire\Component;
use App\Models\Vehicle;
use App\Models\Customer;
use App\Services\VinDecoderService;
use Livewire\Attributes\Validate;
use Livewire\WithFileUploads;

class Create extends Component
{
    use WithFileUploads;
    #[Validate('required|exists:customers,id')]
    public $customer_id = '';

    #[Validate('required|string|size:17|unique:vehicles,vin')]
    public $vin = '';

    #[Validate('required|string|max:255')]
    public $make = '';

    #[Validate('required|string|max:255')]
    public $model = '';

    #[Validate('required|integer|min:1900|max:2030')]
    public $year = '';

    #[Validate('required|string|max:255')]
    public $color = '';

    #[Validate('required|string|max:20|unique:vehicles,license_plate')]
    public $license_plate = '';

    #[Validate('nullable|string|max:255')]
    public $engine_type = '';

    #[Validate('nullable|string|max:255')]
    public $transmission = '';

    #[Validate('required|integer|min:0|max:999999')]
    public $mileage = 0;

    #[Validate('nullable|string|max:1000')]
    public $notes = '';

    #[Validate('nullable|image|max:2048')]
    public $vehicle_image;

    #[Validate('required|in:active,inactive,sold')]
    public $status = 'active';

    // VIN decoding properties
    public $isDecodingVin = false;
    public $vinDecodeError = '';
    public $vinDecodeSuccess = '';

    protected VinDecoderService $vinDecoderService;

    public function boot(VinDecoderService $vinDecoderService)
    {
        $this->vinDecoderService = $vinDecoderService;
    }

    public function mount()
    {
        // If customer ID is passed via query parameter, pre-select it
        if (request()->has('customer')) {
            $this->customer_id = request()->get('customer');
        }
    }

    public function decodeVin()
    {
        // Clear previous messages
        $this->vinDecodeError = '';
        $this->vinDecodeSuccess = '';

        // Validate VIN format first
        if (strlen(trim($this->vin)) !== 17) {
            $this->vinDecodeError = 'VIN must be exactly 17 characters long.';
            return;
        }

        $this->isDecodingVin = true;

        try {
            $result = $this->vinDecoderService->decodeVin($this->vin);

            if ($result['success']) {
                $data = $result['data'];

                // Fill form fields with decoded data
                if (!empty($data['make'])) {
                    $this->make = $data['make'];
                }
                if (!empty($data['model'])) {
                    $this->model = $data['model'];
                }
                if (!empty($data['year'])) {
                    $this->year = $data['year'];
                }
                if (!empty($data['engine_type'])) {
                    $this->engine_type = $data['engine_type'];
                }
                if (!empty($data['transmission'])) {
                    $this->transmission = $data['transmission'];
                }

                // Show success message
                $filledFields = array_filter([
                    $data['make'] ? 'Make' : null,
                    $data['model'] ? 'Model' : null,
                    $data['year'] ? 'Year' : null,
                    $data['engine_type'] ? 'Engine' : null,
                    $data['transmission'] ? 'Transmission' : null,
                ]);

                if (!empty($filledFields)) {
                    $this->vinDecodeSuccess = 'VIN decoded successfully! Auto-filled: ' . implode(', ', $filledFields);
                } else {
                    $this->vinDecodeError = 'VIN was decoded but no vehicle information was found.';
                }

                // Show error codes if any
                if (!empty($data['error_codes'])) {
                    $this->vinDecodeError = 'VIN decoded with warnings: ' . implode(', ', array_slice($data['error_codes'], 0, 2));
                }

            } else {
                $this->vinDecodeError = $result['error'];
            }

        } catch (\Exception $e) {
            $this->vinDecodeError = 'An unexpected error occurred while decoding the VIN.';
        } finally {
            $this->isDecodingVin = false;
        }
    }

    public function createVehicle()
    {
        $this->validate();

        // Handle vehicle image upload
        $vehicleImagePath = null;
        if ($this->vehicle_image) {
            $vehicleImagePath = $this->vehicle_image->store('vehicles', 'public');
        }

        $vehicle = Vehicle::create([
            'customer_id' => $this->customer_id,
            'vin' => strtoupper($this->vin),
            'make' => $this->make,
            'model' => $this->model,
            'year' => $this->year,
            'color' => $this->color,
            'license_plate' => strtoupper($this->license_plate),
            'engine_type' => $this->engine_type,
            'transmission' => $this->transmission,
            'mileage' => $this->mileage,
            'notes' => $this->notes,
            'status' => $this->status,
            'vehicle_image' => $vehicleImagePath,
        ]);

        session()->flash('success', 'Vehicle added successfully!');

        return $this->redirect('/vehicles/' . $vehicle->id, navigate: true);
    }

    public function render()
    {
        $customers = Customer::where('status', 'active')->orderBy('first_name')->get();
        
        return view('livewire.vehicles.create', [
            'customers' => $customers,
        ]);
    }
}
