<?php

namespace App\Filament\Widgets;

use App\Models\Order;
use BezhanSalleh\FilamentShield\Traits\HasWidgetShield;
use Filament\Widgets\ChartWidget;
use Filament\Widgets\Concerns\InteractsWithPageFilters;

class ClassificationOrdersValuesPieChart extends ChartWidget
{
    use HasWidgetShield, InteractsWithPageFilters;

    protected static ?string $heading = null;

    public static ?int $sort = 3;

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

    protected function getData(): array
    {
        // Get filter values
        $selectedYear = $this->filters['year'] ?? null;
        $selectedProjectType = $this->filters['project_type'] ?? null;

        // Build base query for classification orders with financial data
        $query = Order::where('status', Order::STATUS_CLASSIFICATION)
            ->filterByTypePermissions()
            ->whereHas('finance');

        if ($selectedYear) {
            $query->whereYear('created_at', $selectedYear);
        }

        if ($selectedProjectType) {
            $query->where('type', $selectedProjectType);
        }

        // Get orders with finance data grouped by type
        $orders = $query->with(['finance'])
            ->get()
            ->groupBy('type');

        if ($orders->isEmpty()) {
            return [
                'datasets' => [
                    [
                        'label' => __('widgets.order_values_by_type'),
                        'data' => [0],
                        'backgroundColor' => ['#f3f4f6'],
                    ],
                ],
                'labels' => [__('widgets.no_classification_orders')],
            ];
        }

        $labels = [];
        $data = [];
        $colors = [
            '#3b82f6', // blue
            '#ef4444', // red
            '#10b981', // emerald
            '#f59e0b', // amber
            '#8b5cf6', // violet
            '#06b6d4', // cyan
            '#84cc16', // lime
            '#f97316', // orange
            '#ec4899', // pink
            '#6b7280', // gray
        ];

        foreach ($orders as $type => $typeOrders) {
            $orderTypes = Order::getOrderTypes();
            $labels[] = $orderTypes[$type] ?? $type;

            $totalValue = $typeOrders->sum(function ($order) {
                return $order->finance ? $order->finance->approved_price : 0;
            });

            $data[] = round($totalValue, 2);
        }

        return [
            'datasets' => [
                [
                    'label' => __('widgets.order_values_by_type'),
                    'data' => $data,
                    'backgroundColor' => array_slice($colors, 0, count($data)),
                ],
            ],
            'labels' => $labels,
        ];
    }

    protected function getType(): string
    {
        return 'pie';
    }

    protected function getOptions(): array
    {
        return [
            'plugins' => [
                'legend' => [
                    'display' => true,
                    'position' => 'bottom',
                ],
            ],
            'responsive' => true,
            'maintainAspectRatio' => false,
        ];
    }
}
