<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Modules\Academic\Models\AcademicYear;
use Modules\Academic\Models\Classroom;
use Modules\Academic\Models\Subject;
use Modules\Academic\Models\ExamType;
use Modules\Students\Models\Student;
use Modules\Teachers\Models\Teacher;
use Modules\Guardians\Models\Guardian;
use App\Models\User;
use Modules\Results\Models\Result;
use Modules\Results\Models\StudentResultSummary;
use Modules\Enrollment\Models\Enrollment;
use Modules\Configuration\Models\GradingRule;
use Modules\Configuration\Models\DivisionRule;

class DashboardController extends Controller
{
    /**
     * Display the dashboard based on user role
     */
    public function index(Request $request): Response
    {
        $user = $request->user();

        switch ($user->role) {
            case 'admin':
                return $this->adminDashboard();
            case 'teacher':
                return $this->teacherDashboard($user);
            case 'student':
                return $this->studentDashboard($user);
            case 'guardian':
                return $this->guardianDashboard($user);
            default:
                abort(403, 'Unauthorized access');
        }
    }

    /**
     * Admin dashboard with system overview
     */
    private function adminDashboard(): Response
    {
        $currentAcademicYear = AcademicYear::where('is_active', true)->first();

        // Academic statistics
        $academic_stats = [
            'academic_years' => [
                'total' => AcademicYear::count(),
                'active' => AcademicYear::where('is_active', true)->count(),
            ],
            'classrooms' => [
                'total' => Classroom::count(),
                'active' => $currentAcademicYear ? Classroom::where('academic_year_id', $currentAcademicYear->id)->count() : 0,
            ],
            'subjects' => [
                'total' => Subject::count(),
                'with_teachers' => Subject::whereHas('teachers')->count(),
            ],
            'exam_types' => [
                'total' => ExamType::count(),
                'active' => $currentAcademicYear ? ExamType::where('academic_year_id', $currentAcademicYear->id)->count() : 0,
            ],
        ];

        // User statistics
        $user_stats = [
            'students' => [
                'total' => Student::count(),
                'enrolled' => $currentAcademicYear ? Enrollment::where('academic_year_id', $currentAcademicYear->id)->active()->distinct('student_id')->count() : 0,
            ],
            'teachers' => [
                'total' => Teacher::count(),
                'assigned' => Teacher::whereHas('subjects')->count(),
            ],
            'guardians' => [
                'total' => Guardian::count(),
                'with_students' => Guardian::whereHas('students')->count(),
            ],
            'users' => [
                'total' => User::count(),
                'admins' => User::where('role', 'admin')->count(),
            ],
        ];

        // Enrollment statistics
        $totalCapacity = $currentAcademicYear ? Classroom::where('academic_year_id', $currentAcademicYear->id)->sum('capacity') : 0;
        $totalEnrolled = $currentAcademicYear ? Enrollment::where('academic_year_id', $currentAcademicYear->id)->active()->count() : 0;
        $utilizationRate = $totalCapacity > 0 ? round(($totalEnrolled / $totalCapacity) * 100, 1) : 0;

        $enrollment_stats = [
            'total' => Enrollment::count(),
            'active' => Enrollment::active()->count(),
            'current_year' => $totalEnrolled,
            'pending' => 0, // Placeholder for pending enrollments if implemented
            'total_capacity' => $totalCapacity,
            'total_enrolled' => $totalEnrolled,
            'utilization_rate' => $utilizationRate,
            'classrooms_full' => $currentAcademicYear ? Classroom::where('academic_year_id', $currentAcademicYear->id)
                ->whereRaw('(SELECT COUNT(*) FROM enrollments WHERE classroom_id = classrooms.id AND is_active = 1) >= capacity')
                ->count() : 0,
        ];

        // Results statistics
        $totalResults = $currentAcademicYear ? Result::where('academic_year_id', $currentAcademicYear->id)->count() : 0;
        $passedResults = $currentAcademicYear ? Result::where('academic_year_id', $currentAcademicYear->id)
            ->whereIn('grade', ['A', 'B', 'C', 'D'])->count() : 0; // Assuming A-D are passing grades
        $passRate = $totalResults > 0 ? round(($passedResults / $totalResults) * 100, 1) : 0;

        $results_stats = [
            'total' => Result::count(),
            'current_year' => $totalResults,
            'graded' => Result::whereNotNull('grade')->count(),
            'pending' => Result::whereNull('grade')->count(),
            'total_results' => $totalResults,
            'passed_results' => $passedResults,
            'pass_rate' => $passRate,
            'average_marks' => $currentAcademicYear ? Result::where('academic_year_id', $currentAcademicYear->id)->avg('marks') ?? 0 : 0,
        ];

        // Configuration statistics
        $config_stats = [
            'grading_rules' => GradingRule::count(),
            'division_rules' => DivisionRule::count(),
            'current_year_grading' => $currentAcademicYear ? GradingRule::where('academic_year_id', $currentAcademicYear->id)->count() : 0,
            'current_year_division' => $currentAcademicYear ? DivisionRule::where('academic_year_id', $currentAcademicYear->id)->count() : 0,
        ];

        // Recent activities (last 7 days)
        $recent_activities = [
            'new_students' => Student::where('created_at', '>=', now()->subDays(7))->count(),
            'new_enrollments' => Enrollment::where('enrolled_at', '>=', now()->subDays(7))->count(),
            'new_results' => Result::where('entered_at', '>=', now()->subDays(7))->count(),
            'new_teachers' => Teacher::where('created_at', '>=', now()->subDays(7))->count(),
        ];

        return Inertia::render('Dashboard/Admin', [
            'current_academic_year' => $currentAcademicYear,
            'academic_stats' => $academic_stats,
            'user_stats' => $user_stats,
            'enrollment_stats' => $enrollment_stats,
            'results_stats' => $results_stats,
            'config_stats' => $config_stats,
            'recent_activities' => $recent_activities,
        ]);
    }

    /**
     * Teacher dashboard with class management
     */
    private function teacherDashboard($user): Response
    {
        $teacher = $user->teacher;
        $currentAcademicYear = AcademicYear::where('is_active', true)->first();

        // Teacher's classrooms - Fixed to use user_id instead of teacher->id
        $classrooms = collect();
        if ($teacher && $currentAcademicYear) {
            $classrooms = Classroom::whereHas('subjects', function ($query) use ($user) {
                $query->where('teacher_id', $user->id);
            })->where('academic_year_id', $currentAcademicYear->id)
            ->with(['subjects' => function ($query) use ($user) {
                $query->wherePivot('teacher_id', $user->id);
            }, 'enrollments.student.user'])
            ->get();

            // Add student count to each classroom
            $classrooms->each(function ($classroom) {
                $classroom->students_count = $classroom->enrollments()->where('is_active', true)->count();
            });
        }

        // Teacher statistics - Fixed to use user_id
        $stats = [
            'classrooms' => $classrooms->count(),
            'students' => $classrooms->sum('students_count'),
            'subjects' => $teacher ? $teacher->subjects()->count() : 0,
            'results' => $teacher ? Result::where('teacher_id', $user->id)->count() : 0,
        ];

        // Recent results entered by teacher - Fixed to use user_id
        $recentResults = collect();
        if ($teacher) {
            $recentResults = Result::with(['student.user', 'subject', 'examType'])
                ->where('teacher_id', $user->id)
                ->latest('entered_at')
                ->limit(10)
                ->get();
        }

        // Pending tasks (students without results for current exam)
        $pendingTasks = [];
        if ($teacher && $currentAcademicYear) {
            $pendingTasks = [
                'students_without_results' => 0, // Placeholder - can be calculated later
                'classrooms_to_review' => $classrooms->count(),
            ];
        }

        return Inertia::render('Dashboard/Teacher', [
            'stats' => $stats,
            'classrooms' => $classrooms,
            'recentResults' => $recentResults,
            'pendingTasks' => $pendingTasks,
            'currentAcademicYear' => $currentAcademicYear,
        ]);
    }

    /**
     * Student dashboard with academic progress
     */
    private function studentDashboard($user): Response
    {
        $student = $user->student;
        $currentAcademicYear = AcademicYear::where('is_active', true)->first();

        if (!$student) {
            return Inertia::render('Dashboard/Student', [
                'error' => 'Student profile not found.',
            ]);
        }

        // Current enrollment
        $currentEnrollment = null;
        if ($currentAcademicYear) {
            $currentEnrollment = Enrollment::where('student_id', $student->id)
                ->where('academic_year_id', $currentAcademicYear->id)
                ->where('is_active', true)
                ->with(['classroom', 'academicYear'])
                ->first();
        }

        // Academic performance
        $academicStats = [];
        $recentResults = collect();
        $resultSummary = null;

        if ($currentEnrollment && $currentAcademicYear) {
            // Get latest exam results
            $recentResults = Result::where('student_id', $student->id)
                ->where('academic_year_id', $currentAcademicYear->id)
                ->with(['subject', 'examType'])
                ->latest('entered_at')
                ->limit(10)
                ->get();

            // Get result summary for latest exam
            $resultSummary = StudentResultSummary::where('student_id', $student->id)
                ->where('academic_year_id', $currentAcademicYear->id)
                ->latest('computed_at')
                ->first();

            $academicStats = [
                'total_subjects' => $recentResults->count(),
                'average_marks' => $resultSummary ? $resultSummary->average_marks : 0,
                'current_rank' => $resultSummary ? $resultSummary->rank : null,
                'division' => $resultSummary ? $resultSummary->division : null,
            ];
        }

        // Attendance and other metrics would go here
        $attendanceStats = [
            'present_days' => 0, // Placeholder
            'absent_days' => 0,  // Placeholder
            'attendance_percentage' => 0, // Placeholder
        ];

        return Inertia::render('Dashboard/Student', [
            'student' => $student,
            'currentEnrollment' => $currentEnrollment,
            'academicStats' => $academicStats,
            'attendanceStats' => $attendanceStats,
            'recentResults' => $recentResults,
            'resultSummary' => $resultSummary,
            'currentAcademicYear' => $currentAcademicYear,
        ]);
    }

    /**
     * Guardian dashboard with children's progress
     */
    private function guardianDashboard($user): Response
    {
        $guardian = $user->guardian;
        $currentAcademicYear = AcademicYear::where('is_active', true)->first();

        if (!$guardian) {
            return Inertia::render('Dashboard/Guardian', [
                'error' => 'Guardian profile not found.',
            ]);
        }

        // Guardian's students
        $students = $guardian->students()->with([
            'user',
            'enrollments' => function ($query) use ($currentAcademicYear) {
                if ($currentAcademicYear) {
                    $query->where('academic_year_id', $currentAcademicYear->id)
                          ->where('is_active', true);
                }
            },
            'enrollments.classroom'
        ])->get();

        // Academic performance for each student
        $studentsPerformance = [];
        foreach ($students as $student) {
            $resultSummary = null;
            $recentResults = collect();

            if ($currentAcademicYear) {
                $resultSummary = StudentResultSummary::where('student_id', $student->id)
                    ->where('academic_year_id', $currentAcademicYear->id)
                    ->latest('computed_at')
                    ->first();

                $recentResults = Result::where('student_id', $student->id)
                    ->where('academic_year_id', $currentAcademicYear->id)
                    ->with(['subject', 'examType'])
                    ->latest('entered_at')
                    ->limit(5)
                    ->get();
            }

            $studentsPerformance[] = [
                'student' => $student,
                'summary' => $resultSummary,
                'recent_results' => $recentResults,
                'enrollment' => $student->enrollments->first(),
            ];
        }

        // Overall statistics
        $overallStats = [
            'total_children' => $students->count(),
            'enrolled_children' => $students->filter(function ($student) {
                return $student->enrollments->isNotEmpty();
            })->count(),
        ];

        return Inertia::render('Dashboard/Guardian', [
            'guardian' => $guardian,
            'students' => $studentsPerformance,
            'overallStats' => $overallStats,
            'currentAcademicYear' => $currentAcademicYear,
        ]);
    }
}
