<?php

namespace App\Support;

use App\Models\OrganizationSetting;
use App\Models\Theme;
use App\Models\User;

class ThemeManager
{
    /**
     * @return array<string, array{
     *     name:string,
     *     description:string,
     *     palette: array<string, string>,
     *     fonts: array<string, string>,
     *     icons: array<string, string>
     * }>
     */
    public static function userPresets(): array
    {
        $defaults = self::defaults();

        return [
            'oceanic' => [
                'name' => 'Oceanic',
                'description' => 'Calm blue accents with clean light surfaces.',
                'palette' => array_replace($defaults['palette'], [
                    'primary' => '#0F766E',
                    'primary_hover' => '#0D9488',
                    'accent' => '#0284C7',
                    'background' => '#ECFEFF',
                    'surface' => '#FFFFFF',
                    'surface_alt' => '#F0FDFF',
                    'text' => '#0F172A',
                    'text_muted' => '#475569',
                    'border' => '#CFFAFE',
                    'sidebar_bg' => '#0B3A53',
                    'sidebar_surface' => '#0F4F6E',
                    'sidebar_border' => '#1C6A8E',
                    'sidebar_text' => '#E0F2FE',
                    'sidebar_muted' => '#BAE6FD',
                    'sidebar_active' => '#0369A1',
                    'right_rail_bg' => '#FFFFFF',
                    'card_bg' => '#FFFFFF',
                    'input_bg' => '#FFFFFF',
                ]),
                'fonts' => $defaults['fonts'],
                'icons' => array_replace($defaults['icons'], [
                    'color' => '#0E7490',
                    'muted' => '#64748B',
                ]),
            ],
            'sunrise' => [
                'name' => 'Sunrise',
                'description' => 'Warm daylight palette for high readability.',
                'palette' => array_replace($defaults['palette'], [
                    'primary' => '#D97706',
                    'primary_hover' => '#F59E0B',
                    'accent' => '#EA580C',
                    'background' => '#FFFBEB',
                    'surface' => '#FFFFFF',
                    'surface_alt' => '#FEFCE8',
                    'text' => '#1F2937',
                    'text_muted' => '#6B7280',
                    'border' => '#FDE68A',
                    'sidebar_bg' => '#422006',
                    'sidebar_surface' => '#5B2E0A',
                    'sidebar_border' => '#7C3A10',
                    'sidebar_text' => '#FEF3C7',
                    'sidebar_muted' => '#FCD34D',
                    'sidebar_active' => '#B45309',
                    'right_rail_bg' => '#FFFDF5',
                    'card_bg' => '#FFFFFF',
                    'input_bg' => '#FFFFFF',
                ]),
                'fonts' => $defaults['fonts'],
                'icons' => array_replace($defaults['icons'], [
                    'color' => '#9A3412',
                    'muted' => '#78716C',
                ]),
            ],
            'forest' => [
                'name' => 'Forest',
                'description' => 'Natural green tones with soft contrast.',
                'palette' => array_replace($defaults['palette'], [
                    'primary' => '#166534',
                    'primary_hover' => '#15803D',
                    'accent' => '#0D9488',
                    'background' => '#F0FDF4',
                    'surface' => '#FFFFFF',
                    'surface_alt' => '#ECFDF5',
                    'text' => '#052E16',
                    'text_muted' => '#3F6212',
                    'border' => '#BBF7D0',
                    'sidebar_bg' => '#052E16',
                    'sidebar_surface' => '#14532D',
                    'sidebar_border' => '#166534',
                    'sidebar_text' => '#DCFCE7',
                    'sidebar_muted' => '#86EFAC',
                    'sidebar_active' => '#15803D',
                    'right_rail_bg' => '#FFFFFF',
                    'card_bg' => '#FFFFFF',
                    'input_bg' => '#FFFFFF',
                ]),
                'fonts' => $defaults['fonts'],
                'icons' => array_replace($defaults['icons'], [
                    'color' => '#166534',
                    'muted' => '#4D7C0F',
                ]),
            ],
        ];
    }

    /**
     * @return array{
     *     theme: ?Theme,
     *     palette: array<string, string>,
     *     fonts: array<string, string>,
     *     icons: array<string, string>,
     *     css_vars: string,
     *     font_url: string,
     *     custom_css: string
     * }
     */
    public function themeForUser(?User $user): array
    {
        $theme = null;
        if ($user) {
            $setting = OrganizationSetting::current();
            $themeId = (int) ($setting->theme_id ?? 0);
            if ($themeId > 0) {
                $theme = Theme::query()->find($themeId);
            }
        }

        $resolved = $this->resolveTheme($theme);

        $appearance = $user && is_array($user->appearance_settings)
            ? $user->appearance_settings
            : [];

        if (is_array($appearance)) {
            $resolved['palette'] = array_replace($resolved['palette'], $appearance['palette'] ?? []);
            $resolved['fonts'] = array_replace($resolved['fonts'], $appearance['fonts'] ?? []);
            $resolved['icons'] = array_replace($resolved['icons'], $appearance['icons'] ?? []);
            $resolved['css_vars'] = $this->buildCssVars(
                $resolved['palette'],
                $resolved['fonts'],
                $resolved['icons']
            );
            $resolved['font_url'] = (string) ($resolved['fonts']['url'] ?? '');
        }

        $resolved['background_url'] = $user?->background_image_path
            ? \Illuminate\Support\Facades\Storage::disk('public')->url($user->background_image_path)
            : '';
        $resolved['theme'] = $theme;

        return $resolved;
    }

    /**
     * @return array{palette: array<string, string>, fonts: array<string, string>, icons: array<string, string>, css_vars: string, font_url: string, custom_css: string}
     */
    public function resolveTheme(?Theme $theme): array
    {
        $defaults = self::defaults();

        $palette = array_replace($defaults['palette'], is_array($theme?->palette) ? $theme->palette : []);
        $fonts = array_replace($defaults['fonts'], is_array($theme?->fonts) ? $theme->fonts : []);
        $icons = array_replace($defaults['icons'], is_array($theme?->icons) ? $theme->icons : []);
        $customCss = trim((string) ($theme?->custom_css ?? ''));

        $cssVars = $this->buildCssVars($palette, $fonts, $icons);

        return [
            'palette' => $palette,
            'fonts' => $fonts,
            'icons' => $icons,
            'css_vars' => $cssVars,
            'font_url' => (string) ($fonts['url'] ?? ''),
            'custom_css' => $customCss,
        ];
    }

    /**
     * @return array{palette: array<string, string>, fonts: array<string, string>, icons: array<string, string>}
     */
    public static function defaults(): array
    {
        return [
            'palette' => [
                'primary' => '#4F46E5',
                'primary_hover' => '#6366F1',
                'accent' => '#0EA5E9',
                'background' => '#F3F4F6',
                'surface' => '#FFFFFF',
                'surface_alt' => '#F8FAFC',
                'text' => '#0F172A',
                'text_muted' => '#64748B',
                'border' => '#E2E8F0',
                'sidebar_bg' => '#0F172A',
                'sidebar_surface' => '#1E293B',
                'sidebar_border' => '#334155',
                'sidebar_text' => '#E2E8F0',
                'sidebar_muted' => '#94A3B8',
                'sidebar_active' => '#1E40AF',
                'right_rail_bg' => '#FFFFFF',
                'card_bg' => '#FFFFFF',
                'input_bg' => '#FFFFFF',
            ],
            'fonts' => [
                'body' => 'Figtree, ui-sans-serif, system-ui',
                'heading' => 'Figtree, ui-sans-serif, system-ui',
                'url' => '',
            ],
            'icons' => [
                'color' => '#475569',
                'muted' => '#94A3B8',
            ],
        ];
    }

    /**
     * @param  array<string, string>  $palette
     * @param  array<string, string>  $fonts
     * @param  array<string, string>  $icons
     */
    private function buildCssVars(array $palette, array $fonts, array $icons): string
    {
        $vars = [
            '--theme-primary' => $palette['primary'] ?? '#4F46E5',
            '--theme-primary-hover' => $palette['primary_hover'] ?? '#6366F1',
            '--theme-accent' => $palette['accent'] ?? '#0EA5E9',
            '--theme-bg' => $palette['background'] ?? '#F3F4F6',
            '--theme-surface' => $palette['surface'] ?? '#FFFFFF',
            '--theme-surface-alt' => $palette['surface_alt'] ?? '#F8FAFC',
            '--theme-text' => $palette['text'] ?? '#0F172A',
            '--theme-text-muted' => $palette['text_muted'] ?? '#64748B',
            '--theme-border' => $palette['border'] ?? '#E2E8F0',
            '--theme-sidebar-bg' => $palette['sidebar_bg'] ?? '#0F172A',
            '--theme-sidebar-surface' => $palette['sidebar_surface'] ?? '#1E293B',
            '--theme-sidebar-border' => $palette['sidebar_border'] ?? '#334155',
            '--theme-sidebar-text' => $palette['sidebar_text'] ?? '#E2E8F0',
            '--theme-sidebar-muted' => $palette['sidebar_muted'] ?? '#94A3B8',
            '--theme-sidebar-active' => $palette['sidebar_active'] ?? '#1E40AF',
            '--theme-right-rail-bg' => $palette['right_rail_bg'] ?? '#FFFFFF',
            '--theme-card-bg' => $palette['card_bg'] ?? '#FFFFFF',
            '--theme-input-bg' => $palette['input_bg'] ?? '#FFFFFF',
            '--theme-font-body' => $fonts['body'] ?? 'Figtree, ui-sans-serif, system-ui',
            '--theme-font-heading' => $fonts['heading'] ?? $fonts['body'] ?? 'Figtree, ui-sans-serif, system-ui',
            '--theme-icon-color' => $icons['color'] ?? '#475569',
            '--theme-icon-muted' => $icons['muted'] ?? '#94A3B8',
        ];

        return collect($vars)
            ->map(fn ($value, $key) => $key.': '.$value)
            ->implode('; ');
    }
}
