<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Admin\Concerns\StoresUploads;
use App\Http\Controllers\Controller;
use App\Models\ColorTheme;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\View\View;

class ColorThemeController extends Controller
{
    use StoresUploads;

    public function index(): View
    {
        return view('admin.panel.themes.index', [
            'themes' => ColorTheme::orderBy('name')->get(),
        ]);
    }

    public function create(): View
    {
        return view('admin.panel.themes.create');
    }

    public function store(Request $request): RedirectResponse
    {
        $data = $this->validated($request);
        $data['logo'] = $this->storeUpload($request, 'logo', 'themes');
        $data['favicon'] = $this->storeUpload($request, 'favicon', 'themes');

        $theme = ColorTheme::create($data);

        if ($theme->is_active) {
            $this->activateTheme($theme);
        }

        return redirect()->route('admin.themes.index')->with('success', 'Tema berhasil ditambahkan.');
    }

    public function edit(ColorTheme $theme): View
    {
        return view('admin.panel.themes.edit', [
            'theme' => $theme,
        ]);
    }

    public function update(Request $request, ColorTheme $theme): RedirectResponse
    {
        $data = $this->validated($request);

        if ($logo = $this->storeUpload($request, 'logo', 'themes')) {
            if ($theme->logo) {
                Storage::disk('public')->delete($theme->logo);
            }
            $data['logo'] = $logo;
        }

        if ($favicon = $this->storeUpload($request, 'favicon', 'themes')) {
            if ($theme->favicon) {
                Storage::disk('public')->delete($theme->favicon);
            }
            $data['favicon'] = $favicon;
        }

        $theme->update($data);

        if ($theme->is_active) {
            $this->activateTheme($theme);
        }

        return redirect()->route('admin.themes.index')->with('success', 'Tema berhasil diperbarui.');
    }

    public function destroy(ColorTheme $theme): RedirectResponse
    {
        if ($theme->is_active) {
            return back()->withErrors(['theme' => 'Tema yang sedang aktif tidak bisa dihapus. Aktifkan tema lain terlebih dahulu.']);
        }

        foreach ([$theme->logo, $theme->favicon] as $path) {
            if ($path) {
                Storage::disk('public')->delete($path);
            }
        }

        $theme->delete();

        return redirect()->route('admin.themes.index')->with('success', 'Tema berhasil dihapus.');
    }

    public function activate(ColorTheme $theme): RedirectResponse
    {
        $this->activateTheme($theme);

        return back()->with('success', "Tema \"{$theme->name}\" sekarang aktif di homepage.");
    }

    private function activateTheme(ColorTheme $theme): void
    {
        DB::transaction(function () use ($theme) {
            ColorTheme::where('id', '!=', $theme->id)->update(['is_active' => false]);
            $theme->update(['is_active' => true]);
        });
    }

    private function validated(Request $request): array
    {
        $data = $request->validate([
            'name' => ['required', 'string', 'max:100'],
            'primary_color' => ['required', 'regex:/^#[0-9a-fA-F]{6}$/'],
            'logo' => ['nullable', 'image', 'max:2048'],
            'favicon' => ['nullable', 'mimes:ico,png,svg,jpg,jpeg,gif,webp', 'max:1024'],
            'is_active' => ['sometimes', 'boolean'],
        ]);

        unset($data['logo'], $data['favicon']);
        $data['is_active'] = $request->boolean('is_active');

        return $data;
    }
}
