<?php

namespace App\Services;

use App\Models\UiThemeSetting;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Schema;

class UiThemeService
{
    public const CACHE_PREFIX = 'ui_theme_settings_school_';

    public function colorKeys(): array
    {
        return [
            'primary_color' => 'Primary accent color',
            'primary_hover_color' => 'Hover accent color',
            'secondary_color' => 'Secondary accent color',
            'success_color' => 'Success color',
            'warning_color' => 'Warning color',
            'danger_color' => 'Danger color',
            'info_color' => 'Info color',
            'text_color' => 'Text color',
            'muted_text_color' => 'Muted text color',
            'card_background_color' => 'Card background color',
            'border_color' => 'Border color',
        ];
    }

    public function backgroundKeys(): array
    {
        return [
            'light_background_color' => 'Light mode background color',
            'dark_background_color' => 'Dark mode background color',
            'dark_card_background_color' => 'Dark card background color',
            'dark_text_color' => 'Dark text color',
            'dark_muted_text_color' => 'Dark muted text color',
            'dark_border_color' => 'Dark border color',
            'sidebar_background_color' => 'Sidebar background color',
            'sidebar_text_color' => 'Sidebar text color',
            'topbar_background_color' => 'Topbar background color',
            'dark_topbar_background_color' => 'Dark topbar background color',
            'login_background_color' => 'Login page background color',
            'background_image' => 'Background image',
            'enable_background_gradient' => 'Background gradient',
            'enable_glass_effect' => 'Glass effect',
        ];
    }

    public function defaults(): array
    {
        return [
            'primary_color' => '#8DD7FF',
            'primary_hover_color' => '#1BC1E5',
            'secondary_color' => '#6CC2D7',
            'success_color' => '#22C55E',
            'warning_color' => '#F59E0B',
            'danger_color' => '#EF4444',
            'info_color' => '#38BDF8',
            'text_color' => '#111827',
            'muted_text_color' => '#667085',
            'card_background_color' => '#FFFFFF',
            'border_color' => '#E7EAF0',
            'light_background_color' => '#F3F7FB',
            'dark_background_color' => '#08131F',
            'dark_card_background_color' => '#0B1522',
            'dark_text_color' => '#F6F7FB',
            'dark_muted_text_color' => '#97A7B8',
            'dark_border_color' => '#243448',
            'sidebar_background_color' => '#06101B',
            'sidebar_text_color' => '#B5C5D6',
            'topbar_background_color' => '#FFFFFF',
            'dark_topbar_background_color' => '#0B1522',
            'login_background_color' => '#08131F',
            'background_image' => '',
            'enable_background_gradient' => '1',
            'enable_glass_effect' => '1',
        ];
    }

    public function values(?int $schoolId = null): array
    {
        $schoolId = $schoolId ?: $this->schoolId();

        return Cache::remember(self::CACHE_PREFIX . $schoolId, now()->addHour(), function () use ($schoolId) {
            $defaults = $this->defaults();

            if (!Schema::hasTable('ui_theme_settings')) {
                return $defaults;
            }

            $saved = UiThemeSetting::query()
                ->where('school_id', $schoolId)
                ->pluck('value', 'key')
                ->toArray();

            return array_merge($defaults, array_filter($saved, static function ($value) {
                return $value !== null && $value !== '';
            }));
        });
    }

    public function update(array $settings, ?int $updatedBy = null, ?int $schoolId = null): void
    {
        if (!Schema::hasTable('ui_theme_settings')) {
            return;
        }

        $schoolId = $schoolId ?: $this->schoolId();
        $validKeys = array_keys($this->defaults());

        foreach ($settings as $key => $value) {
            if (!in_array($key, $validKeys, true)) {
                continue;
            }

            UiThemeSetting::updateOrCreate(
                ['school_id' => $schoolId, 'key' => $key],
                [
                    'value' => $this->normalize($key, $value),
                    'updated_by' => $updatedBy,
                ]
            );
        }

        $this->clearCache($schoolId);
    }

    public function cssVariables(?int $schoolId = null): array
    {
        $settings = $this->values($schoolId);

        return [
            '--app-primary' => $settings['primary_color'],
            '--app-primary-hover' => $settings['primary_hover_color'],
            '--app-secondary' => $settings['secondary_color'],
            '--app-success' => $settings['success_color'],
            '--app-warning' => $settings['warning_color'],
            '--app-danger' => $settings['danger_color'],
            '--app-info' => $settings['info_color'],
            '--app-bg' => $settings['light_background_color'],
            '--app-card' => $settings['card_background_color'],
            '--app-card-soft' => '#F1F5F9',
            '--app-text' => $settings['text_color'],
            '--app-muted' => $settings['muted_text_color'],
            '--app-border' => $settings['border_color'],
            '--app-sidebar-bg' => $settings['sidebar_background_color'],
            '--app-sidebar-text' => $settings['sidebar_text_color'],
            '--app-topbar-bg' => $settings['topbar_background_color'],
            '--app-login-bg' => $settings['login_background_color'],
        ];
    }

    public function clearCache(?int $schoolId = null): void
    {
        Cache::forget(self::CACHE_PREFIX . ($schoolId ?: $this->schoolId()));
    }

    public function schoolId(): int
    {
        if (Auth::check() && Auth::user()->school_id) {
            return (int) Auth::user()->school_id;
        }

        if (app()->bound('school') && optional(app('school'))->id) {
            return (int) app('school')->id;
        }

        return 1;
    }

    private function normalize(string $key, $value): string
    {
        if (in_array($key, ['enable_background_gradient', 'enable_glass_effect'], true)) {
            return $value ? '1' : '0';
        }

        if ($key === 'background_image') {
            return trim((string) $value);
        }

        $value = strtoupper(trim((string) $value));

        if (preg_match('/^#[0-9A-F]{6}$/', $value)) {
            return $value;
        }

        return $this->defaults()[$key] ?? '';
    }
}
