<?php

namespace App\Filament\Widgets;

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

class FinancialPortfoliosExpensesChart extends ApexChartWidget
{
    use HasWidgetShield, InteractsWithPageFilters;

    protected static ?string $chartId = 'financialPortfoliosExpensesChart';

    protected static ?string $heading = null;

    protected static ?int $sort = 3;

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

    protected function getOptions(): array
    {
        // Get all donor financial portfolios with their allocations
        $portfolios = DonorFinancialPortfolio::orderBy('balance', 'desc')->get();

        $portfolioValues = [];
        $allocatedAmounts = [];
        $categories = [];

        foreach ($portfolios as $portfolio) {
            $portfolioValues[] = (float) $portfolio->balance;

            $allocated = $portfolio->total_allocated;

            $allocatedAmounts[] = (float) $allocated;
            $categories[] = $portfolio->name;
        }

        // Handle empty data case
        if (empty($portfolioValues)) {
            return [
                'chart' => [
                    'type' => 'bar',
                    'height' => 400,
                    'fontFamily' => 'inherit',
                    'toolbar' => [
                        'show' => false,
                    ],
                ],
                'series' => [
                    [
                        'name' => __('widgets.portfolio_value'),
                        'data' => [0],
                    ],
                    [
                        'name' => __('donor_financial_portfolio.allocated_amount'),
                        'data' => [0],
                    ],
                ],
                'xaxis' => [
                    'categories' => [__('widgets.no_portfolios')],
                ],
                'colors' => ['#E5E7EB', '#F3F4F6'],
            ];
        }

        return [
            'chart' => [
                'type' => 'bar',
                'height' => 400,
                'fontFamily' => 'inherit',
                'toolbar' => [
                    'show' => false,
                ],
                'direction' => 'rtl',
            ],
            'series' => [
                [
                    'name' => __('widgets.portfolio_value'),
                    'data' => $portfolioValues,
                ],
                [
                    'name' => __('donor_financial_portfolio.allocated_amount'),
                    'data' => $allocatedAmounts,
                ],
            ],
            'xaxis' => [
                'categories' => $categories,
                'labels' => [
                    'style' => [
                        'fontFamily' => 'inherit',
                        'fontWeight' => 500,
                        'fontSize' => '12px',
                    ],
                    'rotate' => -45,
                    'maxHeight' => 120,
                ],
                'title' => [
                    'text' => __('widgets.portfolio_names'),
                    'style' => [
                        'fontFamily' => 'inherit',
                        'fontWeight' => 600,
                        'fontSize' => '14px',
                    ],
                ],
            ],
            'yaxis' => [
                'title' => [
                    'text' => __('widgets.amount'),
                    'style' => [
                        'fontFamily' => 'inherit',
                        'fontWeight' => 600,
                        'fontSize' => '14px',
                    ],
                ],
                'labels' => [
                    'style' => [
                        'fontFamily' => 'inherit',
                        'fontSize' => '12px',
                    ],
                ],
            ],
            'colors' => ['#3B82F6', '#10B981'], // Blue for values, Green for allocated
            'dataLabels' => [
                'enabled' => true,
                'style' => [
                    'fontFamily' => 'inherit',
                    'fontWeight' => 600,
                    'fontSize' => '10px',
                    'colors' => ['#ffffff'],
                ],
            ],
            'plotOptions' => [
                'bar' => [
                    'borderRadius' => 4,
                    'columnWidth' => '75%',
                    'dataLabels' => [
                        'position' => 'top',
                    ],
                ],
            ],
            'legend' => [
                'show' => true,
                'position' => 'top',
                'horizontalAlign' => 'center',
                'fontFamily' => 'inherit',
                'fontWeight' => 500,
                'fontSize' => '14px',
                'markers' => [
                    'width' => 8,
                    'height' => 8,
                    'radius' => 2,
                ],
            ],
            'grid' => [
                'show' => true,
                'borderColor' => '#E5E7EB',
                'strokeDashArray' => 4,
                'xaxis' => [
                    'lines' => [
                        'show' => false,
                    ],
                ],
                'yaxis' => [
                    'lines' => [
                        'show' => true,
                    ],
                ],
            ],
            'tooltip' => [
                'enabled' => true,
                'style' => [
                    'fontFamily' => 'inherit',
                ],
                'shared' => true,
                'intersect' => false,
            ],
        ];
    }

    protected function extraJsOptions(): ?RawJs
    {
        return RawJs::make(<<<'JS'
        {
            dataLabels: {
                formatter: function (val) {
                    if (val <= 0) return '';
                    return new Intl.NumberFormat('ar', {
                        minimumFractionDigits: 0,
                        maximumFractionDigits: 0,
                        notation: 'compact',
                        compactDisplay: 'short'
                    }).format(val);
                }
            },
            yaxis: {
                labels: {
                    formatter: function (val) {
                        return new Intl.NumberFormat('ar', {
                            minimumFractionDigits: 0,
                            maximumFractionDigits: 0,
                            notation: 'compact',
                            compactDisplay: 'short'
                        }).format(val);
                    }
                }
            },
            tooltip: {
                y: {
                    formatter: function (val) {
                        return new Intl.NumberFormat('ar', {
                            style: 'decimal',
                            minimumFractionDigits: 0,
                            maximumFractionDigits: 0
                        }).format(val);
                    }
                }
            }
        }
        JS);
    }
}
