<?php

namespace App\Livewire\Dashboard;

use App\Models\JobCard;
use App\Models\Estimate;
use App\Models\WorkOrder;
use App\Models\VehicleInspection;
use Livewire\Component;

class WorkflowOverview extends Component
{
    public function render()
    {
        $user = auth()->user();
        
        // Get counts based on user role
        $stats = [
            'pending_inspection' => JobCard::where('status', 'pending_inspection')->count(),
            'assigned_for_diagnosis' => JobCard::where('status', 'assigned_for_diagnosis')->count(),
            'diagnosis_in_progress' => JobCard::where('status', 'diagnosis_in_progress')->count(),
            'estimates_pending_approval' => Estimate::where('customer_approval_status', 'pending')->count(),
            'work_orders_active' => WorkOrder::whereIn('status', ['scheduled', 'in_progress'])->count(),
            'quality_inspections_pending' => JobCard::where('status', 'quality_inspection')->count(),
        ];

        // Get role-specific data
        $roleSpecificData = $this->getRoleSpecificData($user);

        // Get recent activity
        $recentJobCards = JobCard::with(['customer', 'vehicle'])
            ->latest()
            ->limit(5)
            ->get();

        return view('livewire.dashboard.workflow-overview', [
            'stats' => $stats,
            'roleSpecificData' => $roleSpecificData,
            'recentJobCards' => $recentJobCards,
        ]);
    }

    private function getRoleSpecificData($user)
    {
        // Use the RBAC system instead of hardcoded roles
        $userRoles = $user->roles->pluck('name')->toArray();
        
        if ($user->hasPermission('dashboard.supervisor-view')) {
            return [
                'title' => 'Service Supervisor Dashboard',
                'tasks' => [
                    'Pending Inspections' => JobCard::where('status', 'pending_inspection')->count(),
                    'Quality Inspections' => JobCard::where('status', 'quality_inspection')->count(),
                    'Jobs Awaiting Assignment' => JobCard::whereNull('assigned_technician_id')->count(),
                    'Overdue Jobs' => JobCard::where('estimated_completion', '<', now())->whereNotIn('status', ['completed', 'delivered'])->count(),
                ],
                'priority_jobs' => JobCard::where('priority', 'urgent')->where('status', '!=', 'completed')->with(['customer', 'vehicle'])->limit(5)->get(),
            ];
        }

        if ($user->hasPermission('dashboard.technician-view')) {
            return [
                'title' => 'Technician Dashboard',
                'tasks' => [
                    'My Assigned Jobs' => JobCard::where('assigned_technician_id', $user->id)->whereNotIn('status', ['completed', 'delivered'])->count(),
                    'Diagnosis Pending' => JobCard::where('assigned_technician_id', $user->id)->where('status', 'assigned_for_diagnosis')->count(),
                    'Work in Progress' => JobCard::where('assigned_technician_id', $user->id)->where('status', 'work_in_progress')->count(),
                    'Quality Checks' => JobCard::where('assigned_technician_id', $user->id)->where('status', 'quality_inspection')->count(),
                ],
                'my_jobs' => JobCard::where('assigned_technician_id', $user->id)->whereNotIn('status', ['completed', 'delivered'])->with(['customer', 'vehicle'])->limit(5)->get(),
            ];
        }

        if ($user->hasPermission('dashboard.parts-view')) {
            return [
                'title' => 'Parts Manager Dashboard',
                'tasks' => [
                    'Parts Orders Pending' => Estimate::where('customer_approval_status', 'approved')->whereHas('jobCard', function($q) {
                        $q->where('status', 'estimate_approved');
                    })->count(),
                    'Estimates Awaiting Parts' => Estimate::where('status', 'pending_parts')->count(),
                    'Purchase Orders Active' => 0, // Would connect to purchase order system
                    'Stock Alerts' => 0, // Would connect to inventory system
                ],
                'approved_estimates' => Estimate::where('customer_approval_status', 'approved')->with(['jobCard.customer', 'jobCard.vehicle'])->limit(5)->get(),
            ];
        }

        if ($user->hasPermission('dashboard.advisor-view')) {
            return [
                'title' => 'Service Advisor Dashboard',
                'tasks' => [
                    'My Job Cards' => JobCard::where('service_advisor_id', $user->id)->whereNotIn('status', ['completed', 'delivered'])->count(),
                    'Customer Follow-ups' => Estimate::where('status', 'sent')->whereHas('jobCard', function($q) use ($user) {
                        $q->where('service_advisor_id', $user->id);
                    })->count(),
                    'Ready for Pickup' => JobCard::where('service_advisor_id', $user->id)->where('status', 'completed')->count(),
                    'Overdue Estimates' => Estimate::where('created_at', '<', now()->subDays(3))->where('customer_approval_status', 'pending')->count(),
                ],
                'my_customers' => JobCard::where('service_advisor_id', $user->id)->with(['customer', 'vehicle'])->limit(5)->get(),
            ];
        }

        // Default dashboard for general users
        return [
            'title' => 'Dashboard Overview',
            'tasks' => [
                'Today\'s Jobs' => JobCard::whereDate('created_at', today())->count(),
                'This Week\'s Jobs' => JobCard::whereBetween('created_at', [now()->startOfWeek(), now()->endOfWeek()])->count(),
                'Active Customers' => JobCard::distinct('customer_id')->whereMonth('created_at', now()->month)->count(),
            ],
            'items' => JobCard::latest()->with(['customer', 'vehicle'])->limit(3)->get(),
        ];
    }

    public function getStatusVariant($status)
    {
        return match($status) {
            'pending_inspection' => 'info',
            'assigned_for_diagnosis', 'diagnosis_in_progress' => 'warning',
            'estimate_sent', 'estimate_pending' => 'neutral',
            'work_in_progress' => 'primary',
            'quality_inspection' => 'secondary',
            'completed' => 'success',
            'delivered' => 'success',
            'cancelled' => 'danger',
            default => 'neutral'
        };
    }
}
