<?php

namespace App\Filament\Widgets;

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

class ProjectStatusChart extends ApexChartWidget
{
    use HasWidgetShield;
    use InteractsWithPageFilters;

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

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

    protected static bool $isLazy = false;

    protected static ?string $pollingInterval = null;

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

    /**
     * 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 base query with filters
        $baseQuery = ProjectCharter::query();

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

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

        $initiationCount = (clone $baseQuery)->whereIn('status', [
            ProjectCharter::STATUS_DRAFT,
            ProjectCharter::STATUS_AWAITING_APPROVAL,
        ])->count();

        $executionCount = (clone $baseQuery)->where('status', ProjectCharter::STATUS_APPROVED)->count();

        $closureCount = (clone $baseQuery)->whereIn('status', [
            ProjectCharter::STATUS_COMPLETED,
            ProjectCharter::STATUS_CANCELED,
            ProjectCharter::STATUS_REJECTED,
            ProjectCharter::STATUS_SUSPENDED,
        ])->count();

        $data = [$initiationCount, $executionCount, $closureCount];
        $categories = [
            __('project_charter.initiation'),
            __('project_charter.execution'),
            __('project_charter.closure'),
        ];
        $colors = ['#FBBF24', '#22C55E', '#EF4444'];

        if (array_sum($data) === 0) {
            return [
                'chart' => [
                    'type' => 'bar',
                    'height' => 350,
                    'fontFamily' => 'inherit',
                ],
                'series' => [
                    [
                        'name' => __('widgets.no_data_available'),
                        'data' => [0],
                    ],
                ],
                'xaxis' => [
                    'categories' => [__('widgets.no_projects')],
                    'labels' => [
                        'style' => [
                            'fontFamily' => 'inherit',
                            'fontSize' => '12px',
                        ],
                    ],
                ],
                'yaxis' => [
                    'labels' => [
                        'style' => [
                            'fontFamily' => 'inherit',
                            'fontSize' => '12px',
                        ],
                    ],
                ],
                'colors' => ['#E5E7EB'],
                'dataLabels' => [
                    'enabled' => false,
                ],
                'legend' => [
                    'show' => false,
                ],
            ];
        }

        return [
            'chart' => [
                'type' => 'bar',
                'height' => 400,
                'fontFamily' => 'inherit',
                'animations' => [
                    'enabled' => true,
                    'easing' => 'easeinout',
                    'speed' => 800,
                ],
            ],
            'plotOptions' => [
                'bar' => [
                    'horizontal' => false,
                    'borderRadius' => 6,
                    'columnWidth' => '50%',
                    'distributed' => true,
                ],
            ],
            'dataLabels' => [
                'enabled' => true,
            ],
            'series' => [
                [
                    'name' => __('widgets.num_of_projects'),
                    'data' => $data,
                ],
            ],
            'xaxis' => [
                'categories' => $categories,
                'labels' => [
                    'style' => [
                        'fontSize' => '14px',
                        'fontWeight' => 600,
                    ],
                ],
            ],
            'colors' => $colors,
            'legend' => [
                'show' => false,
            ],
            'grid' => [
                'borderColor' => '#E5E7EB',
                'strokeDashArray' => 4,
            ],
        ];
    }
}
