<?php

namespace App\Livewire\Admin;

use App\Models\Language;
use Illuminate\Support\Facades\File;
use Livewire\Attributes\Locked;
use Livewire\Attributes\On;
use Livewire\Component;

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

    public $name;

    public $code;

    public $flag;

    public $status = 'active';

    public $isRtl = false;

    public $showModal = false;

    #[On('create-language')]
    public function create()
    {
        $this->resetForm();
        $this->showModal = true;
    }

    #[On('edit-language')]
    public function edit($id)
    {
        $this->resetForm();
        $language = Language::findOrFail($id);

        $this->languageId = $language->id;
        $this->name = $language->name;
        $this->code = $language->code;
        $this->flag = $language->flag;
        $this->isRtl = $language->is_rtl;
        $this->status = $language->status;
        $this->showModal = true;
    }

    #[On('closeLanguageForm')]
    public function closeFromDelete()
    {
        $this->closeModal();
    }

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

            return;
        }

        $validated = $this->validate([
            'name' => 'required|string|max:255',
            'code' => 'required|string|max:10|unique:languages,code,'.$this->languageId,
            'flag' => 'required|string|max:10',
            'isRtl' => 'boolean',
            'status' => 'required|in:active,inactive',
        ]);

        if ($this->languageId) {
            // Update existing language
            $language = Language::findOrFail($this->languageId);
            $language->update([
                'name' => $this->name,
                'code' => $this->code,
                'flag' => $this->flag,
                'is_rtl' => $this->isRtl,
                'status' => $this->status,
            ]);

            $this->dispatch('show-toast',
                type: 'success',
                message: __('common.item_updated', ['item' => 'Language'])
            );
        } else {
            // Create new language
            $language = Language::create([
                'name' => $this->name,
                'code' => $this->code,
                'flag' => $this->flag,
                'is_rtl' => $this->isRtl,
                'status' => $this->status,
            ]);

            // Create translation files for the new language
            $language->createTranslationFiles();

            $this->dispatch('show-toast',
                type: 'success',
                message: __('common.item_created', ['item' => 'Language'])
            );
        }

        $this->closeModal();
        $this->dispatch('languageUpdated');
    }

    public function closeModal()
    {
        $this->showModal = false;
        $this->resetValidation();
    }

    private function resetForm()
    {
        $this->languageId = null;
        $this->name = '';
        $this->code = '';
        $this->flag = '';
        $this->isRtl = false;
        $this->status = 'active';
        $this->resetValidation();
    }

    /**
     * Get available language folders from lang/ directory
     */
    public function getAvailableLanguageCodes(): array
    {
        $langPath = lang_path();
        $folders = File::directories($langPath);

        $codes = [];
        foreach ($folders as $folder) {
            $code = basename($folder);
            // Only include valid 2-3 letter language codes
            if (preg_match('/^[a-z]{2,3}$/i', $code)) {
                $codes[$code] = strtoupper($code);
            }
        }

        // Sort alphabetically
        ksort($codes);

        return $codes;
    }

    public function render()
    {
        return view('livewire.admin.language-form', [
            'availableLanguageCodes' => $this->getAvailableLanguageCodes(),
        ]);
    }
}
