<?php

namespace App\Livewire\Inspections;

use App\Models\JobCard;
use App\Models\VehicleInspection;
use Livewire\Component;
use Livewire\WithFileUploads;

class Create extends Component
{
    use WithFileUploads;

    public JobCard $jobCard;

    public $type; // 'incoming' or 'outgoing'

    public $current_mileage = '';

    public $fuel_level = '';

    public $overall_condition = '';

    public $recommendations = '';

    public $damage_notes = '';

    public $cleanliness_rating = 5;

    public $quality_rating = null;

    public $follow_up_required = false;

    public $notes = '';

    public $additional_comments = '';

    public $photos = [];

    public $videos = [];

    public $damage_diagram_data = [];

    // Comprehensive inspection checklist items matching the form
    public $checklist = [];

    protected $rules = [
        'current_mileage' => 'required|numeric|min:0|max:999999',
        'fuel_level' => 'required|string|in:empty,low,quarter,half,three_quarter,full',
        'overall_condition' => 'required|in:excellent,good,fair,poor',
        'cleanliness_rating' => 'required|integer|min:1|max:10',
        'quality_rating' => 'nullable|integer|min:1|max:10',
        'additional_comments' => 'nullable|string|max:1000',
        'damage_notes' => 'nullable|string|max:500',
        'recommendations' => 'nullable|string|max:500',
        'notes' => 'nullable|string|max:500',
        'damage_diagram_data' => 'nullable|array',
    ];

    protected $messages = [
        'current_mileage.required' => 'Current mileage is required.',
        'current_mileage.max' => 'Mileage cannot exceed 999,999 km.',
        'fuel_level.required' => 'Please select the fuel level.',
        'overall_condition.required' => 'Please select the overall vehicle condition.',
        'additional_comments.max' => 'Additional comments cannot exceed 1000 characters.',
    ];

    public function mount(JobCard $jobCard, $type)
    {
        $this->jobCard = $jobCard->load(['customer', 'vehicle']);
        $this->type = $type;

        // Pull mileage and fuel level from job card if available
        // Pre-populate with job card data if available
        $this->current_mileage = $jobCard->mileage_in ?? $jobCard->vehicle->current_mileage ?? '';

        // Normalize fuel level from job card
        $jobCardFuelLevel = $jobCard->fuel_level_in ?? '';
        $this->fuel_level = $this->normalizeFuelLevel($jobCardFuelLevel);        // Initialize the comprehensive checklist array properly
        $this->checklist = [
            'documentation' => [
                'manufacturers_handbook' => '',
                'service_record_book' => '',
                'company_drivers_handbook' => '',
                'accident_report_form' => '',
                'safety_inspection_sticker' => '',
            ],
            'exterior' => [
                'windshield_not_cracked' => '',
                'windshield_wipers_functional' => '',
                'headlights_high_low' => '',
                'tail_lights_brake_lights' => '',
                'emergency_brake_working' => '',
                'power_brakes_working' => '',
                'horn_works' => '',
                'tires_good_shape' => '',
                'no_air_leaks' => '',
                'no_oil_grease_leaks' => '',
                'no_fuel_leaks' => '',
                'mirrors_good_position' => '',
                'exhaust_system_working' => '',
                'wheels_fasteners_tight' => '',
                'turn_signals' => '',
                'vehicle_free_damage' => '',
                'loads_fastened' => '',
                'spare_tire_good' => '',
                'vehicle_condition_satisfactory' => '',
                'defects_recorded' => '',
            ],
            'interior' => [
                'heating' => '',
                'air_conditioning' => '',
                'windshield_defrosting_system' => '',
                'window_operation' => '',
                'door_handles_locks' => '',
                'alarm' => '',
                'signals' => '',
                'seat_belts_work' => '',
                'interior_lights' => '',
                'mirrors_good_position' => '',
                'warning_lights' => '',
                'fuel_levels' => '',
                'oil_level_sufficient' => '',
                'washer_fluids_sufficient' => '',
                'radiator_fluid_sufficient' => '',
                'emergency_roadside_supplies' => '',
            ],
            'engine' => [
                'engine_oil_level' => '',
                'coolant_level_antifreeze' => '',
                'battery_secured' => '',
                'brake_fluid_level' => '',
                'air_filter_clean' => '',
                'belts_hoses_good' => '',
            ],
        ];

        if ($type === 'outgoing') {
            $this->rules['quality_rating'] = 'required|integer|min:1|max:10';
        }
    }

    private function normalizeFuelLevel($level)
    {
        // Map various possible fuel level values to our standard ones
        $fuelLevelMap = [
            'empty' => 'empty',
            'low' => 'low',
            'quarter' => 'quarter',
            '1/4' => 'quarter',
            'half' => 'half',
            '1/2' => 'half',
            'three_quarter' => 'three_quarter',
            '3/4' => 'three_quarter',
            'full' => 'full',
            // Add other possible variations
            'E' => 'empty',
            'L' => 'low',
            'Q' => 'quarter',
            'H' => 'half',
            'F' => 'full',
        ];

        $normalized = strtolower(trim($level));

        return $fuelLevelMap[$normalized] ?? $level;
    }

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

        // Validate that at least some checklist items are completed
        $completedItems = 0;
        foreach ($this->checklist as $section => $items) {
            foreach ($items as $item => $value) {
                if (! empty($value)) {
                    $completedItems++;
                }
            }
        }

        if ($completedItems < 5) {
            $this->addError('checklist', 'Please complete at least 5 inspection checklist items before saving.');

            return;
        }

        // Handle file uploads
        $photoUrls = [];
        foreach ($this->photos as $photo) {
            $photoUrls[] = $photo->store('inspections', 'public');
        }

        $videoUrls = [];
        foreach ($this->videos as $video) {
            $videoUrls[] = $video->store('inspections', 'public');
        }

        $inspection = VehicleInspection::create([
            'job_card_id' => $this->jobCard->id,
            'vehicle_id' => $this->jobCard->vehicle_id,
            'inspector_id' => auth()->id(),
            'inspection_type' => $this->type,
            'current_mileage' => $this->current_mileage,
            'fuel_level' => $this->fuel_level,
            'inspection_checklist' => $this->checklist,
            'photos' => $photoUrls,
            'videos' => $videoUrls,
            'overall_condition' => $this->overall_condition,
            'recommendations' => $this->recommendations ?: null,
            'damage_notes' => $this->damage_notes ?: null,
            'cleanliness_rating' => $this->cleanliness_rating,
            'quality_rating' => $this->quality_rating ?: null,
            'follow_up_required' => $this->follow_up_required,
            'notes' => $this->notes ?: null,
            'additional_comments' => $this->additional_comments ?: null,
            'damage_diagram_data' => $this->damage_diagram_data,
            'inspection_date' => now(),
            'service_order_id' => null, // This field is nullable
        ]);

        // Update job card status based on inspection type
        if ($this->type === 'incoming') {
            $this->jobCard->update([
                'status' => 'in_diagnosis', // Use the correct status from enum
                'mileage_in' => $this->current_mileage,
                'fuel_level_in' => $this->fuel_level,
            ]);
        } else {
            $this->jobCard->update([
                'status' => 'completed', // Outgoing inspection means work is completed
                'mileage_out' => $this->current_mileage,
                'fuel_level_out' => $this->fuel_level,
            ]);
        }

        session()->flash('message', ucfirst($this->type).' inspection completed successfully!');

        return redirect()->route('inspections.show', $inspection);
    }

    public function render()
    {
        return view('livewire.inspections.create')
            ->layout('components.layouts.app', ['title' => 'Vehicle Inspection']);
    }
}
