<?php

namespace App\Http\Controllers;

use App\Models\OrganizationSetting;
use App\Models\Theme;
use App\Support\AccessControl;
use App\Support\ThemeManager;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;

class ProfileThemeController extends Controller
{
    public function store(Request $request): RedirectResponse
    {
        $actor = $request->user();
        abort_unless(AccessControl::canManageAccess($actor), 403);

        $defaults = ThemeManager::defaults();

        $validated = $request->validate([
            'name' => ['required', 'string', 'max:120'],
            'slug' => ['nullable', 'string', 'max:120', Rule::unique('themes', 'slug')],
            'palette' => ['nullable', 'array'],
            'palette.*' => ['nullable', 'string', 'regex:/^#[0-9A-Fa-f]{6}$/'],
            'fonts' => ['nullable', 'array'],
            'fonts.body' => ['nullable', 'string', 'max:200'],
            'fonts.heading' => ['nullable', 'string', 'max:200'],
            'fonts.url' => ['nullable', 'url', 'max:2048'],
            'icons' => ['nullable', 'array'],
            'icons.color' => ['nullable', 'string', 'regex:/^#[0-9A-Fa-f]{6}$/'],
            'icons.muted' => ['nullable', 'string', 'regex:/^#[0-9A-Fa-f]{6}$/'],
            'custom_css' => ['nullable', 'string', 'max:10000'],
        ]);

        $name = trim((string) $validated['name']);
        $slug = trim((string) ($validated['slug'] ?? ''));
        if ($slug === '') {
            $slug = Str::slug($name);
        }

        $slug = $this->uniqueSlug($slug);

        $palette = array_replace($defaults['palette'], $validated['palette'] ?? []);
        $fonts = array_replace($defaults['fonts'], $validated['fonts'] ?? []);
        $icons = array_replace($defaults['icons'], $validated['icons'] ?? []);

        Theme::query()->create([
            'name' => $name,
            'slug' => $slug,
            'palette' => $palette,
            'fonts' => $fonts,
            'icons' => $icons,
            'custom_css' => $validated['custom_css'] ?? null,
            'created_by' => $actor?->id,
        ]);

        return Redirect::route('profile.edit', ['section' => 'themes'])
            ->with('status', 'theme-created');
    }

    public function activate(Request $request, Theme $theme): RedirectResponse
    {
        $actor = $request->user();
        abort_unless(AccessControl::canManageAccess($actor), 403);

        $setting = OrganizationSetting::current();
        $setting->theme_id = $theme->id;
        $setting->save();

        return Redirect::route('profile.edit', ['section' => 'themes'])
            ->with('status', 'theme-activated');
    }

    public function destroy(Request $request, Theme $theme): RedirectResponse
    {
        $actor = $request->user();
        abort_unless(AccessControl::canManageAccess($actor), 403);

        $setting = OrganizationSetting::current();
        if ((int) ($setting->theme_id ?? 0) === (int) $theme->id) {
            $setting->theme_id = null;
            $setting->save();
        }

        $theme->delete();

        return Redirect::route('profile.edit', ['section' => 'themes'])
            ->with('status', 'theme-deleted');
    }

    private function uniqueSlug(string $slug): string
    {
        $base = $slug !== '' ? $slug : 'theme';
        $candidate = $base;
        $suffix = 1;

        while (Theme::query()->where('slug', $candidate)->exists()) {
            $suffix++;
            $candidate = $base.'-'.$suffix;
        }

        return $candidate;
    }
}
