<?php

namespace App\Filament\Widgets;

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

class InitiativeOperationGoalsChart extends ApexChartWidget
{
    use HasWidgetShield;
    use InteractsWithPageFilters;

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

    protected static bool $isLazy = false;

    protected static ?string $pollingInterval = null;

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

    protected static ?int $sort = 5;

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

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

    /**
     * Chart options (series, labels, types, size, animations...)
     * https://apexcharts.com/docs/options
     */
    protected function getOptions(): array
    {
        // Get filter values
        $selectedDepartmentId = $this->filters['department_id'] ?? null;
        $selectedWalletId = $this->filters['performance_wallet_id'] ?? null;
        $selectedInitiativeId = $this->filters['initiative_id'] ?? null;

        // Build query with filters
        $query = Initiative::with(['operationGoals' => function ($query) {
            $query->whereNotNull('target');
        }])
            ->whereHas('operationGoals', function ($query) {
                $query->whereNotNull('target');
            });

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

        // Get all initiatives with their operation goals
        $initiatives = $query->get();

        $categories = [];
        $targetData = [];
        $actualData = [];

        foreach ($initiatives as $initiative) {
            foreach ($initiative->operationGoals as $goal) {
                if ($goal->target) {
                    // Create label with initiative name and goal name (truncated for readability)
                    $initiativeName = $this->sanitizeText($initiative->name);
                    $goalName = $this->sanitizeText($goal->name);

                    $label = $this->truncateText($initiativeName, 20).' - '.$this->truncateText($goalName, 25);
                    $categories[] = $label;

                    // Extract numeric values from target and actual strings
                    $targetValue = $this->extractNumericValue($this->sanitizeText($goal->target));
                    $actualValue = $goal->actual ? $this->extractNumericValue($this->sanitizeText($goal->actual)) : 0;

                    $targetData[] = $targetValue;
                    $actualData[] = $actualValue;
                }
            }
        }

        // Handle empty data case
        if (empty($categories)) {
            return [
                'chart' => [
                    'type' => 'bar',
                    'height' => 350,
                    'fontFamily' => 'inherit',
                ],
                'series' => [
                    [
                        'name' => __('widgets.no_data_available'),
                        'data' => [0],
                    ],
                ],
                'xaxis' => [
                    'categories' => [__('widgets.no_operation_goals')],
                    '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' => 350,
                'fontFamily' => 'inherit',
                'toolbar' => [
                    'show' => true,
                    'tools' => [
                        'download' => true,
                        'selection' => false,
                        'zoom' => false,
                        'zoomin' => false,
                        'zoomout' => false,
                        'pan' => false,
                        'reset' => false,
                    ],
                ],
                'animations' => [
                    'enabled' => true,
                    'easing' => 'easeinout',
                    'speed' => 800,
                    'animateGradually' => [
                        'enabled' => true,
                        'delay' => 150,
                    ],
                ],
            ],
            'series' => [
                [
                    'name' => __('widgets.target_values'),
                    'data' => $targetData,
                ],
                [
                    'name' => __('widgets.actual_values'),
                    'data' => $actualData,
                ],
            ],
            'xaxis' => [
                'categories' => $categories,
                'labels' => [
                    'style' => [
                        'fontFamily' => 'inherit',
                        'fontSize' => '12px',
                        'fontWeight' => 500,
                    ],
                    'rotate' => -45,
                    'rotateAlways' => false,
                    'maxHeight' => 120,
                ],
                'axisBorder' => [
                    'show' => true,
                    'color' => '#E4E7EB',
                ],
                'axisTicks' => [
                    'show' => true,
                    'color' => '#E4E7EB',
                ],
            ],
            'yaxis' => [
                'title' => [
                    'text' => __('widgets.values'),
                    'style' => [
                        'fontFamily' => 'inherit',
                        'fontSize' => '14px',
                        'fontWeight' => 600,
                    ],
                ],
                'labels' => [
                    'style' => [
                        'fontFamily' => 'inherit',
                        'fontSize' => '12px',
                        'fontWeight' => 500,
                    ],
                    'formatter' => null, // Will be handled by JavaScript
                ],
            ],
            'colors' => ['#3B82F6', '#10B981'], // Blue for targets, Green for actuals
            'plotOptions' => [
                'bar' => [
                    'horizontal' => false,
                    'columnWidth' => '55%',
                    'endingShape' => 'rounded',
                    'borderRadius' => 2,
                    'dataLabels' => [
                        'position' => 'top',
                    ],
                ],
            ],
            'dataLabels' => [
                'enabled' => true,
                'offsetY' => -20,
                'style' => [
                    'fontSize' => '11px',
                    'fontFamily' => 'inherit',
                    'fontWeight' => 600,
                    'colors' => ['#304758'],
                ],
                'formatter' => null, // Will be handled by JavaScript
            ],
            'legend' => [
                'show' => true,
                'position' => 'top',
                'horizontalAlign' => 'left',
                'offsetX' => 40,
                'fontFamily' => 'inherit',
                'fontSize' => '14px',
                'fontWeight' => 500,
                'markers' => [
                    'width' => 8,
                    'height' => 8,
                    'radius' => 2,
                ],
            ],
            'grid' => [
                'show' => true,
                'borderColor' => '#F1F5F9',
                'strokeDashArray' => 3,
                'xaxis' => [
                    'lines' => [
                        'show' => false,
                    ],
                ],
                'yaxis' => [
                    'lines' => [
                        'show' => true,
                    ],
                ],
                'padding' => [
                    'top' => 10,
                    'right' => 30,
                    'bottom' => 10,
                    'left' => 20,
                ],
            ],
            'tooltip' => [
                'enabled' => true,
                'shared' => true,
                'intersect' => false,
                'style' => [
                    'fontFamily' => 'inherit',
                    'fontSize' => '12px',
                ],
                'y' => [
                    'formatter' => null, // Will be handled by JavaScript
                ],
            ],
            'responsive' => [
                [
                    'breakpoint' => 768,
                    'options' => [
                        'chart' => [
                            'height' => 300,
                        ],
                        'plotOptions' => [
                            'bar' => [
                                'columnWidth' => '70%',
                            ],
                        ],
                    ],
                ],
            ],
        ];
    }

    /**
     * Add custom JavaScript for enhanced formatting and interactions
     */
    protected function extraJsOptions(): ?RawJs
    {
        return RawJs::make(<<<'JS'
        {
            dataLabels: {
                formatter: function (val, opts) {
                    if (val === 0) return '';
                    return new Intl.NumberFormat('ar', {
                        minimumFractionDigits: 0,
                        maximumFractionDigits: 1,
                        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, opts) {
                        return new Intl.NumberFormat('ar', {
                            minimumFractionDigits: 0,
                            maximumFractionDigits: 2
                        }).format(val);
                    }
                }
            }
        }
        JS);
    }

    /**
     * Extract numeric value from text string
     * This handles cases like "95%", "$1000", "85 units", etc.
     */
    private function extractNumericValue(?string $text): float
    {
        if (! $text) {
            return 0;
        }

        // Remove common non-numeric characters and extract the first number found
        $cleaned = preg_replace('/[^\d.,]/', '', $text);

        if (empty($cleaned)) {
            return 0;
        }

        // Handle decimal numbers
        $cleaned = str_replace(',', '.', $cleaned);

        // Extract the first valid number
        preg_match('/\d+\.?\d*/', $cleaned, $matches);

        return $matches ? (float) $matches[0] : 0;
    }

    /**
     * Sanitize text to ensure proper UTF-8 encoding and remove problematic characters
     */
    private function sanitizeText(?string $text): string
    {
        if (! $text) {
            return '';
        }

        // Ensure proper UTF-8 encoding
        $text = mb_convert_encoding($text, 'UTF-8', 'UTF-8');

        // Remove any null bytes and control characters that might cause issues
        $text = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/', '', $text);

        // Remove any remaining invalid UTF-8 sequences
        $text = mb_scrub($text, 'UTF-8');

        return trim($text);
    }

    /**
     * Truncate text to specified length with ellipsis
     */
    private function truncateText(string $text, int $length): string
    {
        // Ensure we're working with clean UTF-8 text
        $text = $this->sanitizeText($text);

        return mb_strlen($text) > $length ? mb_substr($text, 0, $length).'...' : $text;
    }
}
