<?php

namespace App\Filament\Siswa\Widgets;

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

class WeeklyChart extends ApexChartWidget
{
    protected static ?string $chartId = 'weeklyChart';
    protected static ?string $heading = 'Aktivitas Pembelajaran';
    protected int | string | array $columnSpan = 'full';
    protected static ?string $maxHeight = '300px';
    protected static ?int $sort = 2;

    protected function getOptions(): array
    {
        $siswaId = Auth::id();

        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);
        }

        $rawDataCheck = RekapanSiswa::where('siswa_id', $siswaId)
            ->whereBetween('tanggal', [$startDate, $endDate])
            ->count();

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

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

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

        $berjalanMapped = array_fill(0, 7, 0);
        $dibatalkanMapped = array_fill(0, 7, 0);

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

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

        $isEmpty = empty(array_filter($berjalanMapped)) && 
            empty(array_filter($dibatalkanMapped));

        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' => 'Sesi Berjalan', 'data' => array_fill(0, count($categories), 0)],
                    ['name' => 'Sesi Dibatalkan', 'data' => array_fill(0, count($categories), 0)]
                ],
                'colors' => ['#e2e8f0', '#e2e8f0'],
                '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,
                ],
                'plotOptions' => [
                    'bar' => [
                        'borderRadius' => 4,
                        'columnWidth' => '70%',
                    ],
                ],
                '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' => 'Sesi Berjalan',
                    'data' => $berjalanMapped,
                ],
                [
                    'name' => 'Sesi Dibatalkan',
                    'data' => $dibatalkanMapped,
                ],
            ],
            'colors' => ['#62b8ff', '#ef4444'],
            '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,
            ],
            'plotOptions' => [
                'bar' => [
                    'borderRadius' => 4,
                    'columnWidth' => '70%',
                ],
            ],
            '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(),
        ];
    }
}