<?php

namespace App\Http\Controllers;

use App\Support\UserStartPage;
use App\Support\ThemeManager;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Storage;
use Illuminate\Validation\Rule;

class ProfileAppearanceController extends Controller
{
    public function update(Request $request): RedirectResponse
    {
        $user = $request->user();

        $validated = $request->validate([
            'start_page' => ['nullable', 'string', Rule::in(array_keys(UserStartPage::routeMap()))],
            'preset' => ['nullable', 'string', Rule::in(array_merge([''], array_keys(ThemeManager::userPresets())))],
            '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}$/'],
            'background_image' => ['nullable', 'image', 'max:10240'],
            'remove_background_image' => ['nullable', 'boolean'],
        ]);

        $preset = trim((string) ($validated['preset'] ?? ''));

        $appearance = [
            'preset' => $preset !== '' ? $preset : null,
            'palette' => $validated['palette'] ?? [],
            'fonts' => $validated['fonts'] ?? [],
            'icons' => $validated['icons'] ?? [],
        ];

        $user->appearance_settings = $appearance;
        $user->start_page = $validated['start_page'] ?? null;

        if ($request->boolean('remove_background_image') && $user->background_image_path) {
            Storage::disk('public')->delete((string) $user->background_image_path);
            $user->background_image_path = null;
        }

        if ($request->hasFile('background_image')) {
            $newPath = $request->file('background_image')->store('user-backgrounds', 'public');
            if ($user->background_image_path && $user->background_image_path !== $newPath) {
                Storage::disk('public')->delete((string) $user->background_image_path);
            }
            $user->background_image_path = $newPath;
        }

        $user->save();

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