<?php

namespace App\Filament\Employee\Widgets;

use App\Models\Activity;
use App\Models\Attendance;
use App\Models\Holiday;
use Carbon\Carbon;
use Filament\Widgets\Widget;

class PriorityTasksWidget extends Widget
{
    protected static string $view = 'filament.employee.widgets.priority-tasks-widget';

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

    protected static ?int $sort = 0;

    public function getTasks(): array
    {
        $user = auth()->user();
        $company = $user->company;
        $backdateEnabled = $company?->backdate_enabled ?? false;
        $editableEnabled = $company?->allow_editable_location ?? false;

        $tasks = [];
        $today = now();
        $startOfMonth = $today->copy()->startOfMonth();

        // Cutoff untuk backdate (tanggal 10 bulan berikutnya)
        $cutoffDate = $today->copy()->startOfMonth()->addMonth()->setDay(10);

        // Get holidays for the month
        $holidays = Holiday::whereBetween('date', [$startOfMonth, $today])
            ->pluck('date')
            ->map(fn($d) => Carbon::parse($d)->format('Y-m-d'))
            ->toArray();

        // Get attendances for the month
        $attendances = Attendance::where('user_id', $user->id)
            ->whereBetween('date', [$startOfMonth, $today])
            ->get()
            ->keyBy(fn($a) => Carbon::parse($a->date)->format('Y-m-d'));

        // Get activities for the month
        $activities = Activity::where('user_id', $user->id)
            ->whereBetween('date', [$startOfMonth, $today])
            ->get()
            ->keyBy(fn($a) => Carbon::parse($a->date)->format('Y-m-d'));

        // 1. Missing Attendances (only if backdate enabled)
        if ($backdateEnabled) {
            $missingAttendances = [];
            $current = $startOfMonth->copy();

            while ($current < $today) {
                $dateStr = $current->format('Y-m-d');
                $isWeekend = $current->isWeekend();
                $isHoliday = in_array($dateStr, $holidays);
                $hasAttendance = $attendances->has($dateStr);

                if (!$isWeekend && !$isHoliday && !$hasAttendance) {
                    $missingAttendances[] = [
                        'date' => $dateStr,
                        'formatted' => $current->translatedFormat('D, d M'),
                    ];
                }

                $current->addDay();
            }

            if (count($missingAttendances) > 0) {
                $tasks[] = [
                    'type' => 'missing_attendance',
                    'priority' => 'high',
                    'icon' => 'heroicon-o-exclamation-triangle',
                    'color' => 'danger',
                    'title' => 'Kehadiran Belum Diisi',
                    'description' => count($missingAttendances) . ' hari belum ada data kehadiran',
                    'items' => array_slice($missingAttendances, 0, 5),
                    'total' => count($missingAttendances),
                    'action_url' => route('filament.employee.resources.my-attendances.index'),
                    'action_label' => 'Lengkapi Kehadiran',
                ];
            }

            // 2. Incomplete Attendances (no checkout)
            $incompleteAttendances = $attendances->filter(function ($att) {
                return $att->check_in_time && !$att->check_out_time;
            });

            if ($incompleteAttendances->count() > 0) {
                $items = $incompleteAttendances->map(function ($att) {
                    return [
                        'date' => Carbon::parse($att->date)->format('Y-m-d'),
                        'formatted' => Carbon::parse($att->date)->translatedFormat('D, d M'),
                        'check_in' => Carbon::parse($att->check_in_time)->format('H:i'),
                    ];
                })->values()->take(5)->toArray();

                $tasks[] = [
                    'type' => 'incomplete_attendance',
                    'priority' => 'medium',
                    'icon' => 'heroicon-o-clock',
                    'color' => 'warning',
                    'title' => 'Belum Checkout',
                    'description' => $incompleteAttendances->count() . ' hari belum checkout',
                    'items' => $items,
                    'total' => $incompleteAttendances->count(),
                    'action_url' => route('filament.employee.resources.my-attendances.index'),
                    'action_label' => 'Lengkapi Checkout',
                ];
            }
        }

        // 3. Missing Activities (always shown)
        $missingActivities = [];
        $current = $startOfMonth->copy();

        while ($current < $today) {
            $dateStr = $current->format('Y-m-d');
            $isWeekend = $current->isWeekend();
            $isHoliday = in_array($dateStr, $holidays);
            $hasAttendance = $attendances->has($dateStr);
            $hasActivity = $activities->has($dateStr);

            // Jika ada attendance tapi tidak ada activity
            if (!$isWeekend && !$isHoliday && $hasAttendance && !$hasActivity) {
                $att = $attendances->get($dateStr);
                // Skip jika status adalah sick, leave, permission
                if (!in_array($att->status, ['sick', 'leave', 'permission', 'absent'])) {
                    $missingActivities[] = [
                        'date' => $dateStr,
                        'formatted' => $current->translatedFormat('D, d M'),
                        'type' => $att->type,
                    ];
                }
            }

            $current->addDay();
        }

        if (count($missingActivities) > 0) {
            $tasks[] = [
                'type' => 'missing_activity',
                'priority' => $backdateEnabled ? 'medium' : 'high',
                'icon' => 'heroicon-o-clipboard-document-list',
                'color' => $backdateEnabled ? 'warning' : 'danger',
                'title' => 'Aktivitas Belum Diisi',
                'description' => count($missingActivities) . ' hari belum ada catatan aktivitas',
                'items' => array_slice($missingActivities, 0, 5),
                'total' => count($missingActivities),
                'action_url' => route('filament.employee.resources.my-activities.index'),
                'action_label' => 'Isi Aktivitas',
            ];
        }

        // 4. Activities without Output
        $activitiesWithoutOutput = Activity::where('user_id', $user->id)
            ->whereBetween('date', [$startOfMonth, $today])
            ->where(function ($q) {
                $q->whereNull('output')->orWhere('output', '');
            })
            ->orderBy('date', 'desc')
            ->get();

        if ($activitiesWithoutOutput->count() > 0) {
            $items = $activitiesWithoutOutput->take(5)->map(function ($act) {
                return [
                    'date' => Carbon::parse($act->date)->format('Y-m-d'),
                    'formatted' => Carbon::parse($act->date)->translatedFormat('D, d M'),
                    'activity' => \Str::limit($act->activity, 30),
                ];
            })->toArray();

            $tasks[] = [
                'type' => 'missing_output',
                'priority' => 'low',
                'icon' => 'heroicon-o-document-text',
                'color' => 'info',
                'title' => 'Output Belum Diisi',
                'description' => $activitiesWithoutOutput->count() . ' aktivitas belum ada output',
                'items' => $items,
                'total' => $activitiesWithoutOutput->count(),
                'action_url' => route('filament.employee.resources.my-activities.index'),
                'action_label' => 'Lengkapi Output',
            ];
        }

        // Sort by priority
        usort($tasks, function ($a, $b) {
            $priorityOrder = ['high' => 0, 'medium' => 1, 'low' => 2];
            return $priorityOrder[$a['priority']] <=> $priorityOrder[$b['priority']];
        });

        return $tasks;
    }

    public function getSettings(): array
    {
        $user = auth()->user();
        $company = $user->company;

        return [
            'backdate_enabled' => $company?->backdate_enabled ?? false,
            'editable_enabled' => $company?->allow_editable_location ?? false,
        ];
    }
}
