<?php

namespace App\Livewire\JobCards;

use App\Models\Branch;
use App\Models\Customer;
use App\Models\JobCard;
use App\Models\User;
use App\Models\Vehicle;
use App\Services\WorkflowService;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Livewire\Component;

class Create extends Component
{
    use AuthorizesRequests;

    public $customer_id = '';

    public $vehicle_id = '';

    public $service_advisor_id = '';

    public $branch_code = '';

    public $arrival_datetime = '';

    public $expected_completion_date = '';

    public $mileage_in = '';

    public $fuel_level_in = '';

    public $customer_reported_issues = '';

    public $vehicle_condition_notes = '';

    public $keys_location = '';

    public $personal_items_removed = false;

    public $photos_taken = false;

    public $priority = 'medium';

    public $notes = '';

    public $jobCardId = null;

    // Inspection fields
    public $perform_inspection = true;

    public $inspector_id = '';

    public $overall_condition = '';

    public $inspection_notes = '';

    public $inspection_checklist = [];

    public $customers = [];

    public $vehicles = [];

    public $serviceAdvisors = [];

    public $inspectors = [];

    public $branches = [];

    protected function rules()
    {
        return [
            'customer_id' => 'required|exists:customers,id',
            'vehicle_id' => 'required|exists:vehicles,id',
            'service_advisor_id' => 'required|exists:users,id',
            'branch_code' => 'required|string|max:10',
            'arrival_datetime' => 'required|date',
            'expected_completion_date' => 'nullable|date|after:arrival_datetime',
            'mileage_in' => 'nullable|integer|min:0',
            'fuel_level_in' => 'nullable|string|max:20',
            'customer_reported_issues' => 'required|string|max:2000',
            'keys_location' => 'nullable|string|max:255',
            'priority' => 'required|in:low,medium,high,urgent',
            'notes' => 'nullable|string|max:2000',
        ];
    }

    public function mount()
    {
        // Check if user has permission to create job cards
        $this->authorize('create', JobCard::class);

        $this->branch_code = auth()->user()->branch_code ?? config('app.default_branch_code', 'ACC');
        $this->arrival_datetime = now()->format('Y-m-d\TH:i');
        $this->loadData();
        $this->initializeInspectionChecklist();
    }

    public function loadData()
    {
        $user = auth()->user();

        $this->customers = Customer::orderBy('first_name')->get();

        // Load active branches
        $this->branches = Branch::active()->orderBy('name')->get();

        // Filter service advisors based on user's permissions and branch
        $this->serviceAdvisors = User::whereIn('role', ['service_advisor', 'service_supervisor'])
            ->where('status', 'active')
            ->when(! $user->hasPermission('job-cards.view-all'), function ($query) use ($user) {
                return $query->where('branch_code', $user->branch_code);
            })
            ->orderBy('name')
            ->get();

        $this->inspectors = User::whereIn('role', ['service_supervisor', 'quality_inspector'])
            ->where('status', 'active')
            ->when(! $user->hasPermission('job-cards.view-all'), function ($query) use ($user) {
                return $query->where('branch_code', $user->branch_code);
            })
            ->orderBy('name')
            ->get();
    }

    public function updatedCustomerId()
    {
        if ($this->customer_id) {
            $this->vehicles = Vehicle::where('customer_id', $this->customer_id)
                ->orderBy('year', 'desc')
                ->orderBy('make')
                ->orderBy('model')
                ->get();
        } else {
            $this->vehicles = [];
            $this->vehicle_id = '';
        }
    }

    public function initializeInspectionChecklist()
    {
        $this->inspection_checklist = [
            'exterior_damage' => false,
            'interior_condition' => false,
            'tire_condition' => false,
            'fluid_levels' => false,
            'lights_working' => false,
            'battery_condition' => false,
            'belts_hoses' => false,
            'air_filter' => false,
            'brake_condition' => false,
            'suspension' => false,
        ];
    }

    public function save()
    {
        // Check if user still has permission to create job cards
        $this->authorize('create', JobCard::class);

        $this->validate();

        try {
            $workflowService = app(WorkflowService::class);

            $data = [
                'customer_id' => $this->customer_id,
                'vehicle_id' => $this->vehicle_id,
                'service_advisor_id' => $this->service_advisor_id,
                'branch_code' => $this->branch_code,
                'arrival_datetime' => $this->arrival_datetime,
                'expected_completion_date' => $this->expected_completion_date,
                'mileage_in' => $this->mileage_in,
                'fuel_level_in' => $this->fuel_level_in,
                'customer_reported_issues' => $this->customer_reported_issues,
                'keys_location' => $this->keys_location,
                'priority' => $this->priority,
                'notes' => $this->notes,
                // Set default values for removed fields
                'vehicle_condition_notes' => null,
                'personal_items_removed' => false,
                'photos_taken' => false,
            ];

            $jobCard = $workflowService->createJobCard($data);

            // Set the job card ID to show the inspection button
            $this->jobCardId = $jobCard->id;

            session()->flash('success', 'Job card created successfully! Job Card #: '.$jobCard->job_card_number.'. You can now perform the initial inspection.');

            // Reset form fields except jobCardId
            $this->reset([
                'customer_id', 'vehicle_id', 'service_advisor_id', 'branch_code',
                'arrival_datetime', 'expected_completion_date', 'mileage_in',
                'fuel_level_in', 'customer_reported_issues', 'keys_location',
                'priority', 'notes',
            ]);

        } catch (\Exception $e) {
            session()->flash('error', 'Failed to create job card: '.$e->getMessage());
        }
    }

    public function render()
    {
        return view('livewire.job-cards.create')
            ->layout('components.layouts.app', ['title' => 'Create Job Card']);
    }
}
