<?php

namespace App\Filament\AssociationAdmin\Widgets;

use App\Models\ProjectCharter;
use BezhanSalleh\FilamentShield\Traits\HasWidgetShield;
use Filament\Support\RawJs;
use Illuminate\Support\Facades\Auth;
use Leandrocfe\FilamentApexCharts\Widgets\ApexChartWidget;

class AssociationProjectStatusChart extends ApexChartWidget
{
    use HasWidgetShield;

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

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

    protected static ?int $sort = 2;

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

    protected function getHeading(): string
    {
        return __('association-admin-dashboard.dashboard').' - '.'حالة المشاريع';
    }

    /**
     * Chart options (series, labels, types, size, animations...)
     */
    protected function getOptions(): array
    {
        $user = Auth::user();
        $association = $user?->association;

        if (! $association) {
            return [
                'chart' => [
                    'type' => 'donut',
                    'height' => 400,
                    'fontFamily' => 'inherit',
                    'animations' => [
                        'enabled' => true,
                        'easing' => 'easeinout',
                        'speed' => 800,
                    ],
                ],
                'series' => [1],
                'labels' => ['بلا بيانات'],
                'colors' => ['#F3F4F6'],
                'dataLabels' => [
                    'enabled' => false,
                ],
                'legend' => [
                    'show' => false,
                ],
                'plotOptions' => [
                    'pie' => [
                        'donut' => [
                            'size' => '65%',
                            'labels' => [
                                'show' => true,
                                'name' => [
                                    'show' => false,
                                ],
                                'value' => [
                                    'show' => false,
                                ],
                                'total' => [
                                    'show' => true,
                                    'label' => 'لا توجد جهة',
                                    'fontFamily' => 'inherit',
                                    'fontWeight' => 600,
                                    'fontSize' => '16px',
                                    'color' => '#9CA3AF',
                                ],
                            ],
                        ],
                    ],
                ],
                'stroke' => [
                    'width' => 0,
                ],
            ];
        }

        // Get project charters for this association through orders
        $projectCharters = ProjectCharter::withoutGlobalScope(\App\Scopes\ViewPermissionScope::class)->whereHas('order', function ($q) use ($association) {
            $q->where('association_id', $association->id);
        })->get();

        // Get counts by project status using the project_status attribute
        $statusCounts = [
            'جديد' => $projectCharters->filter(fn ($charter) => $charter->project_status === 'not_started')->count(),
            'قيد التنفيذ' => $projectCharters->filter(fn ($charter) => $charter->project_status === 'in_progress')->count(),
            'متأخر' => $projectCharters->filter(fn ($charter) => $charter->project_status === 'late')->count(),
            'مكتمل' => $projectCharters->filter(fn ($charter) => $charter->project_status === 'done')->count(),
        ];

        // Filter out zero values
        $statusCounts = array_filter($statusCounts, fn ($count) => $count > 0);

        // Handle case when no projects exist
        if (empty($statusCounts)) {
            return [
                'chart' => [
                    'type' => 'donut',
                    'height' => 400,
                    'fontFamily' => 'inherit',
                    'animations' => [
                        'enabled' => true,
                        'easing' => 'easeinout',
                        'speed' => 800,
                    ],
                ],
                'series' => [1],
                'labels' => ['لا توجد مشاريع'],
                'colors' => ['#F3F4F6'],
                'dataLabels' => [
                    'enabled' => false,
                ],
                'legend' => [
                    'show' => false,
                ],
                'plotOptions' => [
                    'pie' => [
                        'donut' => [
                            'size' => '65%',
                            'labels' => [
                                'show' => true,
                                'name' => [
                                    'show' => false,
                                ],
                                'value' => [
                                    'show' => false,
                                ],
                                'total' => [
                                    'show' => true,
                                    'label' => 'لا توجد مشاريع',
                                    'fontFamily' => 'inherit',
                                    'fontWeight' => 600,
                                    'fontSize' => '16px',
                                    'color' => '#9CA3AF',
                                ],
                            ],
                        ],
                    ],
                ],
                'stroke' => [
                    'width' => 0,
                ],
            ];
        }

        // Prepare data for chart
        $labels = array_keys($statusCounts);
        $series = array_values($statusCounts);

        // Define colors for different project statuses
        $colors = [
            'جديد' => '#6B7280',        // Gray
            'قيد التنفيذ' => '#3B82F6',      // Blue
            'متأخر' => '#EF4444',           // Red
            'مكتمل' => '#10B981',           // Green
        ];

        $chartColors = array_map(fn ($label) => $colors[$label] ?? '#6B7280', $labels);

        return [
            'chart' => [
                'type' => 'donut',
                'height' => 400,
                'fontFamily' => 'inherit',
                'animations' => [
                    'enabled' => true,
                    'easing' => 'easeinout',
                    'speed' => 800,
                    'animateGradually' => [
                        'enabled' => true,
                        'delay' => 150,
                    ],
                ],
            ],
            'series' => $series,
            'labels' => $labels,
            'colors' => $chartColors,
            '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' => 'إجمالي المشاريع',
                                'fontFamily' => 'inherit',
                                'fontWeight' => 600,
                                'fontSize' => '14px',
                                'color' => '#64748B',
                            ],
                        ],
                    ],
                ],
            ],
            'dataLabels' => [
                'enabled' => true,
                'style' => [
                    'fontFamily' => 'inherit',
                    'fontWeight' => 600,
                    'fontSize' => '12px',
                    'colors' => ['#ffffff'],
                ],
                'dropShadow' => [
                    'enabled' => true,
                    'top' => 1,
                    'left' => 1,
                    'blur' => 1,
                    'opacity' => 0.5,
                ],
            ],
            'legend' => [
                'show' => true,
                'position' => 'bottom',
                'fontFamily' => 'inherit',
                'fontWeight' => 500,
                'fontSize' => '14px',
                'itemMargin' => [
                    'horizontal' => 5,
                    'vertical' => 4,
                ],
                'markers' => [
                    'width' => 8,
                    'height' => 8,
                    'radius' => 2,
                ],
            ],
            '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 interactions
     */
    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: {
                            value: {
                                formatter: function(val) {
                                    return parseInt(val);
                                }
                            },
                            total: {
                                formatter: function(w) {
                                    if (w.globals.seriesTotals && w.globals.seriesTotals.length > 0) {
                                        const total = w.globals.seriesTotals.reduce((a, b) => a + b, 0);
                                        return total;
                                    }
                                    return 0;
                                }
                            }
                        }
                    }
                }
            },
            tooltip: {
                enabled: true,
                style: {
                    fontFamily: 'inherit'
                }
            }
        }
        JS);
    }
}
