<?php
declare(strict_types=1);

namespace App\Modules\Settings\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Modules\Settings\Models\SystemConfig;

class AppearanceController extends Controller
{
    private const DEFAULTS = [
        'appearance.brand_color'      => '#0D7377',
        'appearance.accent_color'     => '#6366f1',
        'appearance.sidebar_style'    => 'dark',
        'appearance.sidebar_width'    => 'normal',
        'appearance.card_radius'      => 'rounded',
        'appearance.font_size'        => 'normal',
        'appearance.animation'        => 'full',
        'appearance.header_style'     => 'clean',
        'appearance.table_style'      => 'striped',
        'appearance.density'          => 'comfortable',
    ];

    private const COLOR_PRESETS = [
        ['label' => 'تيل كلاسيك',   'value' => '#0D7377'],
        ['label' => 'أزرق ملكي',    'value' => '#2563EB'],
        ['label' => 'بنفسجي أنيق',  'value' => '#7C3AED'],
        ['label' => 'أخضر زمردي',   'value' => '#059669'],
        ['label' => 'وردي عصري',   'value' => '#DB2777'],
        ['label' => 'برتقالي دافئ', 'value' => '#EA580C'],
        ['label' => 'رمادي حديث',   'value' => '#475569'],
        ['label' => 'ذهبي فاخر',   'value' => '#B45309'],
    ];

    public function index(Request $request): Response
    {
        $this->authorize('settings.edit');

        $settings = [];
        foreach (self::DEFAULTS as $key => $default) {
            $row = SystemConfig::get($key);
            $settings[str_replace('appearance.', '', $key)] = $row ? $row['config_value'] : $default;
        }

        return $this->view('Settings.Views.appearance', [
            'settings'     => $settings,
            'colorPresets' => self::COLOR_PRESETS,
        ]);
    }

    public function update(Request $request): Response
    {
        $this->authorize('settings.edit');

        $fields = [
            'brand_color'   => $_POST['brand_color'] ?? '',
            'accent_color'  => $_POST['accent_color'] ?? '',
            'sidebar_style' => $_POST['sidebar_style'] ?? 'dark',
            'sidebar_width' => $_POST['sidebar_width'] ?? 'normal',
            'card_radius'   => $_POST['card_radius'] ?? 'rounded',
            'font_size'     => $_POST['font_size'] ?? 'normal',
            'animation'     => $_POST['animation'] ?? 'full',
            'header_style'  => $_POST['header_style'] ?? 'clean',
            'table_style'   => $_POST['table_style'] ?? 'striped',
            'density'       => $_POST['density'] ?? 'comfortable',
        ];

        foreach ($fields as $name => $value) {
            $key = 'appearance.' . $name;
            if ($name === 'brand_color' || $name === 'accent_color') {
                if (!preg_match('/^#[0-9A-Fa-f]{6}$/', $value)) {
                    $value = self::DEFAULTS[$key];
                }
            }
            SystemConfig::set($key, $value);
        }

        return $this->redirect('/settings/appearance')->withSuccess('تم حفظ إعدادات المظهر بنجاح');
    }

    public static function getThemeVars(): array
    {
        $vars = [];
        foreach (self::DEFAULTS as $key => $default) {
            $row = SystemConfig::get($key);
            $name = str_replace('appearance.', '', $key);
            $vars[$name] = $row ? $row['config_value'] : $default;
        }
        return $vars;
    }

    public static function getCssOverrides(): string
    {
        $v = self::getThemeVars();
        $css = ':root{';

        if ($v['brand_color'] !== '#0D7377') {
            $hex = $v['brand_color'];
            $r = hexdec(substr($hex, 1, 2));
            $g = hexdec(substr($hex, 3, 2));
            $b = hexdec(substr($hex, 5, 2));
            $css .= "--brand-primary:{$hex};";
            $css .= "--brand-primary-rgb:{$r},{$g},{$b};";
            $css .= "--brand-primary-light:{$hex}cc;";
            $css .= "--brand-primary-dark:{$hex};";
            $css .= "--border-focus:{$hex};";
        }

        if ($v['accent_color'] !== '#6366f1') {
            $hex = $v['accent_color'];
            $r = hexdec(substr($hex, 1, 2));
            $g = hexdec(substr($hex, 3, 2));
            $b = hexdec(substr($hex, 5, 2));
            $css .= "--brand-accent:{$hex};";
            $css .= "--brand-accent-rgb:{$r},{$g},{$b};";
        }

        $radiusMap = ['sharp' => '4px', 'rounded' => '10px', 'pill' => '18px'];
        if (isset($radiusMap[$v['card_radius']])) {
            $r = $radiusMap[$v['card_radius']];
            $css .= "--radius-md:{$r};";
        }

        $fontMap = ['compact' => '13px', 'normal' => '14px', 'large' => '15px'];
        if (isset($fontMap[$v['font_size']])) {
            $css .= "--font-size-base:{$fontMap[$v['font_size']]};";
        }

        $widthMap = ['narrow' => '240px', 'normal' => '270px', 'wide' => '300px'];
        if (isset($widthMap[$v['sidebar_width']])) {
            $css .= "--sidebar-width:{$widthMap[$v['sidebar_width']]};";
        }

        $css .= '}';

        if ($v['animation'] === 'none') {
            $css .= '*,*::before,*::after{animation-duration:0s!important;transition-duration:0s!important;}';
        } elseif ($v['animation'] === 'subtle') {
            $css .= ':root{--duration-fast:100ms;--duration-normal:150ms;--duration-slow:200ms;}';
        }

        if ($v['sidebar_style'] === 'light') {
            $css .= ':root{--sidebar-bg:#ffffff;--sidebar-item-hover:rgba(0,0,0,0.04);--sidebar-item-active:rgba(13,115,119,0.08);--sidebar-border:rgba(0,0,0,0.06);}';
            $css .= '.sidebar{border-left:1px solid var(--border-light);}.sidebar .sidebar-brand-name,.sidebar .sidebar-item-label,.sidebar .sidebar-section-title{color:#1A1A2E!important;}.sidebar .sidebar-item i{color:#64748B!important;}.sidebar .sidebar-item.active i{color:var(--brand-primary)!important;}';
        } elseif ($v['sidebar_style'] === 'gradient') {
            $css .= ':root{--sidebar-bg:linear-gradient(180deg,#0f0f1a 0%,#1a1a3e 100%);}';
            $css .= '.sidebar{background:var(--sidebar-bg);}';
        }

        if ($v['density'] === 'compact') {
            $css .= '.page-content{padding:16px;}.card{padding:14px;}.data-table td,.data-table th{padding:8px 12px;}.form-input,.form-select,.form-textarea{padding:7px 12px;}';
        } elseif ($v['density'] === 'spacious') {
            $css .= '.page-content{padding:32px;}.card{padding:24px;}.data-table td,.data-table th{padding:14px 18px;}';
        }

        if ($v['table_style'] === 'bordered') {
            $css .= '.data-table td,.data-table th{border:1px solid var(--border-light);}';
        } elseif ($v['table_style'] === 'minimal') {
            $css .= '.data-table thead{background:transparent;}.data-table th{border-bottom:2px solid var(--border-light);background:transparent;}.data-table td{border:none;}';
        }

        return $css;
    }
}
