<?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 Edit extends Component
{
    use WithFileUploads;
    public Vehicle $vehicle;

    #[Validate('required|exists:customers,id')]
    public $customer_id = '';

    #[Validate('required|string|size:17')]
    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')]
    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(Vehicle $vehicle)
    {
        $this->vehicle = $vehicle;
        $this->customer_id = $vehicle->customer_id;
        $this->vin = $vehicle->vin;
        $this->make = $vehicle->make;
        $this->model = $vehicle->model;
        $this->year = $vehicle->year;
        $this->color = $vehicle->color;
        $this->license_plate = $vehicle->license_plate;
        $this->engine_type = $vehicle->engine_type;
        $this->transmission = $vehicle->transmission;
        $this->mileage = $vehicle->mileage;
        $this->notes = $vehicle->notes;
        $this->status = $vehicle->status;
    }

    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'];

                // Ask user before overwriting existing data
                $updatedFields = [];

                if (!empty($data['make']) && $data['make'] !== $this->make) {
                    $this->make = $data['make'];
                    $updatedFields[] = 'Make';
                }
                if (!empty($data['model']) && $data['model'] !== $this->model) {
                    $this->model = $data['model'];
                    $updatedFields[] = 'Model';
                }
                if (!empty($data['year']) && $data['year'] != $this->year) {
                    $this->year = $data['year'];
                    $updatedFields[] = 'Year';
                }
                if (!empty($data['engine_type']) && $data['engine_type'] !== $this->engine_type) {
                    $this->engine_type = $data['engine_type'];
                    $updatedFields[] = 'Engine';
                }
                if (!empty($data['transmission']) && $data['transmission'] !== $this->transmission) {
                    $this->transmission = $data['transmission'];
                    $updatedFields[] = 'Transmission';
                }

                // Show success message
                if (!empty($updatedFields)) {
                    $this->vinDecodeSuccess = 'VIN decoded successfully! Updated: ' . implode(', ', $updatedFields);
                } else {
                    $this->vinDecodeSuccess = 'VIN decoded successfully! No changes needed - current data matches VIN.';
                }

                // 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 updateVehicle()
    {
        // Update validation rules to exclude current vehicle's unique fields
        $this->validate([
            'customer_id' => 'required|exists:customers,id',
            'vin' => 'required|string|size:17|unique:vehicles,vin,' . $this->vehicle->id,
            'make' => 'required|string|max:255',
            'model' => 'required|string|max:255',
            'year' => 'required|integer|min:1900|max:2030',
            'color' => 'required|string|max:255',
            'license_plate' => 'required|string|max:20|unique:vehicles,license_plate,' . $this->vehicle->id,
            'engine_type' => 'nullable|string|max:255',
            'transmission' => 'nullable|string|max:255',
            'mileage' => 'required|integer|min:0|max:999999',
            'notes' => 'nullable|string|max:1000',
            'status' => 'required|in:active,inactive,sold',
            'vehicle_image' => 'nullable|image|max:2048',
        ]);

        // Handle vehicle image upload
        $updateData = [
            '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,
        ];

        if ($this->vehicle_image) {
            // Delete old image if exists
            if ($this->vehicle->vehicle_image) {
                \Storage::disk('public')->delete($this->vehicle->vehicle_image);
            }
            // Store new image
            $updateData['vehicle_image'] = $this->vehicle_image->store('vehicles', 'public');
        }

        $this->vehicle->update($updateData);

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

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

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