<?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 ProjectCostChart extends ApexChartWidget
{
    use HasWidgetShield;
    use InteractsWithPageFilters;

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

    protected static bool $isLazy = false;

    protected static ?string $pollingInterval = null;

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

    protected static ?int $sort = 4;

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

    /**
     * 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()
            ->whereNotNull('total_cost')
            ->where('total_cost', '>', 0);

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

        $projectCharters = $query->get();

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

        // Enhanced Material Design color palette with better contrast
        $colorPalette = [
            '#3B82F6', // Blue
            '#10B981', // Emerald
            '#F59E0B', // Amber
            '#EF4444', // Red
            '#8B5CF6', // Violet
            '#EC4899', // Pink
            '#06B6D4', // Cyan
            '#F97316', // Orange
            '#6366F1', // Indigo
            '#84CC16', // Lime
            '#14B8A6', // Teal
            '#A855F7', // Purple
            '#64748B', // Slate
            '#FBBF24', // Yellow
            '#7C3AED', // Purple
        ];

        $colorIndex = 0;
        foreach ($projectCharters as $charter) {
            $data[] = (float) $charter->total_cost;
            $projectManner = $charter->project_manner;
            $labels[] = $charter->name ?? ($projectManner ? strtoupper(substr($projectManner, 0, 1)).'-'.$charter->id : '#'.$charter->id);
            $colors[] = $colorPalette[$colorIndex % count($colorPalette)];
            $colorIndex++;
        }

        // Handle empty data case
        if (empty($data)) {
            return [
                'chart' => [
                    'type' => 'donut',
                    'height' => 400,
                    'fontFamily' => 'inherit',
                ],
                'series' => [1],
                'labels' => [__('widgets.no_project_costs')],
                'colors' => ['#E5E7EB'],
                'dataLabels' => [
                    'enabled' => true,
                    'style' => [
                        'fontFamily' => 'inherit',
                        'fontWeight' => 600,
                    ],
                ],
                'legend' => [
                    'show' => false,
                    '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_costs'),
                                    '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' => array_slice($colorPalette, 0, count($data)),
            '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 for currency formatting
            ],
            'legend' => [
                'show' => false,
                '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' => false, // Disable clicking on legend items to toggle data
                ],
                'onItemHover' => [
                    'highlightDataSeries' => false, // Disable 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_costs'),
                                'fontFamily' => 'inherit',
                                'fontWeight' => 600,
                                'fontSize' => '14px',
                                'color' => '#64748B',
                            ],
                        ],
                    ],
                ],
            ],
            'tooltip' => [
                'enabled' => true,
                'style' => [
                    'fontFamily' => 'inherit',
                ],
                'marker' => [
                    'show' => false, // This removes the square marker on hover
                ],
                'y' => [
                    'formatter' => null, // Will be handled by JavaScript for currency formatting
                ],
            ],
            'stroke' => [
                'width' => 3,
                'colors' => ['transparent'],
            ],
            'states' => [
                'hover' => [
                    'filter' => [
                        'type' => 'lighten',
                        'value' => 0.1,
                    ],
                ],
                'active' => [
                    'allowMultipleDataPointsSelection' => false,
                    'filter' => [
                        'type' => 'darken',
                        'value' => 0.1,
                    ],
                ],
            ],
        ];
    }

    /**
     * Add custom JavaScript for currency formatting and enhanced UI
     */
    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) {
                                    if (val.length > 15) {
                                        return val.substring(0, 15) + '...';
                                    }
                                    return val;
                                }
                            },
                            value: {
                                formatter: function (val) {
                                    return new Intl.NumberFormat('ar', {
                                        minimumFractionDigits: 0,
                                        maximumFractionDigits: 0,
                                        notation: 'compact',
                                        compactDisplay: 'short'
                                    }).format(val);
                                }
                            },
                            total: {
                                formatter: function (w) {
                                    const total = w.globals.seriesTotals.reduce((a, b) => a + b, 0);
                                    return new Intl.NumberFormat('ar', {
                                        minimumFractionDigits: 0,
                                        maximumFractionDigits: 0,
                                        notation: 'compact',
                                        compactDisplay: 'short'
                                    }).format(total);
                                }
                            }
                        }
                    }
                }
            },
            tooltip: {
                enabled: true,
                y: {
                    formatter: function (val) {
                        return new Intl.NumberFormat('ar', {
                            minimumFractionDigits: 2,
                            maximumFractionDigits: 2
                        }).format(val);
                    }
                }
            },
            states: {
                hover: {
                    filter: {
                        type: 'lighten',
                        value: 0.08
                    }
                },
                active: {
                    allowMultipleDataPointsSelection: false,
                    filter: {
                        type: 'darken',
                        value: 0.1
                    }
                }
            }
        }
        JS);
    }
}
