<?php

namespace App\Filament\Widgets\HRD;

use App\Models\AttendanceCorrection;
use App\Models\EarlyLeaveRequest;
use App\Models\LateArrivalRequest;
use App\Models\User;
use Carbon\Carbon;
use Filament\Widgets\StatsOverviewWidget as BaseWidget;
use Filament\Widgets\StatsOverviewWidget\Stat;

class HRDStatsWidget extends BaseWidget
{
    protected static ?string $pollingInterval = '30s';

    protected static ?int $sort = 1;

    protected int | string | array $columnSpan = 'full';

    protected function getStats(): array
    {
        $today = now()->toDateString();
        $thisMonth = now()->month;
        $thisYear = now()->year;

        // Pending approvals
        $pendingCorrections = AttendanceCorrection::where('status', 'pending')->count();
        $pendingLateArrival = LateArrivalRequest::where('status', 'pending')->count();
        $pendingEarlyLeave = EarlyLeaveRequest::where('status', 'pending')->count();
        $totalPending = $pendingCorrections + $pendingLateArrival + $pendingEarlyLeave;

        // New employees this month
        $newEmployees = User::whereMonth('created_at', $thisMonth)
            ->whereYear('created_at', $thisYear)
            ->whereDoesntHave('roles', fn ($q) => $q->where('name', 'super_admin'))
            ->count();

        // Pending user approvals
        $pendingUserApprovals = User::where('approval_status', 'pending')
            ->whereDoesntHave('roles', fn ($q) => $q->where('name', 'super_admin'))
            ->count();

        // Attendance today
        $attendanceToday = \App\Models\Attendance::whereDate('date', $today)
            ->whereHas('user', fn ($q) => $q->whereDoesntHave('roles', fn ($r) => $r->where('name', 'super_admin')))
            ->count();

        $activeUsers = User::where('is_active', true)
            ->whereDoesntHave('roles', fn ($q) => $q->where('name', 'super_admin'))
            ->count();

        return [
            Stat::make('Pengajuan Menunggu', $totalPending)
                ->description($pendingCorrections . ' koreksi, ' . $pendingLateArrival . ' terlambat, ' . $pendingEarlyLeave . ' pulang cepat')
                ->descriptionIcon('heroicon-m-clock')
                ->color($totalPending > 0 ? 'warning' : 'success')
                ->chart($this->getPendingRequestsTrend())
                ->extraAttributes([
                    'class' => 'cursor-pointer',
                ]),

            Stat::make('Karyawan Baru', $newEmployees)
                ->description('Bulan ini')
                ->descriptionIcon('heroicon-m-user-plus')
                ->color('info')
                ->chart($this->getNewEmployeesTrend())
                ->extraAttributes([
                    'class' => 'cursor-pointer',
                ]),

            Stat::make('User Menunggu Approval', $pendingUserApprovals)
                ->description($pendingUserApprovals > 0 ? 'Perlu verifikasi' : 'Semua terverifikasi')
                ->descriptionIcon($pendingUserApprovals > 0 ? 'heroicon-m-exclamation-triangle' : 'heroicon-m-check-circle')
                ->color($pendingUserApprovals > 0 ? 'warning' : 'success')
                ->chart($this->getPendingUsersTrend())
                ->extraAttributes([
                    'class' => 'cursor-pointer',
                ]),

            Stat::make('Kehadiran Hari Ini', $attendanceToday . ' / ' . $activeUsers)
                ->description(round(($attendanceToday / max($activeUsers, 1)) * 100, 1) . '% dari total karyawan')
                ->descriptionIcon('heroicon-m-calendar')
                ->color($attendanceToday >= $activeUsers * 0.9 ? 'success' : ($attendanceToday >= $activeUsers * 0.7 ? 'warning' : 'danger'))
                ->chart($this->getAttendanceTodayTrend())
                ->extraAttributes([
                    'class' => 'cursor-pointer',
                ]),
        ];
    }

    private function getPendingRequestsTrend(): array
    {
        $trend = [];
        for ($i = 6; $i >= 0; $i--) {
            $date = now()->subDays($i)->toDateString();
            $trend[] = AttendanceCorrection::whereDate('created_at', $date)
                    ->where('status', 'pending')
                    ->count() +
                LateArrivalRequest::whereDate('created_at', $date)
                    ->where('status', 'pending')
                    ->count() +
                EarlyLeaveRequest::whereDate('created_at', $date)
                    ->where('status', 'pending')
                    ->count();
        }
        return $trend;
    }

    private function getNewEmployeesTrend(): array
    {
        $trend = [];
        for ($i = 6; $i >= 0; $i--) {
            $date = now()->subDays($i)->toDateString();
            $trend[] = User::whereDate('created_at', $date)
                ->whereDoesntHave('roles', fn ($q) => $q->where('name', 'super_admin'))
                ->count();
        }
        return $trend;
    }

    private function getPendingUsersTrend(): array
    {
        $trend = [];
        for ($i = 6; $i >= 0; $i--) {
            $date = now()->subDays($i)->toDateString();
            $trend[] = User::whereDate('created_at', '<=', $date)
                ->where('approval_status', 'pending')
                ->whereDoesntHave('roles', fn ($q) => $q->where('name', 'super_admin'))
                ->count();
        }
        return $trend;
    }

    private function getAttendanceTodayTrend(): array
    {
        $trend = [];
        for ($i = 6; $i >= 0; $i--) {
            $date = now()->subDays($i)->toDateString();
            $trend[] = \App\Models\Attendance::whereDate('date', $date)
                ->whereHas('user', fn ($q) => $q->whereDoesntHave('roles', fn ($r) => $r->where('name', 'super_admin')))
                ->count();
        }
        return $trend;
    }
}
