<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\StoreLanguageRequest;
use App\Http\Requests\UpdateLanguageRequest;
use App\Models\Language;
use App\Services\Localization\LanguageService;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View;

class LanguageController extends Controller
{
    public function index(LanguageService $languages): View
    {
        $languages->ensureDefaults();
        $languageRows = Language::query()->withCount([
            'translations',
            'translations as missing_translations_count' => fn ($query) => $query->where('is_missing', true),
        ])->orderByDesc('is_default')->orderBy('sort_order')->orderBy('name')->get();

        return view('admin.settings.languages.index', [
            'languages' => $languageRows,
            'activeTab' => 'languages',
            'stats' => [
                'active' => $languageRows->where('is_active', true)->count(),
                'default' => $languageRows->firstWhere('is_default', true)?->name ?? 'English',
                'rtl' => $languageRows->where('direction', 'rtl')->count(),
            ],
        ]);
    }

    public function create(): View
    {
        return view('admin.settings.languages.create', [
            'language' => new Language(['direction' => 'ltr', 'is_active' => true]),
            'activeTab' => 'languages',
            'formAction' => route('admin.settings.languages.store'),
            'formMethod' => 'POST',
            'submitLabel' => 'Save Language',
        ]);
    }

    public function store(StoreLanguageRequest $request, LanguageService $languages): RedirectResponse
    {
        $language = Language::query()->create($request->validated());
        $languages->seedCatalogFor($language);

        if ($request->boolean('is_default')) {
            $languages->setDefault($language);
        }

        return redirect()->route('admin.settings.languages.index')->with('status', 'Language created successfully.');
    }

    public function edit(Language $language): View
    {
        return view('admin.settings.languages.edit', [
            'language' => $language,
            'activeTab' => 'languages',
            'formAction' => route('admin.settings.languages.update', $language),
            'formMethod' => 'PUT',
            'submitLabel' => 'Update Language',
        ]);
    }

    public function update(UpdateLanguageRequest $request, Language $language, LanguageService $languages): RedirectResponse
    {
        $language->update($request->validated());

        if ($request->boolean('is_default')) {
            $languages->setDefault($language);
        }

        $languages->seedCatalogFor($language);

        return redirect()->route('admin.settings.languages.index')->with('status', 'Language updated successfully.');
    }

    public function makeDefault(Language $language, LanguageService $languages): RedirectResponse
    {
        $languages->setDefault($language);

        return redirect()->route('admin.settings.languages.index')->with('status', "{$language->name} is now the default language.");
    }

    public function toggle(Language $language): RedirectResponse
    {
        abort_if($language->is_default && $language->is_active, 422, 'Default language cannot be disabled.');

        $language->forceFill(['is_active' => ! $language->is_active])->save();

        return redirect()->route('admin.settings.languages.index')->with('status', 'Language status updated.');
    }

    public function destroy(Language $language): RedirectResponse
    {
        abort_if($language->is_default, 422, 'Default language cannot be deleted.');
        $language->delete();

        return redirect()->route('admin.settings.languages.index')->with('status', 'Language deleted successfully.');
    }
}
