<?php

namespace App\Livewire\Website;

use App\Domain\Website\Services\WebsiteCacheService;
use App\Domain\Website\Services\WebsiteSettingService;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Component;

#[Layout('layouts.app')]
#[Title('تصميم الموقع')]
class ThemeEditor extends Component
{
    // Template
    public string $template = 'bold_athletic';

    // Colors
    public string $primary_color = '#1a1a2e';
    public string $secondary_color = '#16213e';
    public string $accent_color = '#e94560';
    public string $text_color = '#ffffff';
    public string $background_color = '#ffffff';
    public string $surface_color = '#f8fafc';
    public string $border_color = '#e2e8f0';
    public string $muted_text_color = '#64748b';

    // Typography
    public string $heading_font = 'Cairo';
    public string $body_font = 'Cairo';
    public string $font_size_scale = 'medium';
    public string $heading_weight = '700';
    public string $line_height = 'normal';
    public string $letter_spacing = 'normal';

    // Spacing & Shapes
    public string $density = 'comfortable';
    public string $border_radius_preset = 'rounded';
    public string $card_style = 'raised';
    public string $section_divider = 'none';
    public string $image_shape = 'rounded';

    // Animation
    public bool $animations_enabled = true;
    public string $animation_speed = 'normal';

    // Navbar
    public string $navbar_style = 'transparent';
    public string $navbar_cta_text = '';
    public string $navbar_cta_link = '';
    public bool $navbar_show_social = false;
    public string $navbar_logo_position = 'start';

    // Footer
    public string $footer_style = 'dark';
    public int $footer_columns = 4;
    public array $footer_blocks = [];
    public string $footer_bottom_text = '';

    // General
    public string $site_title = '';
    public string $site_title_en = '';
    public string $site_description = '';
    public string $site_description_en = '';
    public string $whatsapp_number = '';
    public array $social_links = [];
    public string $custom_css = '';
    public string $google_analytics_id = '';
    public string $facebook_pixel_id = '';

    public array $availableFonts = [
        'Cairo', 'Tajawal', 'IBM Plex Sans Arabic', 'Noto Sans Arabic',
        'Almarai', 'Readex Pro', 'Rubik', 'El Messiri', 'Changa',
        'Noto Kufi Arabic', 'Alexandria', 'Baloo Bhaijaan 2',
    ];

    public array $templatePresets = [
        'bold_athletic' => ['label' => 'رياضي جريء', 'primary' => '#1a1a2e', 'secondary' => '#16213e', 'accent' => '#e94560', 'text' => '#ffffff', 'bg' => '#0f0f1a', 'surface' => '#1a1a2e', 'border' => '#2d2d4a', 'muted' => '#94a3b8'],
        'clean_professional' => ['label' => 'احترافي نظيف', 'primary' => '#ffffff', 'secondary' => '#f8fafc', 'accent' => '#2563eb', 'text' => '#1f2937', 'bg' => '#ffffff', 'surface' => '#f9fafb', 'border' => '#e5e7eb', 'muted' => '#6b7280'],
        'vibrant_playful' => ['label' => 'حيوي ومرح', 'primary' => '#fef3c7', 'secondary' => '#ecfccb', 'accent' => '#f59e0b', 'text' => '#1c1917', 'bg' => '#fffbeb', 'surface' => '#fef9c3', 'border' => '#fde68a', 'muted' => '#78716c'],
        'dark_sport' => ['label' => 'رياضي داكن', 'primary' => '#0a0a0a', 'secondary' => '#1c1c1c', 'accent' => '#22c55e', 'text' => '#ffffff', 'bg' => '#000000', 'surface' => '#111111', 'border' => '#2a2a2a', 'muted' => '#a1a1aa'],
        'minimal_corporate' => ['label' => 'مؤسسي بسيط', 'primary' => '#f9fafb', 'secondary' => '#ffffff', 'accent' => '#6366f1', 'text' => '#111827', 'bg' => '#ffffff', 'surface' => '#f3f4f6', 'border' => '#d1d5db', 'muted' => '#9ca3af'],
        'gradient_modern' => ['label' => 'عصري متدرج', 'primary' => '#1e1b4b', 'secondary' => '#312e81', 'accent' => '#a78bfa', 'text' => '#ffffff', 'bg' => '#0f0b2e', 'surface' => '#1e1b4b', 'border' => '#3730a3', 'muted' => '#a5b4fc'],
        'neon_energy' => ['label' => 'نيون حيوي', 'primary' => '#18181b', 'secondary' => '#27272a', 'accent' => '#facc15', 'text' => '#ffffff', 'bg' => '#09090b', 'surface' => '#18181b', 'border' => '#3f3f46', 'muted' => '#a1a1aa'],
        'earth_natural' => ['label' => 'طبيعي دافئ', 'primary' => '#fefce8', 'secondary' => '#f0fdf4', 'accent' => '#65a30d', 'text' => '#1c1917', 'bg' => '#fafaf9', 'surface' => '#f5f5f4', 'border' => '#d6d3d1', 'muted' => '#78716c'],
    ];

    public function mount(): void
    {
        $this->authorize('settings.manage');

        $settings = app(WebsiteSettingService::class)->getOrCreate(app('current_academy'));

        $this->template = $settings->template ?? 'bold_athletic';
        $this->primary_color = $settings->primary_color;
        $this->secondary_color = $settings->secondary_color;
        $this->accent_color = $settings->accent_color;
        $this->text_color = $settings->text_color;
        $this->background_color = $settings->background_color ?? '#ffffff';
        $this->surface_color = $settings->surface_color ?? '#f8fafc';
        $this->border_color = $settings->border_color ?? '#e2e8f0';
        $this->muted_text_color = $settings->muted_text_color ?? '#64748b';
        $this->heading_font = $settings->heading_font;
        $this->body_font = $settings->body_font;
        $this->font_size_scale = $settings->font_size_scale ?? 'medium';
        $this->heading_weight = $settings->heading_weight ?? '700';
        $this->line_height = $settings->line_height ?? 'normal';
        $this->letter_spacing = $settings->letter_spacing ?? 'normal';
        $this->density = $settings->density ?? 'comfortable';
        $this->border_radius_preset = $settings->border_radius_preset ?? 'rounded';
        $this->card_style = $settings->card_style ?? 'raised';
        $this->section_divider = $settings->section_divider ?? 'none';
        $this->image_shape = $settings->image_shape ?? 'rounded';
        $this->animations_enabled = $settings->animations_enabled ?? true;
        $this->animation_speed = $settings->animation_speed ?? 'normal';
        $this->navbar_style = $settings->navbar_style;
        $this->navbar_cta_text = $settings->navbar_cta_text ?? '';
        $this->navbar_cta_link = $settings->navbar_cta_link ?? '';
        $this->navbar_show_social = $settings->navbar_show_social ?? false;
        $this->navbar_logo_position = $settings->navbar_logo_position ?? 'start';
        $this->footer_style = $settings->footer_style ?? 'dark';
        $this->footer_columns = $settings->footer_columns ?? 4;
        $this->footer_blocks = $settings->footer_blocks ?? [];
        $this->footer_bottom_text = $settings->footer_bottom_text ?? '';
        $this->site_title = $settings->site_title ?? '';
        $this->site_title_en = $settings->site_title_en ?? '';
        $this->site_description = $settings->site_description ?? '';
        $this->site_description_en = $settings->site_description_en ?? '';
        $this->whatsapp_number = $settings->whatsapp_number ?? '';
        $this->social_links = $settings->social_links ?? [];
        $this->custom_css = $settings->custom_css ?? '';
        $this->google_analytics_id = $settings->google_analytics_id ?? '';
        $this->facebook_pixel_id = $settings->facebook_pixel_id ?? '';
    }

    public function applyTemplate(string $template): void
    {
        if (!isset($this->templatePresets[$template])) {
            return;
        }

        $preset = $this->templatePresets[$template];
        $this->template = $template;
        $this->primary_color = $preset['primary'];
        $this->secondary_color = $preset['secondary'];
        $this->accent_color = $preset['accent'];
        $this->text_color = $preset['text'];
        $this->background_color = $preset['bg'];
        $this->surface_color = $preset['surface'];
        $this->border_color = $preset['border'];
        $this->muted_text_color = $preset['muted'];
    }

    public function generatePaletteFromAccent(): void
    {
        $hex = ltrim($this->accent_color, '#');
        $r = hexdec(substr($hex, 0, 2));
        $g = hexdec(substr($hex, 2, 2));
        $b = hexdec(substr($hex, 4, 2));
        [$h, $s, $l] = $this->rgbToHsl($r, $g, $b);

        $isDark = $l < 0.5;

        if ($isDark) {
            $this->background_color = '#ffffff';
            $this->surface_color = '#f9fafb';
            $this->text_color = '#111827';
            $this->muted_text_color = '#6b7280';
            $this->border_color = '#e5e7eb';
            $this->primary_color = $this->hslToHex($h, max(0.1, $s * 0.3), 0.95);
            $this->secondary_color = $this->hslToHex($h, max(0.05, $s * 0.2), 0.97);
        } else {
            $this->background_color = $this->hslToHex($h, max(0.05, $s * 0.4), 0.06);
            $this->surface_color = $this->hslToHex($h, max(0.08, $s * 0.3), 0.10);
            $this->text_color = '#ffffff';
            $this->muted_text_color = $this->hslToHex($h, 0.1, 0.65);
            $this->border_color = $this->hslToHex($h, 0.1, 0.20);
            $this->primary_color = $this->hslToHex($h, max(0.1, $s * 0.4), 0.12);
            $this->secondary_color = $this->hslToHex($h, max(0.1, $s * 0.35), 0.15);
        }
    }

    public function save(): void
    {
        $this->validate([
            'template' => 'required|in:bold_athletic,clean_professional,vibrant_playful,dark_sport,minimal_corporate,gradient_modern,neon_energy,earth_natural',
            'primary_color' => 'required|regex:/^#[0-9a-fA-F]{6}$/',
            'secondary_color' => 'required|regex:/^#[0-9a-fA-F]{6}$/',
            'accent_color' => 'required|regex:/^#[0-9a-fA-F]{6}$/',
            'text_color' => 'required|regex:/^#[0-9a-fA-F]{6}$/',
            'background_color' => 'required|regex:/^#[0-9a-fA-F]{6}$/',
            'surface_color' => 'required|regex:/^#[0-9a-fA-F]{6}$/',
            'border_color' => 'required|regex:/^#[0-9a-fA-F]{6}$/',
            'muted_text_color' => 'required|regex:/^#[0-9a-fA-F]{6}$/',
            'heading_font' => 'required|string|max:50',
            'body_font' => 'required|string|max:50',
            'font_size_scale' => 'required|in:small,medium,large,xlarge',
            'heading_weight' => 'required|in:400,500,600,700,800,900',
            'line_height' => 'required|in:tight,normal,relaxed,loose',
            'letter_spacing' => 'required|in:tight,normal,wide',
            'density' => 'required|in:compact,comfortable,spacious',
            'border_radius_preset' => 'required|in:sharp,subtle,rounded,pill',
            'card_style' => 'required|in:flat,raised,bordered,glass',
            'section_divider' => 'required|in:none,line,wave,angle,curve',
            'image_shape' => 'required|in:square,rounded,circle,blob',
            'animations_enabled' => 'boolean',
            'animation_speed' => 'required|in:slow,normal,fast',
            'navbar_style' => 'required|in:solid,transparent,floating,centered,minimal',
            'navbar_cta_text' => 'nullable|string|max:50',
            'navbar_cta_link' => 'nullable|string|max:255',
            'navbar_show_social' => 'boolean',
            'navbar_logo_position' => 'required|in:start,center,end',
            'footer_style' => 'required|in:dark,light,accent,transparent',
            'footer_columns' => 'required|integer|min:2|max:4',
            'footer_blocks' => 'nullable|array',
            'footer_bottom_text' => 'nullable|string|max:500',
            'site_title' => 'nullable|string|max:255',
            'site_description' => 'nullable|string|max:1000',
            'whatsapp_number' => 'nullable|string|max:20',
        ]);

        app(WebsiteSettingService::class)->update(app('current_academy'), [
            'template' => $this->template,
            'primary_color' => $this->primary_color,
            'secondary_color' => $this->secondary_color,
            'accent_color' => $this->accent_color,
            'text_color' => $this->text_color,
            'background_color' => $this->background_color,
            'surface_color' => $this->surface_color,
            'border_color' => $this->border_color,
            'muted_text_color' => $this->muted_text_color,
            'heading_font' => $this->heading_font,
            'body_font' => $this->body_font,
            'font_size_scale' => $this->font_size_scale,
            'heading_weight' => $this->heading_weight,
            'line_height' => $this->line_height,
            'letter_spacing' => $this->letter_spacing,
            'density' => $this->density,
            'border_radius_preset' => $this->border_radius_preset,
            'card_style' => $this->card_style,
            'section_divider' => $this->section_divider,
            'image_shape' => $this->image_shape,
            'animations_enabled' => $this->animations_enabled,
            'animation_speed' => $this->animation_speed,
            'navbar_style' => $this->navbar_style,
            'navbar_cta_text' => $this->navbar_cta_text,
            'navbar_cta_link' => $this->navbar_cta_link,
            'navbar_show_social' => $this->navbar_show_social,
            'navbar_logo_position' => $this->navbar_logo_position,
            'footer_style' => $this->footer_style,
            'footer_columns' => $this->footer_columns,
            'footer_blocks' => $this->footer_blocks,
            'footer_bottom_text' => $this->footer_bottom_text,
            'site_title' => $this->site_title,
            'site_title_en' => $this->site_title_en,
            'site_description' => $this->site_description,
            'site_description_en' => $this->site_description_en,
            'whatsapp_number' => $this->whatsapp_number,
            'social_links' => $this->social_links,
            'custom_css' => $this->custom_css,
            'google_analytics_id' => $this->google_analytics_id,
            'facebook_pixel_id' => $this->facebook_pixel_id,
        ]);

        app(WebsiteCacheService::class)->invalidateAll(app('current_academy'));

        session()->flash('success', __('تم حفظ إعدادات التصميم بنجاح'));
    }

    private function rgbToHsl(int $r, int $g, int $b): array
    {
        $r /= 255;
        $g /= 255;
        $b /= 255;
        $max = max($r, $g, $b);
        $min = min($r, $g, $b);
        $l = ($max + $min) / 2;

        if ($max === $min) {
            return [0, 0, $l];
        }

        $d = $max - $min;
        $s = $l > 0.5 ? $d / (2 - $max - $min) : $d / ($max + $min);

        $h = match ($max) {
            $r => (($g - $b) / $d + ($g < $b ? 6 : 0)) / 6,
            $g => (($b - $r) / $d + 2) / 6,
            default => (($r - $g) / $d + 4) / 6,
        };

        return [$h, $s, $l];
    }

    private function hslToHex(float $h, float $s, float $l): string
    {
        $s = max(0, min(1, $s));
        $l = max(0, min(1, $l));

        if ($s === 0.0) {
            $v = (int) round($l * 255);
            return sprintf('#%02x%02x%02x', $v, $v, $v);
        }

        $q = $l < 0.5 ? $l * (1 + $s) : $l + $s - $l * $s;
        $p = 2 * $l - $q;

        $r = $this->hueToRgb($p, $q, $h + 1 / 3);
        $g = $this->hueToRgb($p, $q, $h);
        $b = $this->hueToRgb($p, $q, $h - 1 / 3);

        return sprintf('#%02x%02x%02x', (int) round($r * 255), (int) round($g * 255), (int) round($b * 255));
    }

    private function hueToRgb(float $p, float $q, float $t): float
    {
        if ($t < 0) $t += 1;
        if ($t > 1) $t -= 1;
        if ($t < 1 / 6) return $p + ($q - $p) * 6 * $t;
        if ($t < 1 / 2) return $q;
        if ($t < 2 / 3) return $p + ($q - $p) * (2 / 3 - $t) * 6;
        return $p;
    }

    public function render()
    {
        return view('livewire.website.theme-editor');
    }
}
