<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\BrandKit;
use App\Models\Client;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Illuminate\View\View;

class BrandKitController extends Controller
{
    public function index(Request $request): View
    {
        $page_title = 'Marka Kitleri';
        $page_description = 'Rapor PDF, Excel ve mail çıktılarında kullanılacak logo, renk ve kapak tasarımları';
        $clients = Client::orderBy('company_name')->get();

        $brandKits = BrandKit::with('client')
            ->withCount('reportTemplates')
            ->when($request->filled('client_id'), fn ($query) => $query->where('client_id', $request->integer('client_id')))
            ->when($request->filled('status'), fn ($query) => $query->where('is_active', $request->string('status') === 'active'))
            ->when($request->filled('q'), function ($query) use ($request) {
                $term = '%' . Str::lower($request->string('q')) . '%';
                $query->whereRaw('LOWER(name) LIKE ?', [$term]);
            })
            ->orderByRaw('client_id IS NOT NULL')
            ->orderBy('sort_order')
            ->orderBy('name')
            ->paginate(20)
            ->withQueryString();

        return view('admin.brand-kits.index', compact('page_title', 'page_description', 'brandKits', 'clients'));
    }

    public function create(): View
    {
        $page_title = 'Marka Kiti Ekle';
        $page_description = 'Ajans veya müşteri için rapor marka kimliği oluşturun';
        $clients = Client::orderBy('company_name')->get();
        $brandKit = new BrandKit([
            'primary_color' => '#111827',
            'accent_color' => '#ef5f86',
            'secondary_color' => '#f8fafc',
            'text_color' => '#111827',
            'muted_color' => '#6b7280',
            'cover_style' => 'gradient',
            'is_active' => true,
            'sort_order' => 100,
        ]);

        return view('admin.brand-kits.create', compact('page_title', 'page_description', 'clients', 'brandKit'));
    }

    public function store(Request $request): RedirectResponse
    {
        $brandKit = BrandKit::create($this->validated($request));
        $this->resetOtherDefaults($brandKit);

        return redirect()->route('admin.brand-kits.show', $brandKit)->with('success', 'Marka kiti oluşturuldu.');
    }

    public function show(BrandKit $brandKit): View
    {
        $page_title = 'Marka Kiti Detayı';
        $page_description = $brandKit->name;
        $brandKit->load(['client', 'reportTemplates']);

        return view('admin.brand-kits.show', compact('page_title', 'page_description', 'brandKit'));
    }

    public function edit(BrandKit $brandKit): View
    {
        $page_title = 'Marka Kiti Düzenle';
        $page_description = $brandKit->name;
        $clients = Client::orderBy('company_name')->get();

        return view('admin.brand-kits.edit', compact('page_title', 'page_description', 'clients', 'brandKit'));
    }

    public function update(Request $request, BrandKit $brandKit): RedirectResponse
    {
        $brandKit->fill($this->validated($request));
        $brandKit->save();
        $this->resetOtherDefaults($brandKit);

        return redirect()->route('admin.brand-kits.show', $brandKit)->with('success', 'Marka kiti güncellendi.');
    }

    public function destroy(BrandKit $brandKit): RedirectResponse
    {
        $brandKit->delete();

        return redirect()->route('admin.brand-kits.index')->with('success', 'Marka kiti silindi.');
    }

    public function duplicate(BrandKit $brandKit): RedirectResponse
    {
        $copy = $brandKit->replicate();
        $copy->name = 'Kopya - ' . $brandKit->name;
        $copy->is_default = false;
        $copy->is_active = true;
        $copy->sort_order = ((int) $brandKit->sort_order) + 1;
        $copy->save();

        return redirect()->route('admin.brand-kits.edit', $copy)->with('success', 'Marka kiti kopyalandı.');
    }

    /** @return array<string, mixed> */
    private function validated(Request $request): array
    {
        $data = $request->validate([
            'client_id' => ['nullable', 'exists:clients,id'],
            'name' => ['required', 'string', 'max:180'],
            'description' => ['nullable', 'string', 'max:2000'],
            'agency_name' => ['nullable', 'string', 'max:160'],
            'agency_logo_url' => ['nullable', 'string', 'max:500'],
            'client_logo_url' => ['nullable', 'string', 'max:500'],
            'primary_color' => ['required', 'string', 'max:20'],
            'accent_color' => ['required', 'string', 'max:20'],
            'secondary_color' => ['nullable', 'string', 'max:20'],
            'text_color' => ['nullable', 'string', 'max:20'],
            'muted_color' => ['nullable', 'string', 'max:20'],
            'cover_style' => ['required', 'in:gradient,minimal,image,dark'],
            'cover_background_url' => ['nullable', 'string', 'max:500'],
            'footer_note' => ['nullable', 'string', 'max:600'],
            'contact_email' => ['nullable', 'email', 'max:180'],
            'contact_phone' => ['nullable', 'string', 'max:80'],
            'website_url' => ['nullable', 'string', 'max:220'],
            'settings' => ['nullable', 'array'],
            'is_default' => ['nullable', 'boolean'],
            'is_active' => ['nullable', 'boolean'],
            'sort_order' => ['nullable', 'integer', 'between:0,9999'],
        ]);

        foreach (['primary_color', 'accent_color', 'secondary_color', 'text_color', 'muted_color'] as $key) {
            if (! empty($data[$key]) && ! preg_match('/^#[0-9a-fA-F]{6}$/', $data[$key])) {
                $data[$key] = match ($key) {
                    'primary_color' => '#111827',
                    'accent_color' => '#ef5f86',
                    'secondary_color' => '#f8fafc',
                    'text_color' => '#111827',
                    default => '#6b7280',
                };
            }
        }

        $data['is_default'] = $request->boolean('is_default');
        $data['is_active'] = $request->boolean('is_active');
        $data['sort_order'] = (int) ($data['sort_order'] ?? 100);

        return $data;
    }

    private function resetOtherDefaults(BrandKit $brandKit): void
    {
        if (! $brandKit->is_default) {
            return;
        }

        BrandKit::query()
            ->where('id', '!=', $brandKit->id)
            ->where(function ($query) use ($brandKit) {
                $brandKit->client_id
                    ? $query->where('client_id', $brandKit->client_id)
                    : $query->whereNull('client_id');
            })
            ->update(['is_default' => false]);
    }
}
