<?php

namespace App\Filament\Guru\Widgets;

use App\Models\RekapanGuru;
use Filament\Support\Enums\IconPosition;
use Filament\Widgets\StatsOverviewWidget as BaseWidget;
use Filament\Widgets\StatsOverviewWidget\Stat;
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
    {
        $guruId = Auth::id();
        
        // Get weekly data for all statuses in one query
        $weeklyData = RekapanGuru::where('guru_id', $guruId)
            ->whereBetween('tanggal', [now()->subDays(6), now()])
            ->select([
                DB::raw('DATE(tanggal) as date'),
                DB::raw('COUNT(*) as total'),
                DB::raw('SUM(CASE WHEN status = "terlaksana" THEN 1 ELSE 0 END) as terlaksana'),
                DB::raw('SUM(CASE WHEN status = "tidak_terlaksana" THEN 1 ELSE 0 END) as tidak_terlaksana'),
                DB::raw('SUM(CASE WHEN status = "digantikan" THEN 1 ELSE 0 END) as digantikan')
            ])
            ->groupBy('date')
            ->orderBy('date')
            ->get();

        // Fill missing days with zeros
        $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,
                'terlaksana' => $record->terlaksana ?? 0,
                'tidak_terlaksana' => $record->tidak_terlaksana ?? 0,
                'digantikan' => $record->digantikan ?? 0,
            ];
        });

        // Main statistics
        $stats = RekapanGuru::where('guru_id', $guruId)
            ->selectRaw('count(*) as total')
            ->selectRaw('sum(case when status = "terlaksana" then 1 else 0 end) as terlaksana')
            ->selectRaw('sum(case when status = "tidak_terlaksana" then 1 else 0 end) as tidak_terlaksana')
            ->selectRaw('sum(case when status = "digantikan" then 1 else 0 end) as digantikan')
            ->first();

        $actualTeaching = $stats->total - $stats->tidak_terlaksana;
        $completionRate = $stats->total > 0 ? round(($actualTeaching / $stats->total) * 100) : 0;

        // Monthly frequency data
        $currentMonthCount = RekapanGuru::where('guru_id', $guruId)
            ->whereYear('tanggal', now()->year)
            ->whereMonth('tanggal', now()->month)
            ->count();

        $daysWithTeaching = RekapanGuru::where('guru_id', $guruId)
            ->whereYear('tanggal', now()->year)
            ->whereMonth('tanggal', now()->month)
            ->distinct('tanggal')
            ->count('tanggal');

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

        // Prepare chart data arrays
        $totalChart = $weeklyStats->pluck('total')->toArray();
        $terlaksanaChart = $weeklyStats->pluck('terlaksana')->toArray();
        $tidakTerlaksanaChart = $weeklyStats->pluck('tidak_terlaksana')->toArray();
        $digantikanChart = $weeklyStats->pluck('digantikan')->toArray();
        $completionRateChart = $weeklyStats->map(function ($day) {
            $total = $day['total'] ?: 1;
            return round(($day['terlaksana'] + $day['digantikan']) / $total * 100);
        })->toArray();

        return [
            Stat::make('Total Mengajar', $stats->total ?? 0)
                ->description('Seluruh sesi yang diajarkan')
                ->descriptionIcon('heroicon-o-book-open', IconPosition::Before)
                ->chart($totalChart)
                ->color('primary'),
                
            Stat::make('Hasil Mengajar', $completionRate . '%')
                ->description($actualTeaching . ' dari ' . $stats->total . ' sesi')
                ->descriptionIcon('heroicon-o-hand-thumb-up', IconPosition::Before)
                ->chart($completionRateChart)
                ->color($completionRate >= 80 ? 'success' : 
                      ($completionRate >= 60 ? 'warning' : 'danger')),
                
            Stat::make('Intensitas Mengajar', 
                $frequency > 0 ? $frequency . ' sesi/hari' : 'Belum ada data'
            )
            ->description('Pada ' . $daysWithTeaching . ' hari aktif')
            ->descriptionIcon('heroicon-o-calendar-days', IconPosition::Before)
            ->chart($totalChart)
            ->color('info'),

            Stat::make('Terlaksana', $stats->terlaksana ?? 0)
                ->description('Sesi berjalan normal')
                ->descriptionIcon('heroicon-o-check-circle', IconPosition::Before)
                ->chart($terlaksanaChart)
                ->color('success'),
                
            Stat::make('Tidak Terlaksana', $stats->tidak_terlaksana ?? 0)
                ->description('Sesi tidak berjalan normal')
                ->descriptionIcon('heroicon-o-x-circle', IconPosition::Before)
                ->chart($tidakTerlaksanaChart)
                ->color('danger'),
            
            Stat::make('Digantikan', $stats->digantikan ?? 0)
                ->description('Sesi diajar guru lain')
                ->descriptionIcon('heroicon-o-arrow-path', IconPosition::Before)
                ->chart($digantikanChart)
                ->color('warning'),
        ];
    }

    protected function getChartData(): array
    {
        $data = RekapanGuru::where('guru_id', Auth::id())
            ->selectRaw('DATE_FORMAT(tanggal, "%Y-%m") as month, count(*) as total')
            ->groupBy('month')
            ->orderBy('month')
            ->pluck('total')
            ->toArray();
            
        return count($data) > 0 ? $data : [0];
    }
}