<?php

namespace App\Livewire\Vehicle;

use App\Livewire\Forms\DocumentForm;
use App\Livewire\Forms\MaintenanceForm;
use App\Livewire\Forms\VehicleForm; // Import DocumentForm
use App\Models\Document;
use App\Models\Vehicle; // Import Document model
use App\Models\VehicleType; // Import VehicleType model
use Livewire\Attributes\Computed;
use Livewire\Component;
use Livewire\WithFileUploads; // Import WithFileUploads
use Livewire\WithPagination; // Import Computed

class Index extends Component
{
    use WithFileUploads;
    use WithPagination; // Use WithFileUploads

    

    public VehicleForm $form;

    public DocumentForm $documentForm; // Add DocumentForm

    public MaintenanceForm $maintenanceForm;

    public bool $isEditingMaintenance = false;

    public ?int $currentMaintenanceRecordId = null;

    public bool $isEditing = false;

    public string $filterStatus = 'active'; // 'active', 'trashed', 'all'

    public ?int $currentVehicleId = null; // Add currentVehicleId

    #[Url]
    public $vehicle_id = null; // For query string

    public ?int $currentVehicleIdForMaintenance = null; // For maintenance modal

    #[Computed] // Computed property to get the Vehicle object
    public function currentVehicle()
    {
        return $this->currentVehicleId ? Vehicle::withTrashed()->find($this->currentVehicleId) : null;
    }

    #[Computed] // Computed property to get the Vehicle object for maintenance
    public function currentVehicleForMaintenance()
    {
        if ($this->currentVehicleIdForMaintenance) {
            return Vehicle::withTrashed()->findOrFail($this->currentVehicleIdForMaintenance);
        }
        // Return an empty Vehicle model to prevent errors when no vehicle is selected
        return new Vehicle();
    }

    #[Computed]
    public function maintenanceTypes()
    {
        return \App\Models\MaintenanceType::all();
    }

    public function create()
    {
        $this->isEditing = false;
        $this->form->reset();
        $this->dispatch('open-modal');
    }

    public function edit(Vehicle $vehicle)
    {
        $this->isEditing = true;
        $this->form->setVehicle($vehicle);
        $this->dispatch('open-modal');
    }

    public function save()
    {
        if ($this->isEditing) {
            $this->form->update();
        } else {
            $this->form->store();
        }

        $this->dispatch('close-modal');
        session()->flash('flash.banner', 'Vehicle saved successfully!');
    }

    public function delete(Vehicle $vehicle)
    {
        $vehicle->delete();
        session()->flash('flash.banner', 'Vehicle deleted successfully.');
    }

    public function restore($vehicleId)
    {
        $vehicle = Vehicle::withTrashed()->findOrFail($vehicleId);
        $vehicle->restore();
        session()->flash('flash.banner', 'Vehicle restored successfully!');
    }

    public function forceDelete($vehicleId)
    {
        $vehicle = Vehicle::withTrashed()->findOrFail($vehicleId);
        $vehicle->forceDelete();
        session()->flash('flash.banner', 'Vehicle permanently deleted!');
    }

    // --- Document Management Methods ---
    public function manageDocuments($vehicleId)
    {
        \Log::info('manageDocuments called for vehicle ID: ' . $vehicleId);
        $vehicle = Vehicle::withTrashed()->find($vehicleId);
        if (! $vehicle) {
            \Log::warning('Vehicle not found in manageDocuments for ID: ' . $vehicleId);
            return;
        }
        $this->currentVehicleId = $vehicle->id;
        $this->documentForm->resetDocumentForm();
        $this->documentForm->documentable_id = $this->currentVehicleId;
        $this->documentForm->documentable_type = \App\Models\Vehicle::class;
        $this->dispatch('open-document-form-modal');
        \Log::info('Dispatched open-document-form-modal for vehicle ID: ' . $vehicleId);
    }

    public function createDocument()
    {
        $this->documentForm->resetDocumentForm();
        $this->documentForm->documentable_id = $this->currentVehicleId;
        $this->documentForm->documentable_type = \App\Models\Vehicle::class;
        $this->dispatch('open-document-form-modal');
    }

    public function editDocument($document_id)
    {
        $document = \App\Models\Document::findOrFail($document_id);
        $this->documentForm->setDocument($document);
        $this->dispatch('open-document-form-modal');
    }

    public function saveDocument()
    {
        if ($this->documentForm->document && $this->documentForm->document->exists) {
            $this->documentForm->update();
        } else {
            $this->documentForm->store();
        }
        session()->flash('flash.banner', 'Document saved successfully!');
        $this->documentForm->resetDocumentForm();
    }

    public function deleteDocument($document_id)
    {
        $document = \App\Models\Document::findOrFail($document_id);
        $document->delete();
        session()->flash('flash.banner', 'Document deleted successfully!');
        $this->documentForm->resetDocumentForm();
    }

    public function restoreDocument($document_id)
    {
        $document = \App\Models\Document::withTrashed()->findOrFail($document_id);
        $document->restore();
        session()->flash('flash.banner', 'Document restored successfully!');
    }

    public function forceDeleteDocument($document_id)
    {
        $document = \App\Models\Document::withTrashed()->findOrFail($document_id);
        if ($document->file_path && \Storage::disk('public')->exists($document->file_path)) {
            \Storage::disk('public')->delete($document->file_path);
        }
        $document->forceDelete();
        session()->flash('flash.banner', 'Document permanently deleted!');
    }

    // --- Maintenance Management Methods ---
    public function manageMaintenance($vehicleId)
    {
        $vehicle = Vehicle::withTrashed()->find($vehicleId);
        if (! $vehicle) {
            return;
        }
        $this->currentVehicleIdForMaintenance = $vehicle->id;
        $this->createMaintenance(); // Reset form to a clean state
        $this->dispatch('open-maintenance-management-modal');
    }

    public function createMaintenance()
    {
        $this->isEditingMaintenance = false;
        $this->maintenanceForm->resetForm();
        $this->maintenanceForm->vehicle_id = $this->currentVehicleIdForMaintenance;
    }

    public function editMaintenance($maintenanceRecordId)
    {
        $maintenanceRecord = \App\Models\MaintenanceRecord::findOrFail($maintenanceRecordId);
        $this->maintenanceForm->setMaintenanceRecord($maintenanceRecord);
        $this->isEditingMaintenance = true;
    }

    public function saveMaintenance()
    {
        $this->maintenanceForm->vehicle_id = $this->currentVehicleIdForMaintenance;

        if ($this->isEditingMaintenance) {
            $this->maintenanceForm->update();
            session()->flash('flash.banner', 'Maintenance record updated successfully!');
        } else {
            $this->maintenanceForm->store();
            session()->flash('flash.banner', 'Maintenance record created successfully!');
        }

        // Reset form to a clean "create" state after saving
        $this->createMaintenance();
    }

    public function deleteMaintenanceRecord($maintenanceRecordId)
    {
        $maintenanceRecord = \App\Models\MaintenanceRecord::findOrFail($maintenanceRecordId);
        $maintenanceRecord->delete();
        session()->flash('flash.banner', 'Maintenance record deleted successfully!');
    }

    public function restoreMaintenanceRecord($maintenanceRecordId)
    {
        $maintenanceRecord = \App\Models\MaintenanceRecord::withTrashed()->findOrFail($maintenanceRecordId);
        $maintenanceRecord->restore();
        session()->flash('flash.banner', 'Maintenance record restored successfully!');
    }

    public function forceDeleteMaintenanceRecord($maintenanceRecordId)
    {
        $maintenanceRecord = \App\Models\MaintenanceRecord::withTrashed()->findOrFail($maintenanceRecordId);
        $maintenanceRecord->forceDelete();
        session()->flash('flash.banner', 'Maintenance record permanently deleted!');
    }

    public function resetVehicleId()
    {
        $this->vehicle_id = null;
    }

    public function mount()
    {
        \Log::debug('VehicleIndex mount called. vehicle_id: ' . $this->vehicle_id);
        if ($this->vehicle_id) {
            $vehicle = Vehicle::find($this->vehicle_id);
            if ($vehicle) {
                \Log::info('Vehicle found in mount. Calling manageDocuments for vehicle ID: ' . $vehicle->id);
                $this->manageDocuments($vehicle->id);
            } else {
                \Log::warning('Vehicle not found in mount for ID: ' . $this->vehicle_id);
            }
        }
    }

    public function render()
    {
        \Log::info('VehicleIndex render called. vehicle_id: ' . $this->vehicle_id);

        $query = Vehicle::query()->with('vehicleType');

        if ($this->filterStatus === 'trashed') {
            $query->onlyTrashed();
        } elseif ($this->filterStatus === 'all') {
            $query->withTrashed();
        }

        $vehicles = $query->latest()->paginate(10);
        $vehicleTypes = VehicleType::all(); // Fetch all vehicle types

        return view('livewire.vehicle.index', [
            'vehicles' => $vehicles,
            'vehicleDocuments' => $this->currentVehicle ? $this->currentVehicle->documents()->latest()->get() : collect(),
            'vehicleMaintenanceRecords' => $this->currentVehicleForMaintenance ? $this->currentVehicleForMaintenance->maintenanceRecords()->with('maintenanceType')->latest()->get() : collect(),
            'vehicleTypes' => $vehicleTypes, // Pass vehicle types to the view
            'maintenanceTypes' => $this->maintenanceTypes,
        ]);
    }
}
