<?php

namespace App\Http\Controllers;

use App\Services\ReportService;
use App\Services\UserService;
use App\Services\ApiService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Log;

class DashboardController extends Controller
{
    protected $reportService;
    protected $userService;
    protected $apiService;

    public function __construct(ReportService $reportService, UserService $userService, ApiService $apiService)
    {
        $this->reportService = $reportService;
        $this->userService = $userService;
        $this->apiService = $apiService;
    }

    /**
     * Mostrar el dashboard principal
     */
    public function index()
    {
        Log::info('Dashboard accessed');
        
        $userType = session('backoffice_user_type');
        
        // Redirigir según el tipo de usuario
        if (in_array($userType, ['commercial_advisor', 'advisor'])) {
            return $this->advisorDashboard();
        }
        
        // Dashboard para admin
        return $this->adminDashboard();
    }

    /**
     * Dashboard específico para administradores
     */
    private function adminDashboard()
    {
        try {
            $data = [
                'stats' => $this->getGeneralStats(),
                'recent_activities' => $this->getRecentActivities(),
                'company_plans_summary' => $this->getCompanyPlansSummary(),
                'payments_summary' => $this->getPaymentsSummary(),
                'expiring_plans' => $this->getExpiringPlans(),
                'realTimeMetrics' => $this->getRealTimeMetrics(),
            ];

            return view('dashboard.index', $data);

        } catch (\Exception $e) {
            Log::error('Admin dashboard error', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
            ]);

            $data = [
                'stats' => $this->getGeneralStats(),
                'recent_activities' => $this->getRecentActivities(),
                'company_plans_summary' => $this->getCompanyPlansSummary(),
                'payments_summary' => $this->getPaymentsSummary(),
                'expiring_plans' => $this->getExpiringPlans(),
                'realTimeMetrics' => $this->getRealTimeMetrics(),
                'demo_mode' => true,
            ];

            return view('dashboard.index', $data)->with('warning', 'Error al conectar con el servidor. Mostrando datos de ejemplo.');
        }
    }

    /**
     * Dashboard específico para asesores comerciales
     */
    private function advisorDashboard()
    {
        try {
            $data = [
                'advisor_stats' => $this->getAdvisorStats(),
                'my_companies' => $this->getMyCompanies(),
                'upcoming_payments' => $this->getUpcomingPayments(),
                'goals' => $this->getAdvisorGoals(),
                'achievements' => $this->getAdvisorAchievements(),
                'commissions_chart' => $this->getCommissionsChart(),
            ];

            return view('dashboard.advisor', $data);

        } catch (\Exception $e) {
            Log::error('Advisor dashboard error', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
            ]);

            // Datos de ejemplo para asesores
            $data = [
                'advisor_stats' => $this->getAdvisorStatsExample(),
                'my_companies' => $this->getMyCompaniesExample(),
                'upcoming_payments' => $this->getUpcomingPaymentsExample(),
                'goals' => $this->getAdvisorGoalsExample(),
                'achievements' => $this->getAdvisorAchievementsExample(),
                'commissions_chart' => $this->getCommissionsChartExample(),
                'demo_mode' => true,
            ];

            return view('dashboard.advisor', $data)->with('warning', 'Error al conectar con el servidor. Mostrando datos de ejemplo.');
        }
    }

    /**
     * Obtener estadísticas generales desde API
     */
    private function getGeneralStats(): array
    {
        try {
            // Intentar obtener estadísticas desde la API externa
            $companies = $this->apiService->makeApiRequest('GET', '/companies/stats', [], [], 'get_companies_stats');
            $plans = $this->apiService->makeApiRequest('GET', '/plans/stats', [], [], 'get_plans_stats');
            $payments = $this->apiService->makeApiRequest('GET', '/payments/stats', [], [], 'get_payments_stats');

            return [
                'total_companies' => $companies['data']['total'] ?? 0,
                'active_companies' => $companies['data']['active'] ?? 0,
                'total_plans' => $plans['data']['total'] ?? 0,
                'active_company_plans' => $plans['data']['active'] ?? 0,
                'total_payments' => $payments['data']['total'] ?? 0,
                'confirmed_payments' => $payments['data']['confirmed'] ?? 0,
                'pending_payments' => $payments['data']['pending'] ?? 0,
                'monthly_revenue' => $payments['data']['monthly_revenue'] ?? 0,
            ];
        } catch (\Exception $e) {
            Log::error('Error getting stats from API', ['error' => $e->getMessage()]);
            
            // Fallback: estadísticas de ejemplo para desarrollo
            return [
                'total_companies' => 125,
                'active_companies' => 112,
                'total_plans' => 3,
                'active_company_plans' => 98,
                'total_payments' => 247,
                'confirmed_payments' => 198,
                'pending_payments' => 15,
                'monthly_revenue' => 485000,
            ];
        }
    }

    /**
     * Obtener actividades recientes desde API
     */
    private function getRecentActivities(): array
    {
        try {
            $activities = $this->apiService->makeApiRequest('GET', '/activities/recent', [], [], 'get_recent_activities');
            return $activities['data']['data'] ?? [];
        } catch (\Exception $e) {
            Log::error('Error getting recent activities from API', ['error' => $e->getMessage()]);
            
            // Datos de ejemplo para desarrollo
            return [
                [
                    'id' => 1,
                    'type' => 'company_registered',
                    'description' => 'Nueva empresa registrada: Empresa Demo SA',
                    'user' => 'Sistema',
                    'created_at' => now()->subMinutes(15)->toISOString(),
                    'icon' => 'fas fa-building',
                    'color' => 'success',
                ],
                [
                    'id' => 2,
                    'type' => 'payment_confirmed',
                    'description' => 'Pago confirmado de $4,500 - Empresa ABC SRL',
                    'user' => 'admin',
                    'created_at' => now()->subHours(2)->toISOString(),
                    'icon' => 'fas fa-credit-card',
                    'color' => 'info',
                ],
                [
                    'id' => 3,
                    'type' => 'plan_activated',
                    'description' => 'Plan PRO activado para Empresa XYZ',
                    'user' => 'Sistema',
                    'created_at' => now()->subHours(4)->toISOString(),
                    'icon' => 'fas fa-layer-group',
                    'color' => 'primary',
                ],
                [
                    'id' => 4,
                    'type' => 'plan_expiring',
                    'description' => 'Plan próximo a vencer: Empresa 123 (3 días)',
                    'user' => 'Sistema',
                    'created_at' => now()->subHours(6)->toISOString(),
                    'icon' => 'fas fa-exclamation-triangle',
                    'color' => 'warning',
                ],
                [
                    'id' => 5,
                    'type' => 'payment_failed',
                    'description' => 'Pago fallido de $2,500 - Empresa DEF',
                    'user' => 'Sistema',
                    'created_at' => now()->subHours(8)->toISOString(),
                    'icon' => 'fas fa-times-circle',
                    'color' => 'danger',
                ],
            ];
        }
    }

    /**
     * Obtener resumen de planes de empresas desde API
     */
    private function getCompanyPlansSummary(): array
    {
        try {
            $summary = $this->apiService->makeApiRequest('GET', '/company-plans/summary', [], [], 'get_company_plans_summary');
            return $summary['data'] ?? [
                'active' => 0,
                'suspended' => 0,
                'expired' => 0,
                'cancelled' => 0,
                'pending' => 0,
                'expiring_soon' => 0,
            ];
        } catch (\Exception $e) {
            Log::error('Error getting company plans summary from API', ['error' => $e->getMessage()]);
            
            // Datos de ejemplo para desarrollo
            return [
                'active' => 98,
                'suspended' => 8,
                'expired' => 12,
                'cancelled' => 5,
                'pending' => 3,
                'expiring_soon' => 7,
            ];
        }
    }

    /**
     * Obtener resumen de pagos desde API
     */
    private function getPaymentsSummary(): array
    {
        try {
            $summary = $this->apiService->makeApiRequest('GET', '/payments/summary', [], [], 'get_payments_summary');
            return $summary['data'] ?? [
                'current_month' => [
                    'total' => 0,
                    'count' => 0,
                    'confirmed' => 0,
                ],
                'last_month' => [
                    'total' => 0,
                    'count' => 0,
                    'confirmed' => 0,
                ],
                'by_method' => [],
            ];
        } catch (\Exception $e) {
            Log::error('Error getting payments summary from API', ['error' => $e->getMessage()]);
            
            // Datos de ejemplo para desarrollo
            return [
                'current_month' => [
                    'total' => 485000,
                    'count' => 78,
                    'confirmed' => 456000,
                ],
                'last_month' => [
                    'total' => 423000,
                    'count' => 65,
                    'confirmed' => 398000,
                ],
                'by_method' => [
                    'mercadopago' => [
                        'count' => 45,
                        'amount' => 298500,
                    ],
                    'transfer' => [
                        'count' => 23,
                        'amount' => 157500,
                    ],
                    'cash' => [
                        'count' => 10,
                        'amount' => 29000,
                    ],
                ],
            ];
        }
    }

    /**
     * Obtener planes próximos a vencer desde API
     */
    private function getExpiringPlans(): array
    {
        try {
            $plans = $this->apiService->makeApiRequest('GET', '/company-plans/expiring', [], [], 'get_expiring_plans');
            return $plans['data']['data'] ?? [];
        } catch (\Exception $e) {
            Log::error('Error getting expiring plans from API', ['error' => $e->getMessage()]);
            
            // Datos de ejemplo para desarrollo
            return [
                [
                    'id' => 1,
                    'company_name' => 'Empresa ABC SA',
                    'plan_name' => 'PRO',
                    'expires_at' => now()->addDays(3)->toISOString(),
                    'days_remaining' => 3,
                    'amount' => 4500,
                    'is_critical' => true,
                ],
                [
                    'id' => 2,
                    'company_name' => 'Comercial XYZ SRL',
                    'plan_name' => 'LITE',
                    'expires_at' => now()->addDays(7)->toISOString(),
                    'days_remaining' => 7,
                    'amount' => 2500,
                    'is_critical' => false,
                ],
                [
                    'id' => 3,
                    'company_name' => 'Industrias DEF',
                    'plan_name' => 'PRO',
                    'expires_at' => now()->addDays(12)->toISOString(),
                    'days_remaining' => 12,
                    'amount' => 4500,
                    'is_critical' => false,
                ],
                [
                    'id' => 4,
                    'company_name' => 'Servicios GHI',
                    'plan_name' => 'LITE',
                    'expires_at' => now()->addDays(15)->toISOString(),
                    'days_remaining' => 15,
                    'amount' => 2500,
                    'is_critical' => false,
                ],
                [
                    'id' => 5,
                    'company_name' => 'Empresa JKL',
                    'plan_name' => 'PRO',
                    'expires_at' => now()->addDays(20)->toISOString(),
                    'days_remaining' => 20,
                    'amount' => 4500,
                    'is_critical' => false,
                ],
            ];
        }
    }

    /**
     * Obtener métricas en tiempo real
     */
    private function getRealTimeMetrics(): array
    {
        try {
            $realTimeMetrics = $this->reportService->getRealTimeMetrics();
            return $realTimeMetrics;
        } catch (\Exception $e) {
            Log::error('Error getting real time metrics', ['error' => $e->getMessage()]);
            
            // Datos de ejemplo para desarrollo
            return [
                'active_users' => 23,
                'concurrent_sessions' => 8,
                'api_requests_per_minute' => 145,
                'average_response_time' => 230,
                'system_health' => 'good',
                'database_connections' => 12,
                'memory_usage' => 67.5,
                'cpu_usage' => 23.8,
                'disk_usage' => 45.2,
                'uptime' => '7d 14h 32m',
            ];
        }
    }

    /**
     * API: Obtener estadísticas en JSON
     */
    public function getStats(Request $request)
    {
        Log::info('Dashboard stats API accessed');

        try {
            $stats = [
                'general' => $this->getGeneralStats(),
                'company_plans' => $this->getCompanyPlansSummary(),
                'payments' => $this->getPaymentsSummary(),
            ];

            return response()->json([
                'success' => true,
                'data' => $stats,
            ]);
        } catch (\Exception $e) {
            Log::error('Dashboard stats API error', [
                'error' => $e->getMessage(),
            ]);

            return response()->json([
                'success' => false,
                'message' => 'Error al obtener estadísticas',
                'error' => $e->getMessage(),
            ], 500);
        }
    }

    /**
     * API: Obtener actividades recientes en JSON
     */
    public function getRecentActivitiesApi(Request $request)
    {
        Log::info('Dashboard recent activities API accessed');

        try {
            $activities = $this->getRecentActivities();

            return response()->json([
                'success' => true,
                'data' => $activities,
            ]);
        } catch (\Exception $e) {
            Log::error('Dashboard recent activities API error', [
                'error' => $e->getMessage(),
            ]);

            return response()->json([
                'success' => false,
                'message' => 'Error al obtener actividades recientes',
                'error' => $e->getMessage(),
            ], 500);
        }
    }

    /**
     * API: Obtener planes próximos a vencer en JSON
     */
    public function getExpiringPlansApi(Request $request)
    {
        Log::info('Dashboard expiring plans API accessed');

        try {
            $days = $request->get('days', 30);
            $expiringPlans = $this->getExpiringPlans();

            return response()->json([
                'success' => true,
                'data' => $expiringPlans,
            ]);
        } catch (\Exception $e) {
            Log::error('Dashboard expiring plans API error', [
                'error' => $e->getMessage(),
            ]);

            return response()->json([
                'success' => false,
                'message' => 'Error al obtener planes próximos a vencer',
                'error' => $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Obtener estadísticas del asesor desde la API
     */
    private function getAdvisorStats(): array
    {
        try {
            $userData = session('user_data');
            $advisorId = $userData['id'] ?? null;

            if (!$advisorId) {
                return $this->getAdvisorStatsExample();
            }

            $stats = $this->apiService->makeApiRequest('GET', "/backoffice/commercial-advisors/{$advisorId}/stats", [], [], 'get_advisor_stats');

            return $stats['data'] ?? $this->getAdvisorStatsExample();
        } catch (\Exception $e) {
            Log::error('Error getting advisor stats from API', ['error' => $e->getMessage()]);
            return $this->getAdvisorStatsExample();
        }
    }

    /**
     * Obtener empresas del asesor desde la API
     */
    private function getMyCompanies(): array
    {
        try {
            $userData = session('user_data');
            $advisorId = $userData['id'] ?? null;

            if (!$advisorId) {
                return $this->getMyCompaniesExample();
            }

            $companies = $this->apiService->makeApiRequest('GET', "/backoffice/commercial-advisors/{$advisorId}/companies", [], [], 'get_advisor_companies');

            return $companies['data']['data'] ?? $this->getMyCompaniesExample();
        } catch (\Exception $e) {
            Log::error('Error getting advisor companies from API', ['error' => $e->getMessage()]);
            return $this->getMyCompaniesExample();
        }
    }

    /**
     * Obtener próximas liquidaciones del asesor
     */
    private function getUpcomingPayments(): array
    {
        try {
            $userData = session('user_data');
            $advisorId = $userData['id'] ?? null;

            if (!$advisorId) {
                return $this->getUpcomingPaymentsExample();
            }

            $payments = $this->apiService->makeApiRequest('GET', "/backoffice/commercial-advisors/{$advisorId}/payments/upcoming", [], [], 'get_advisor_upcoming_payments');

            return $payments['data']['data'] ?? $this->getUpcomingPaymentsExample();
        } catch (\Exception $e) {
            Log::error('Error getting advisor upcoming payments from API', ['error' => $e->getMessage()]);
            return $this->getUpcomingPaymentsExample();
        }
    }

    /**
     * Obtener metas del asesor
     */
    private function getAdvisorGoals(): array
    {
        try {
            $userData = session('user_data');
            $advisorId = $userData['id'] ?? null;

            if (!$advisorId) {
                return $this->getAdvisorGoalsExample();
            }

            $goals = $this->apiService->makeApiRequest('GET', "/backoffice/commercial-advisors/{$advisorId}/goals", [], [], 'get_advisor_goals');

            return $goals['data'] ?? $this->getAdvisorGoalsExample();
        } catch (\Exception $e) {
            Log::error('Error getting advisor goals from API', ['error' => $e->getMessage()]);
            return $this->getAdvisorGoalsExample();
        }
    }

    /**
     * Obtener logros del asesor
     */
    private function getAdvisorAchievements(): array
    {
        try {
            $userData = session('user_data');
            $advisorId = $userData['id'] ?? null;

            if (!$advisorId) {
                return $this->getAdvisorAchievementsExample();
            }

            $achievements = $this->apiService->makeApiRequest('GET', "/backoffice/commercial-advisors/{$advisorId}/achievements", [], [], 'get_advisor_achievements');

            return $achievements['data']['data'] ?? $this->getAdvisorAchievementsExample();
        } catch (\Exception $e) {
            Log::error('Error getting advisor achievements from API', ['error' => $e->getMessage()]);
            return $this->getAdvisorAchievementsExample();
        }
    }

    /**
     * Obtener datos del gráfico de comisiones
     */
    private function getCommissionsChart(): array
    {
        try {
            $userData = session('user_data');
            $advisorId = $userData['id'] ?? null;

            if (!$advisorId) {
                return $this->getCommissionsChartExample();
            }

            $chart = $this->apiService->makeApiRequest('GET', "/backoffice/commercial-advisors/{$advisorId}/commissions/chart", [], [], 'get_advisor_commissions_chart');

            return $chart['data'] ?? $this->getCommissionsChartExample();
        } catch (\Exception $e) {
            Log::error('Error getting advisor commissions chart from API', ['error' => $e->getMessage()]);
            return $this->getCommissionsChartExample();
        }
    }

    // Métodos de datos de ejemplo para desarrollo

    private function getAdvisorStatsExample(): array
    {
        return [
            'my_companies' => 15,
            'monthly_commissions' => 125000,
            'commission_growth' => 12,
            'monthly_sales' => 8,
            'conversion_rate' => 73,
            'next_payment_days' => 12,
        ];
    }

    private function getMyCompaniesExample(): array
    {
        return [
            [
                'name' => 'Empresa ABC SA',
                'plan' => 'PRO',
                'status' => 'active',
                'commission' => 4500,
            ],
            [
                'name' => 'Comercial XYZ SRL',
                'plan' => 'LITE',
                'status' => 'active',
                'commission' => 2500,
            ],
            [
                'name' => 'Industrias DEF',
                'plan' => 'PRO',
                'status' => 'pending',
                'commission' => 4500,
            ],
            [
                'name' => 'Servicios GHI',
                'plan' => 'BASIC',
                'status' => 'active',
                'commission' => 1500,
            ],
            [
                'name' => 'Empresa JKL',
                'plan' => 'PRO',
                'status' => 'active',
                'commission' => 4500,
            ],
        ];
    }

    private function getUpcomingPaymentsExample(): array
    {
        return [
            [
                'period' => 'Octubre 2025',
                'companies_count' => 12,
                'estimated_amount' => 85000,
                'payment_date' => '2025-11-05',
                'status' => 'calculated',
            ],
            [
                'period' => 'Noviembre 2025',
                'companies_count' => 15,
                'estimated_amount' => 95000,
                'payment_date' => '2025-12-05',
                'status' => 'pending',
            ],
            [
                'period' => 'Diciembre 2025',
                'companies_count' => 13,
                'estimated_amount' => 78000,
                'payment_date' => '2026-01-05',
                'status' => 'pending',
            ],
        ];
    }

    private function getAdvisorGoalsExample(): array
    {
        return [
            'sales_current' => 8,
            'sales_target' => 12,
            'sales_progress' => 67,
            'commission_current' => 125000,
            'commission_target' => 180000,
            'commission_progress' => 69,
        ];
    }

    private function getAdvisorAchievementsExample(): array
    {
        return [
            ['title' => 'Meta mensual superada'],
            ['title' => '10 empresas activas'],
            ['title' => 'Cliente referido'],
        ];
    }

    private function getCommissionsChartExample(): array
    {
        return [
            'labels' => ['May', 'Jun', 'Jul', 'Ago', 'Sep', 'Oct'],
            'data' => [95000, 110000, 87000, 125000, 140000, 125000],
        ];
    }
}