<?php

namespace App\Livewire\Admin;

use App\Models\Language;
use App\Models\SystemSetting;
use Livewire\Attributes\Locked;
use Livewire\Attributes\On;
use Livewire\Component;

class DeleteLanguageModal extends Component
{
    #[Locked]
    public $languageId;

    public $languageName;

    public $showModal = false;

    public $isDefaultLanguage = false;

    #[On('delete-language')]
    public function confirmDelete($id, $name)
    {
        $this->languageId = $id;
        $this->languageName = $name;

        // Check if this is the default language or the first language
        $language = Language::find($id);
        $defaultLocale = SystemSetting::get('default_locale', 'en');
        $firstLanguageId = Language::orderBy('id')->first()?->id;

        $this->isDefaultLanguage = $language && (
            $language->code === $defaultLocale || $language->id === $firstLanguageId
        );

        $this->showModal = true;
    }

    public function delete()
    {
        if (config('app.demo')) {
            $this->dispatch('show-toast',
                type: 'error',
                message: __('common.demo_mode_deletion_disabled')
            );
            $this->closeModal();

            return;
        }

        // Prevent deletion of default language
        if ($this->isDefaultLanguage) {
            $this->dispatch('show-toast',
                type: 'error',
                message: __('admin.cannot_delete_default_language')
            );
            $this->closeModal();

            return;
        }

        if ($this->languageId) {
            Language::findOrFail($this->languageId)->delete();
            $this->dispatch('show-toast',
                type: 'success',
                message: __('common.item_deleted', ['item' => 'Language'])
            );
            $this->closeModal();
            $this->dispatch('languageUpdated');
            $this->dispatch('closeLanguageForm');
        }
    }

    public function closeModal()
    {
        $this->showModal = false;
        // Don't reset other properties immediately to prevent flashing during close animation
        // They will be set correctly when confirmDelete is called next time
    }

    public function render()
    {
        return view('livewire.admin.delete-language-modal');
    }
}
