<?php

namespace App\Filament\Widgets;

use App\Models\ProjectCharter;
use BezhanSalleh\FilamentShield\Traits\HasWidgetShield;
use Filament\Support\RawJs;
use Filament\Widgets\Concerns\InteractsWithPageFilters;
use Leandrocfe\FilamentApexCharts\Widgets\ApexChartWidget;

class ProjectCharterStatusChart extends ApexChartWidget
{
    use HasWidgetShield;
    use InteractsWithPageFilters;

    /**
     * Chart Id
     */
    protected static ?string $chartId = 'projectCharterStatusChart';

    protected static bool $isLazy = false;

    protected static ?string $pollingInterval = null;

    /**
     * Widget Title
     */
    protected static ?string $heading = null;

    protected static ?int $sort = 3;

    public function getHeading(): string
    {
        return __('pages.projects_dashboard').' - '.__('widgets.project_charters_by_status');
    }

    /**
     * Chart options (series, labels, types, size, animations...)
     * https://apexcharts.com/docs/options
     */
    protected function getOptions(): array
    {
        // Get filter values
        $selectedYear = $this->filters['year'] ?? null;
        $selectedDepartmentId = $this->filters['department_id'] ?? null;
        $selectedWalletId = $this->filters['performance_wallet_id'] ?? null;
        $selectedInitiativeId = $this->filters['initiative_id'] ?? null;

        // Build query with filters
        $query = ProjectCharter::query();

        // Apply year filter
        if ($selectedYear) {
            $query->where(function ($subQuery) use ($selectedYear) {
                $subQuery->whereYear('start_date', $selectedYear)
                    ->orWhereYear('expected_end_date', $selectedYear);
            });
        }

        if ($selectedInitiativeId) {
            $query->whereHas('initiativeProject', function ($q) use ($selectedInitiativeId) {
                $q->where('initiative_id', $selectedInitiativeId);
            });
        } elseif ($selectedWalletId) {
            $query->whereHas('initiativeProject.initiative', function ($q) use ($selectedWalletId) {
                $q->where('performance_wallet_id', $selectedWalletId);
            });
        } elseif ($selectedDepartmentId) {
            $query->whereHas('initiativeProject.initiative.performanceWallet.performanceCard', function ($q) use ($selectedDepartmentId) {
                $q->where('department_id', $selectedDepartmentId);
            });
        }

        // Get all project charters
        $charters = $query->get();

        // Initialize status counts
        $statusCounts = [
            'not_started' => 0,
            'in_progress' => 0,
            'late' => 0,
            'done' => 0,
        ];

        // Count charters by their project status
        foreach ($charters as $charter) {
            $status = $charter->project_status;
            if (isset($statusCounts[$status])) {
                $statusCounts[$status]++;
            }
        }

        $data = [];
        $labels = [];
        $colors = [];

        // Material Design color palette with meaningful status colors
        $statusColors = [
            'not_started' => '#607D8B', // Material Blue Grey
            'in_progress' => '#2196F3', // Material Blue
            'late' => '#F44336',        // Material Red
            'done' => '#4CAF50',        // Material Green
        ];

        // Status labels
        $statusLabels = [
            'not_started' => __('project_charter.project_status_not_started'),
            'in_progress' => __('project_charter.project_status_in_progress'),
            'late' => __('project_charter.project_status_late'),
            'done' => __('project_charter.project_status_done'),
        ];

        // Only include statuses that have data
        foreach ($statusCounts as $status => $count) {
            if ($count > 0) {
                $data[] = $count;
                $labels[] = $statusLabels[$status];
                $colors[] = $statusColors[$status];
            }
        }

        // Handle empty data case
        if (empty($data)) {
            return [
                'chart' => [
                    'type' => 'donut',
                    'height' => 400,
                    'fontFamily' => 'inherit',
                ],
                'series' => [1],
                'labels' => [__('widgets.no_project_charters')],
                'colors' => ['#E5E7EB'],
                'dataLabels' => [
                    'enabled' => true,
                    'style' => [
                        'fontFamily' => 'inherit',
                        'fontWeight' => 600,
                    ],
                ],
                'legend' => [
                    'show' => true,
                    'position' => 'bottom',
                    'fontFamily' => 'inherit',
                    'fontWeight' => 500,
                    'fontSize' => '14px',
                    'itemMargin' => [
                        'horizontal' => 5,
                        'vertical' => 4,
                    ],
                ],
                'plotOptions' => [
                    'pie' => [
                        'donut' => [
                            'size' => '60%',
                            'labels' => [
                                'show' => true,
                                'name' => [
                                    'show' => true,
                                    'fontFamily' => 'inherit',
                                    'fontWeight' => 600,
                                ],
                                'value' => [
                                    'show' => true,
                                    'fontFamily' => 'inherit',
                                    'fontWeight' => 700,
                                    'fontSize' => '24px',
                                ],
                                'total' => [
                                    'show' => true,
                                    'label' => __('widgets.total_project_charters'),
                                    'fontFamily' => 'inherit',
                                    'fontWeight' => 600,
                                ],
                            ],
                        ],
                    ],
                ],
                'stroke' => [
                    'width' => 2,
                    'colors' => ['transparent'],
                ],
            ];
        }

        return [
            'chart' => [
                'type' => 'donut',
                'height' => 400,
                'fontFamily' => 'inherit',
                'animations' => [
                    'enabled' => true,
                    'easing' => 'easeinout',
                    'speed' => 800,
                    'animateGradually' => [
                        'enabled' => true,
                        'delay' => 150,
                    ],
                ],
            ],
            'series' => $data,
            'labels' => $labels,
            'colors' => $colors,
            'dataLabels' => [
                'enabled' => true,
                'style' => [
                    'fontFamily' => 'inherit',
                    'fontWeight' => 600,
                    'fontSize' => '12px',
                    'colors' => ['#ffffff'],
                ],
                'dropShadow' => [
                    'enabled' => true,
                    'top' => 1,
                    'left' => 1,
                    'blur' => 1,
                    'opacity' => 0.5,
                ],
                'formatter' => null, // Will be handled by JavaScript
            ],
            'legend' => [
                'show' => true,
                'position' => 'bottom',
                'fontFamily' => 'inherit',
                'fontWeight' => 500,
                'fontSize' => '14px',
                'itemMargin' => [
                    'horizontal' => 5,
                    'vertical' => 4,
                ],
                'markers' => [
                    'width' => 8,
                    'height' => 8,
                    'radius' => 2,
                    'offsetX' => 0,
                    'offsetY' => 0,
                ],
                'onItemClick' => [
                    'toggleDataSeries' => true, // Enable clicking on legend items to toggle data
                ],
                'onItemHover' => [
                    'highlightDataSeries' => true, // Enable hover highlighting from legend
                ],
            ],
            'plotOptions' => [
                'pie' => [
                    'donut' => [
                        'size' => '65%',
                        'labels' => [
                            'show' => true,
                            'name' => [
                                'show' => true,
                                'fontFamily' => 'inherit',
                                'fontWeight' => 600,
                                'fontSize' => '14px',
                                'offsetY' => -5,
                            ],
                            'value' => [
                                'show' => true,
                                'fontFamily' => 'inherit',
                                'fontWeight' => 700,
                                'fontSize' => '28px',
                                'offsetY' => 5,
                            ],
                            'total' => [
                                'show' => true,
                                'label' => __('widgets.total_project_charters'),
                                'fontFamily' => 'inherit',
                                'fontWeight' => 600,
                                'fontSize' => '14px',
                                'color' => '#64748B',
                            ],
                        ],
                    ],
                ],
            ],
            'stroke' => [
                'width' => 2,
                'colors' => ['transparent'],
            ],
            'states' => [
                'hover' => [
                    'filter' => [
                        'type' => 'lighten',
                        'value' => 0.1,
                    ],
                ],
                'active' => [
                    'allowMultipleDataPointsSelection' => false,
                    'filter' => [
                        'type' => 'darken',
                        'value' => 0.1,
                    ],
                ],
            ],
        ];
    }

    /**
     * Add custom JavaScript for enhanced formatting and hover effects
     */
    protected function extraJsOptions(): ?RawJs
    {
        return RawJs::make(<<<'JS'
        {
            dataLabels: {
                formatter: function(val, opts) {
                    if (val >= 5) {
                        return Math.round(val) + '%';
                    }
                    return '';
                }
            },
            plotOptions: {
                pie: {
                    donut: {
                        labels: {
                            name: {
                                formatter: function(val) {
                                    return val;
                                }
                            },
                            value: {
                                formatter: function(val) {
                                    return parseInt(val);
                                }
                            },
                            total: {
                                formatter: function(w) {
                                    const total = w.globals.seriesTotals.reduce((a, b) => a + b, 0);
                                    return total;
                                }
                            }
                        }
                    }
                }
            },
            tooltip: {
                enabled: false,
            },
            states: {
                hover: {
                    filter: {
                        type: 'lighten',
                        value: 0.08
                    }
                },
                active: {
                    allowMultipleDataPointsSelection: false,
                    filter: {
                        type: 'darken',
                        value: 0.1
                    }
                }
            }
        }
        JS);
    }
}
