<?php

namespace App\Helpers;

use App\Models\UserSetting;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;

class ThemeHelper
{
    /**
     * Colori di default del tema NetGesCon
     */
    const DEFAULT_THEME = [
        'primary_color' => '#f39c12',        // Giallo NetGesCon
        'secondary_color' => '#3498db',      // Blu
        'success_color' => '#27ae60',        // Verde
        'danger_color' => '#e74c3c',         // Rosso
        'warning_color' => '#f39c12',        // Arancione/Giallo
        'info_color' => '#17a2b8',           // Azzurro
        'light_color' => '#f8f9fa',          // Grigio chiaro
        'dark_color' => '#343a40',           // Grigio scuro
        'sidebar_bg' => '#f39c12',           // Sfondo sidebar (giallo)
        'sidebar_text' => '#ffffff',         // Testo sidebar (bianco)
        'header_bg' => '#2c5aa0',            // Sfondo header (blu)
        'header_text' => '#ffffff',          // Testo header (bianco)
        'theme_mode' => 'light'              // Modalità tema (light/dark)
    ];

    /**
     * Temi predefiniti disponibili
     */
    const PRESET_THEMES = [
        'netgescon_classic' => [
            'name' => 'NetGesCon Classico',
            'description' => 'Schema colori tradizionale NetGesCon',
            'colors' => self::DEFAULT_THEME
        ],
        'netgescon_blue' => [
            'name' => 'NetGesCon Blu',
            'description' => 'Variante blu professionale',
            'colors' => [
                'primary_color' => '#2c5aa0',
                'secondary_color' => '#f39c12',
                'success_color' => '#27ae60',
                'danger_color' => '#e74c3c',
                'warning_color' => '#f39c12',
                'info_color' => '#17a2b8',
                'light_color' => '#f8f9fa',
                'dark_color' => '#343a40',
                'sidebar_bg' => '#2c5aa0',
                'sidebar_text' => '#ffffff',
                'header_bg' => '#f39c12',
                'header_text' => '#ffffff',
                'theme_mode' => 'light'
            ]
        ],
        'netgescon_green' => [
            'name' => 'NetGesCon Verde',
            'description' => 'Variante verde natura',
            'colors' => [
                'primary_color' => '#27ae60',
                'secondary_color' => '#2c5aa0',
                'success_color' => '#2ecc71',
                'danger_color' => '#e74c3c',
                'warning_color' => '#f39c12',
                'info_color' => '#17a2b8',
                'light_color' => '#f8f9fa',
                'dark_color' => '#343a40',
                'sidebar_bg' => '#27ae60',
                'sidebar_text' => '#ffffff',
                'header_bg' => '#2c5aa0',
                'header_text' => '#ffffff',
                'theme_mode' => 'light'
            ]
        ],
        'netgescon_dark' => [
            'name' => 'NetGesCon Dark',
            'description' => 'Tema scuro per la sera',
            'colors' => [
                'primary_color' => '#f39c12',
                'secondary_color' => '#6c757d',
                'success_color' => '#28a745',
                'danger_color' => '#dc3545',
                'warning_color' => '#ffc107',
                'info_color' => '#17a2b8',
                'light_color' => '#343a40',
                'dark_color' => '#212529',
                'sidebar_bg' => '#212529',
                'sidebar_text' => '#f39c12',
                'header_bg' => '#343a40',
                'header_text' => '#f39c12',
                'theme_mode' => 'dark'
            ]
        ]
    ];

    /**
     * Ottiene i colori del tema per l'utente corrente
     */
    public static function getUserTheme($userId = null): array
    {
        $userId = $userId ?? Auth::id();
        
        if (!$userId) {
            return self::DEFAULT_THEME;
        }

        $settings = UserSetting::where('user_id', $userId)
            ->whereIn('key', array_keys(self::DEFAULT_THEME))
            ->pluck('value', 'key')
            ->toArray();

        // Merge con i valori di default
        return array_merge(self::DEFAULT_THEME, $settings);
    }

    /**
     * Salva le impostazioni del tema per un utente
     */
    public static function saveUserTheme($userId, array $themeData): bool
    {
        try {
            foreach ($themeData as $key => $value) {
                if (array_key_exists($key, self::DEFAULT_THEME)) {
                    UserSetting::updateOrCreate(
                        ['user_id' => $userId, 'key' => $key],
                        ['value' => $value]
                    );
                }
            }
            return true;
        } catch (\Exception $e) {
            Log::error('Errore salvataggio tema utente: ' . $e->getMessage());
            return false;
        }
    }

    /**
     * Applica un tema predefinito a un utente
     */
    public static function applyPresetTheme($userId, string $presetName): bool
    {
        if (!isset(self::PRESET_THEMES[$presetName])) {
            return false;
        }

        return self::saveUserTheme($userId, self::PRESET_THEMES[$presetName]['colors']);
    }

    /**
     * Genera CSS personalizzato per il tema utente
     */
    public static function generateCustomCSS($userId = null): string
    {
        $theme = self::getUserTheme($userId);
        
        return "
        :root {
            --netgescon-primary: {$theme['primary_color']};
            --netgescon-secondary: {$theme['secondary_color']};
            --netgescon-success: {$theme['success_color']};
            --netgescon-danger: {$theme['danger_color']};
            --netgescon-warning: {$theme['warning_color']};
            --netgescon-info: {$theme['info_color']};
            --netgescon-light: {$theme['light_color']};
            --netgescon-dark: {$theme['dark_color']};
            --netgescon-sidebar-bg: {$theme['sidebar_bg']};
            --netgescon-sidebar-text: {$theme['sidebar_text']};
            --netgescon-header-bg: {$theme['header_bg']};
            --netgescon-header-text: {$theme['header_text']};
        }

        /* Sidebar personalizzata */
        .netgescon-sidebar {
            background-color: var(--netgescon-sidebar-bg) !important;
            color: var(--netgescon-sidebar-text) !important;
        }

        .netgescon-sidebar .nav-link {
            color: var(--netgescon-sidebar-text) !important;
        }

        .netgescon-sidebar .nav-link:hover {
            background-color: rgba(255, 255, 255, 0.1) !important;
        }

        .netgescon-sidebar .nav-link.active {
            background-color: rgba(255, 255, 255, 0.2) !important;
        }

        /* Header personalizzato */
        .netgescon-header {
            background-color: var(--netgescon-header-bg) !important;
            color: var(--netgescon-header-text) !important;
        }

        /* Pulsanti principali */
        .btn-primary {
            background-color: var(--netgescon-primary) !important;
            border-color: var(--netgescon-primary) !important;
        }

        .btn-secondary {
            background-color: var(--netgescon-secondary) !important;
            border-color: var(--netgescon-secondary) !important;
        }

        /* Badge e alert */
        .badge-primary {
            background-color: var(--netgescon-primary) !important;
        }

        .alert-primary {
            background-color: var(--netgescon-primary) !important;
            border-color: var(--netgescon-primary) !important;
        }

        /* Tema scuro */
        " . ($theme['theme_mode'] === 'dark' ? "
        body {
            background-color: var(--netgescon-dark) !important;
            color: var(--netgescon-light) !important;
        }

        .card {
            background-color: var(--netgescon-light) !important;
            border-color: #6c757d !important;
        }

        .table-dark {
            --bs-table-bg: var(--netgescon-dark);
        }
        " : "") . "
        ";
    }

    /**
     * Ottiene tutti i temi predefiniti
     */
    public static function getPresetThemes(): array
    {
        return self::PRESET_THEMES;
    }

    /**
     * Valida un colore esadecimale
     */
    public static function isValidHexColor(string $color): bool
    {
        return preg_match('/^#([a-f0-9]{3}){1,2}$/i', $color);
    }

    /**
     * Converte un colore esadecimale in RGB
     */
    public static function hexToRgb(string $hex): array
    {
        $hex = str_replace('#', '', $hex);
        
        if (strlen($hex) == 3) {
            $hex = $hex[0] . $hex[0] . $hex[1] . $hex[1] . $hex[2] . $hex[2];
        }
        
        return [
            'r' => hexdec(substr($hex, 0, 2)),
            'g' => hexdec(substr($hex, 2, 2)),
            'b' => hexdec(substr($hex, 4, 2))
        ];
    }
}
