<?php

namespace App\Http\Controllers\Admin\Settings;

use App\Http\Controllers\Controller;
use App\Traits\RefreshesSettingsCache;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Inertia\Inertia;

class ThemeSettingsController extends Controller
{
    use RefreshesSettingsCache;

    /**
     * Default sidebar theme presets (AdminLTE inspired colors)
     */
    public const THEME_PRESETS = [
        'default' => [
            'name' => 'Default Light',
            'description' => 'Clean white sidebar - follows system light/dark mode',
            'respectsSystemTheme' => true,
            'colors' => [
                'background' => '#ffffff',
                'foreground' => '#1f2937',
                'primary' => '#3b82f6',
                'accent' => '#e5e7eb',
                'border' => '#d1d5db',
            ],
        ],
        'dark' => [
            'name' => 'Dark Modern',
            'description' => 'Modern dark sidebar - follows system light/dark mode',
            'respectsSystemTheme' => true,
            'colors' => [
                'background' => '#1f2937',
                'foreground' => '#f9fafb',
                'primary' => '#60a5fa',
                'accent' => '#4b5563',
                'border' => '#4b5563',
            ],
        ],
        'adminlte_blue' => [
            'name' => 'AdminLTE Blue',
            'description' => 'Classic AdminLTE blue theme',
            'colors' => [
                'background' => '#343a40',
                'foreground' => '#c2c7d0',
                'primary' => '#007bff',
                'accent' => '#494e53',
                'border' => '#4b545c',
            ],
        ],
        'adminlte_dark' => [
            'name' => 'AdminLTE Dark',
            'description' => 'Dark AdminLTE theme',
            'colors' => [
                'background' => '#212529',
                'foreground' => '#dee2e6',
                'primary' => '#17a2b8',
                'accent' => '#2c3035',
                'border' => '#373b3e',
            ],
        ],
        'midnight' => [
            'name' => 'Midnight Blue',
            'description' => 'Deep blue professional',
            'colors' => [
                'background' => '#0f172a',
                'foreground' => '#e2e8f0',
                'primary' => '#3b82f6',
                'accent' => '#1e293b',
                'border' => '#334155',
            ],
        ],
        'purple_dream' => [
            'name' => 'Purple Dream',
            'description' => 'Elegant purple theme',
            'colors' => [
                'background' => '#2e1065',
                'foreground' => '#faf5ff',
                'primary' => '#a855f7',
                'accent' => '#4c1d95',
                'border' => '#5b21b6',
            ],
        ],
        'forest' => [
            'name' => 'Forest Green',
            'description' => 'Natural green theme',
            'colors' => [
                'background' => '#064e3b',
                'foreground' => '#ecfdf5',
                'primary' => '#10b981',
                'accent' => '#065f46',
                'border' => '#047857',
            ],
        ],
        'sunset' => [
            'name' => 'Sunset Orange',
            'description' => 'Warm orange theme',
            'colors' => [
                'background' => '#7c2d12',
                'foreground' => '#fff7ed',
                'primary' => '#f97316',
                'accent' => '#9a3412',
                'border' => '#c2410c',
            ],
        ],
        'ocean' => [
            'name' => 'Ocean Teal',
            'description' => 'Calm teal theme',
            'colors' => [
                'background' => '#134e4a',
                'foreground' => '#f0fdfa',
                'primary' => '#14b8a6',
                'accent' => '#115e59',
                'border' => '#0f766e',
            ],
        ],
        'rose' => [
            'name' => 'Rose Pink',
            'description' => 'Elegant rose theme',
            'colors' => [
                'background' => '#881337',
                'foreground' => '#fff1f2',
                'primary' => '#f43f5e',
                'accent' => '#9f1239',
                'border' => '#be123c',
            ],
        ],
        'slate' => [
            'name' => 'Slate Gray',
            'description' => 'Professional slate gray',
            'colors' => [
                'background' => '#334155',
                'foreground' => '#f8fafc',
                'primary' => '#64748b',
                'accent' => '#475569',
                'border' => '#52647b',
            ],
        ],
        'indigo' => [
            'name' => 'Indigo Night',
            'description' => 'Deep indigo theme',
            'colors' => [
                'background' => '#312e81',
                'foreground' => '#eef2ff',
                'primary' => '#6366f1',
                'accent' => '#4338ca',
                'border' => '#4f46e5',
            ],
        ],
    ];

    /**
     * Display the theme settings page.
     */
    public function index()
    {
        // Get current theme settings
        $currentTheme = DB::table('settings')->where('key', 'admin_sidebar_theme')->value('value') ?? 'default';
        $customColors = json_decode(DB::table('settings')->where('key', 'admin_sidebar_custom_colors')->value('value') ?? '{}', true);

        // Ensure we have valid colors
        $defaultColors = self::THEME_PRESETS['default']['colors'];
        $customColors = array_merge($defaultColors, $customColors ?: []);

        // Determine if current theme respects system theme
        $respectsSystemTheme = self::THEME_PRESETS[$currentTheme]['respectsSystemTheme'] ?? false;

        return Inertia::render('admin/settings/theme/index', [
            'currentTheme' => $currentTheme,
            'customColors' => $customColors,
            'presets' => self::THEME_PRESETS,
            'respectsSystemTheme' => $respectsSystemTheme,
        ]);
    }

    /**
     * Update theme settings.
     */
    public function update(Request $request)
    {
        $request->validate([
            'theme' => 'required|string|in:'.implode(',', array_keys(self::THEME_PRESETS)).',custom',
            'colors' => 'nullable|array',
            'colors.background' => 'nullable|string|regex:/^#[a-fA-F0-9]{6}$/',
            'colors.foreground' => 'nullable|string|regex:/^#[a-fA-F0-9]{6}$/',
            'colors.primary' => 'nullable|string|regex:/^#[a-fA-F0-9]{6}$/',
            'colors.accent' => 'nullable|string|regex:/^#[a-fA-F0-9]{6}$/',
            'colors.border' => 'nullable|string|regex:/^#[a-fA-F0-9]{6}$/',
        ]);

        $theme = $request->input('theme');

        // Save theme selection
        DB::table('settings')->updateOrInsert(
            ['key' => 'admin_sidebar_theme'],
            ['value' => $theme, 'updated_at' => now()]
        );

        // If custom theme, save custom colors
        if ($theme === 'custom' && $request->has('colors')) {
            DB::table('settings')->updateOrInsert(
                ['key' => 'admin_sidebar_custom_colors'],
                ['value' => json_encode($request->input('colors')), 'updated_at' => now()]
            );
        }

        $this->refreshSettingsCache();

        return back()->with('success', 'Theme settings updated successfully.');
    }

    /**
     * Get current theme data (for API use)
     */
    public function getTheme()
    {
        $themeKey = DB::table('settings')->where('key', 'admin_sidebar_theme')->value('value') ?? 'default';
        $customColors = json_decode(DB::table('settings')->where('key', 'admin_sidebar_custom_colors')->value('value') ?? '{}', true);

        $themeData = self::THEME_PRESETS[$themeKey] ?? self::THEME_PRESETS['default'];

        if ($themeKey === 'custom' && ! empty($customColors)) {
            $themeData['colors'] = array_merge($themeData['colors'], $customColors);
        }

        return response()->json([
            'theme' => $themeKey,
            'colors' => $themeData['colors'],
            'respectsSystemTheme' => $themeData['respectsSystemTheme'] ?? false,
        ]);
    }
}
