<?php

namespace App\Filament\Siswa\Widgets;

use App\Models\RekapanSiswa;
use Filament\Support\Enums\IconPosition;
use Filament\Widgets\StatsOverviewWidget\Stat;
use Filament\Widgets\StatsOverviewWidget as BaseWidget;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class StatsOverview extends BaseWidget
{
    protected int | string | array $columnSpan = 'full';
    protected static ?string $pollingInterval = '30s';
    protected static ?int $sort = 1;

    protected function getStats(): array
    {
        $siswaId = Auth::id();
        $kelasId = Auth::user()->siswa->kelas_id;

        $weeklyData = RekapanSiswa::where(function($query) use ($siswaId, $kelasId) {
                $query->where('siswa_id', $siswaId)
                      ->orWhere('kelas_id', $kelasId);
            })
            ->whereBetween('tanggal', [now()->subDays(6), now()])
            ->select([
                DB::raw('DATE(tanggal) as date'),
                DB::raw('COUNT(*) as total'),
                DB::raw('SUM(CASE WHEN status = "hadir_mengajar" THEN 1 ELSE 0 END) as hadir'),
                DB::raw('SUM(CASE WHEN status = "tidak_mengajar" THEN 1 ELSE 0 END) as tidak_hadir'),
                DB::raw('SUM(CASE WHEN status = "hadir_digantikan" THEN 1 ELSE 0 END) as digantikan')
            ])
            ->groupBy('date')
            ->orderBy('date')
            ->get();

        $dates = collect(range(0, 6))->map(fn ($day) => now()->subDays($day)->format('Y-m-d'));
        
        $weeklyStats = $dates->map(function ($date) use ($weeklyData) {
            $record = $weeklyData->firstWhere('date', $date);
            return [
                'total' => $record->total ?? 0,
                'hadir' => $record->hadir ?? 0,
                'tidak_hadir' => $record->tidak_hadir ?? 0,
                'digantikan' => $record->digantikan ?? 0,
            ];
        });

        $stats = RekapanSiswa::query()
            ->where(function($query) use ($siswaId, $kelasId) {
                $query->where('siswa_id', $siswaId)
                      ->orWhere('kelas_id', $kelasId);
            })
            ->selectRaw('count(*) as total')
            ->selectRaw('sum(case when status = "hadir_mengajar" then 1 else 0 end) as hadir_mengajar')
            ->selectRaw('sum(case when status = "tidak_mengajar" then 1 else 0 end) as tidak_mengajar')
            ->selectRaw('sum(case when status = "hadir_digantikan" then 1 else 0 end) as hadir_digantikan')
            ->first();

        $actualAttendance = $stats->hadir_mengajar + $stats->hadir_digantikan;
        $attendanceRate = $stats->total > 0 ? round(($actualAttendance / $stats->total) * 100) : 0;

        $currentMonthCount = RekapanSiswa::where(function($query) use ($siswaId, $kelasId) {
                $query->where('siswa_id', $siswaId)
                      ->orWhere('kelas_id', $kelasId);
            })
            ->whereYear('tanggal', now()->year)
            ->whereMonth('tanggal', now()->month)
            ->count();

        $daysWithAttendance = RekapanSiswa::where(function($query) use ($siswaId, $kelasId) {
                $query->where('siswa_id', $siswaId)
                      ->orWhere('kelas_id', $kelasId);
            })
            ->whereYear('tanggal', now()->year)
            ->whereMonth('tanggal', now()->month)
            ->distinct('tanggal')
            ->count('tanggal');

        $frequency = $daysWithAttendance > 0 ? 
            round($currentMonthCount / $daysWithAttendance, 1) : 0;

        $totalChart = $weeklyStats->pluck('total')->toArray();
        $hadirChart = $weeklyStats->pluck('hadir')->toArray();
        $tidakHadirChart = $weeklyStats->pluck('tidak_hadir')->toArray();
        $digantikanChart = $weeklyStats->pluck('digantikan')->toArray();
        $attendanceRateChart = $weeklyStats->map(function ($day) {
            $total = $day['total'] ?: 1;
            return round(($day['hadir'] + $day['digantikan']) / $total * 100);
        })->toArray();

        return [
            Stat::make('Total Sesi', $stats->total ?? 0)
                ->description('Seluruh sesi pembelajaran')
                ->descriptionIcon('heroicon-o-clipboard-document-list', IconPosition::Before)
                ->chart($totalChart)
                ->color('primary'),
                
            Stat::make('Kehadiran Guru', $attendanceRate . '%')
                ->description($actualAttendance . ' dari ' . $stats->total . ' sesi')
                ->descriptionIcon('heroicon-o-hand-thumb-up', IconPosition::Before)
                ->chart($attendanceRateChart)
                ->color($attendanceRate >= 80 ? 'success' : 
                      ($attendanceRate >= 60 ? 'warning' : 'danger')),
                
            Stat::make('Intensitas Mengajar', 
                $frequency > 0 ? $frequency . ' sesi/hari' : 'Belum ada data'
            )
            ->description('Pada ' . $daysWithAttendance . ' hari aktif')
            ->descriptionIcon('heroicon-o-calendar-days', IconPosition::Before)
            ->chart($totalChart)
            ->color('info'),

            Stat::make('Guru Hadir', $stats->hadir_mengajar ?? 0)
                ->description('Diajar oleh guru utama')
                ->descriptionIcon('heroicon-o-user', IconPosition::Before)
                ->chart($hadirChart)
                ->color('success'),
                
            Stat::make('Tidak Hadir', $stats->tidak_mengajar ?? 0)
                ->description('Guru tidak mengajar')
                ->descriptionIcon('heroicon-o-user-minus', IconPosition::Before)
                ->chart($tidakHadirChart)
                ->color('danger'),
            
            Stat::make('Digantikan', $stats->hadir_digantikan ?? 0)
                ->description('Diajar oleh guru pengganti')
                ->descriptionIcon('heroicon-o-users', IconPosition::Before)
                ->chart($digantikanChart)
                ->color('warning'),
        ];
    }

    protected function getChartData(): array
    {
        $siswaId = Auth::id();
        $kelasId = Auth::user()->siswa->kelas_id;

        $data = RekapanSiswa::where(function($query) use ($siswaId, $kelasId) {
                $query->where('siswa_id', $siswaId)
                      ->orWhere('kelas_id', $kelasId);
            })
            ->selectRaw('DATE_FORMAT(tanggal, "%Y-%m") as month, count(*) as total')
            ->groupBy('month')
            ->orderBy('month')
            ->pluck('total')
            ->toArray();
            
        return count($data) > 0 ? $data : [0];
    }
}