<?php

namespace App\Filament\Guru\Widgets;

use App\Models\RekapanSiswa;
use Flowframe\Trend\Trend;
use Filament\Forms\Components\DatePicker;
use Leandrocfe\FilamentApexCharts\Widgets\ApexChartWidget;
use Illuminate\Support\Carbon;

class RekapanSiswaOverview extends ApexChartWidget
{
    protected static ?string $heading = 'Rekap Kehadiran Mengajar';
    protected static ?string $chartId = 'rekapanSiswaChart';
    protected int | string | array $columnSpan = 'full';
    protected static ?string $maxHeight = '300px';
    protected static ?string $pollingInterval = '30s';
    protected static ?int $sort = 3;

    protected function getOptions(): array
    {
        try {
            $startDate = isset($this->filterFormData['date_start'])
                ? Carbon::parse($this->filterFormData['date_start'])->startOfDay()
                : now()->startOfWeek(Carbon::MONDAY);
            
            $endDate = isset($this->filterFormData['date_end'])
                ? Carbon::parse($this->filterFormData['date_end'])->endOfDay()
                : now()->endOfWeek(Carbon::SUNDAY);
        } catch (\Exception $e) {
            $startDate = now()->startOfWeek(Carbon::MONDAY);
            $endDate = now()->endOfWeek(Carbon::SUNDAY);
        }

        $hadirMengajarData = Trend::query(
            RekapanSiswa::where('status', 'hadir_mengajar')
        )
        ->between($startDate, $endDate)
        ->perDay()
        ->count();

        $tidakMengajarData = Trend::query(
            RekapanSiswa::where('status', 'tidak_mengajar')
        )
        ->between($startDate, $endDate)
        ->perDay()
        ->count();

        $hadirDigantikanData = Trend::query(
            RekapanSiswa::where('status', 'hadir_digantikan')
        )
        ->between($startDate, $endDate)
        ->perDay()
        ->count();

        $categories = ['Senin', 'Selasa', 'Rabu', 'Kamis', 'Jumat', 'Sabtu', 'Minggu'];

        $hadirMengajarMapped = array_fill(0, 7, 0);
        $tidakMengajarMapped = array_fill(0, 7, 0);
        $hadirDigantikanMapped = array_fill(0, 7, 0);

        foreach ($hadirMengajarData as $item) {
            $date = Carbon::parse($item->date);
            $dayOfWeek = $date->dayOfWeek;
            $dayIndex = $dayOfWeek === 0 ? 6 : $dayOfWeek - 1;
            
            if ($dayIndex >= 0 && $dayIndex <= 6) {
                $hadirMengajarMapped[$dayIndex] += $item->aggregate;
            }
        }

        foreach ($tidakMengajarData as $item) {
            $date = Carbon::parse($item->date);
            $dayOfWeek = $date->dayOfWeek;
            $dayIndex = $dayOfWeek === 0 ? 6 : $dayOfWeek - 1;
            
            if ($dayIndex >= 0 && $dayIndex <= 6) {
                $tidakMengajarMapped[$dayIndex] += $item->aggregate;
            }
        }

        foreach ($hadirDigantikanData as $item) {
            $date = Carbon::parse($item->date);
            $dayOfWeek = $date->dayOfWeek;
            $dayIndex = $dayOfWeek === 0 ? 6 : $dayOfWeek - 1;
            
            if ($dayIndex >= 0 && $dayIndex <= 6) {
                $hadirDigantikanMapped[$dayIndex] += $item->aggregate;
            }
        }

        $isEmpty = empty(array_filter($hadirMengajarMapped)) && 
                   empty(array_filter($tidakMengajarMapped)) && 
                   empty(array_filter($hadirDigantikanMapped));

        if ($isEmpty) {
            return [
                'chart' => [
                    'type' => 'area',
                    'height' => 300,
                    'toolbar' => ['show' => false],
                    'events' => [
                        'beforeRender' => 'function() {
                            this.updateOptions({
                                annotations: {
                                    position: "front",
                                    yaxis: [{
                                        y: 50,
                                        y2: 60,
                                        borderColor: "#e2e8f0",
                                        fillColor: "#f8fafc",
                                        label: {
                                            borderColor: "#94a3b8",
                                            style: {
                                                color: "#64748b",
                                                fontSize: "14px",
                                                background: "transparent"
                                            },
                                            text: "Belum ada data untuk periode ini",
                                            position: "center"
                                        }
                                    }]
                                },
                                yaxis: {
                                    min: 0,
                                    max: 100
                                }
                            });
                        }'
                    ]
                ],
                'series' => [
                    [
                        'name' => 'Hadir Mengajar',
                        'data' => array_fill(0, count($categories), 0)
                    ],
                    [
                        'name' => 'Tidak Mengajar',
                        'data' => array_fill(0, count($categories), 0)
                    ],
                    [
                        'name' => 'Hadir Digantikan',
                        'data' => array_fill(0, count($categories), 0)
                    ]
                ],
                'colors' => ['#e2e8f0', '#e2e8f0', '#e2e8f0'],
                'fill' => [
                    'type' => 'solid',
                    'opacity' => 0.2,
                ],
                'xaxis' => [
                    'categories' => $categories,
                    'labels' => [
                        'style' => [
                            'colors' => '#9ca3af',
                            'fontWeight' => 600,
                        ],
                    ],
                    'axisBorder' => ['show' => false],
                    'axisTicks' => ['show' => false],
                ],
                'yaxis' => [
                    'labels' => [
                        'style' => [
                            'colors' => '#9ca3af',
                            'fontWeight' => 600,
                        ],
                    ],
                    'min' => 0,
                    'max' => 100,
                    'tickAmount' => 5,
                    'forceNiceScale' => false,
                ],
                'dataLabels' => ['enabled' => false],
                'legend' => [
                    'position' => 'top',
                    'horizontalAlign' => 'right',
                ],
                'stroke' => [
                    'show' => true,
                    'width' => 2,
                    'colors' => ['transparent'],
                ],
                'tooltip' => [
                    'enabled' => false,
                ],
            ];
        }

        return [
            'chart' => [
                'type' => 'area',
                'height' => 300,
                'toolbar' => ['show' => false],
            ],
            'series' => [
                [
                    'name' => 'Hadir Mengajar',
                    'data' => $hadirMengajarMapped,
                ],
                [
                    'name' => 'Tidak Mengajar',
                    'data' => $tidakMengajarMapped,
                ],
                [
                    'name' => 'Hadir Digantikan',
                    'data' => $hadirDigantikanMapped,
                ],
            ],
            'colors' => ['#10b981', '#ef4444', '#f59e0b'],
            'xaxis' => [
                'categories' => $categories,
                'labels' => [
                    'style' => [
                        'colors' => '#9ca3af',
                        'fontWeight' => 600,
                    ],
                ],
                'axisBorder' => ['show' => false],
                'axisTicks' => ['show' => false],
            ],
            'yaxis' => [
                'labels' => [
                    'style' => [
                        'colors' => '#9ca3af',
                        'fontWeight' => 600,
                    ],
                ],
                'min' => 0,
                'tickAmount' => 5,
                'forceNiceScale' => true,
            ],
            'dataLabels' => ['enabled' => false],
            'legend' => [
                'position' => 'top',
                'horizontalAlign' => 'right',
            ],
            'stroke' => [
                'show' => true,
                'width' => 2,
                'colors' => ['transparent'],
            ],
            'tooltip' => [
                'enabled' => true,
                'shared' => true,
                'intersect' => false,
                'y' => [
                    'formatter' => 'function(val) { return val + " sesi"; }'
                ]
            ],
        ];
    }

    protected function getFormSchema(): array
    {
        return [
            DatePicker::make('date_start')
                ->label('Dari Tanggal')
                ->default(now()->startOfWeek(Carbon::MONDAY))
                ->displayFormat('d/m/Y')
                ->format('d/m/Y')
                ->native(false)
                ->closeOnDateSelection(),
            DatePicker::make('date_end')
                ->label('Sampai Tanggal')
                ->default(now()->endOfWeek(Carbon::SUNDAY))
                ->displayFormat('d/m/Y')
                ->format('d/m/Y')
                ->native(false)
                ->closeOnDateSelection(),
        ];
    }
}