<?php

namespace App\Filament\Widgets;

use Filament\Widgets\StatsOverviewWidget as BaseWidget;
use Filament\Widgets\StatsOverviewWidget\Stat;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Carbon;

class StudentStatsWidget extends BaseWidget
{
    protected static ?int $sort = 1;

    protected function getStats(): array
    {
        $currentUser = auth()->user();
        $isTeacher = $currentUser?->isTeacher() ?? false;

        // 构建基础查询（带老师过滤）
        $baseQuery = DB::table('students');
        if ($isTeacher) {
            $teacherId = $currentUser?->teacher?->teacher_id;
            if ($teacherId) {
                $baseQuery->where('teacher_id', $teacherId);
            }
        }

        // 总学生数
        $totalStudents = (clone $baseQuery)->count();

        // 本月新增学生
        $newStudentsThisMonth = (clone $baseQuery)
            ->whereMonth('created_at', Carbon::now()->month)
            ->whereYear('created_at', Carbon::now()->year)
            ->count();

        // 有登录记录的学生数
        $activeStudents = (clone $baseQuery)
            ->join('users', 'students.student_id', '=', 'users.user_id')
            ->whereNotNull('users.last_login')
            ->count();

        // 本周登录的学生数
        $weeklyActiveStudents = (clone $baseQuery)
            ->join('users', 'students.student_id', '=', 'users.user_id')
            ->where('users.last_login', '>=', Carbon::now()->subWeek())
            ->count();

        // 按年级统计
        $gradeStats = (clone $baseQuery)
            ->select('grade', DB::raw('count(*) as count'))
            ->groupBy('grade')
            ->orderBy('count', 'desc')
            ->get();

        // 按班级统计
        $classStats = (clone $baseQuery)
            ->select('class_name', DB::raw('count(*) as count'))
            ->groupBy('class_name')
            ->orderBy('count', 'desc')
            ->limit(5)
            ->get();

        // 设置描述文本
        $description = $isTeacher ? '我的学生' : '全平台注册学生';

        return [
            Stat::make('总学生数', $totalStudents)
                ->description($description)
                ->descriptionIcon('heroicon-m-academic-cap')
                ->color('primary')
                ->chart([7, 15, 23, 38, 45, 52, $totalStudents]),

            Stat::make('本月新增', $newStudentsThisMonth)
                ->description('较上月 ' . ($newStudentsThisMonth > 0 ? '+' : '') . $newStudentsThisMonth)
                ->descriptionIcon('heroicon-m-arrow-trending-up')
                ->color($newStudentsThisMonth > 0 ? 'success' : 'gray'),

            Stat::make('活跃学生', $activeStudents)
                ->description('至少登录过一次')
                ->descriptionIcon('heroicon-m-user')
                ->color('info'),

            Stat::make('本周活跃', $weeklyActiveStudents)
                ->description('最近7天登录')
                ->descriptionIcon('heroicon-m-clock')
                ->color($weeklyActiveStudents > 0 ? 'success' : 'warning'),
        ];
    }

    protected function getColumns(): int
    {
        return 4;
    }
}