<?php

namespace App\Filament\Pages;

use Filament\Pages\Page;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Artisan;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Forms\Components\Grid;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\TextInput\Mask;
use Filament\Actions\Action;
use Filament\Actions\Concerns\CanOpenModal;
use Filament\Forms\Components\Section;
use Filament\Notifications\Notification;
use Illuminate\Support\Str;

class TranslationManager extends Page
{
    protected static ?string $navigationIcon = 'heroicon-o-language';
    protected static ?string $title = 'Frontend Translations';
    protected static string $view = 'filament.pages.translation-manager';
    protected static ?string $navigationLabel = 'Frontend Translations';
    protected static ?int $navigationSort = 99;
    protected static ?string $navigationGroup = 'Content';


    public array $translations = [];
    public string $search = '';

    public function mount(): void
    {
        $this->search = ''; // Ensure search is empty initially
        $this->loadTranslations();
    }

    protected function loadTranslations(): void
    {
        $en = File::exists(lang_path('en.json')) ? json_decode(File::get(lang_path('en.json')), true) : [];
        $ar = File::exists(lang_path('ar.json')) ? json_decode(File::get(lang_path('ar.json')), true) : [];
        $allKeys = array_unique(array_merge(array_keys($en), array_keys($ar)));

        $this->translations = [];

        foreach ($allKeys as $key) {
            if (!empty($this->search) && !Str::contains(Str::lower($key), Str::lower($this->search))) {
                continue;
            }

            $this->translations[] = [
                'key' => $key,
                'en' => $en[$key] ?? '',
                'ar' => $ar[$key] ?? '',
            ];
        }
    }

    public function updated($property): void
    {
        if ($property === 'search') {
            $this->loadTranslations(); // re-filter when typing
        }
    }

    public function save(): void
    {
        // Load existing full translations
        $existingEn = File::exists(lang_path('en.json')) ? json_decode(File::get(lang_path('en.json')), true) : [];
        $existingAr = File::exists(lang_path('ar.json')) ? json_decode(File::get(lang_path('ar.json')), true) : [];

        // Update only modified keys from the form
        foreach ($this->translations as $row) {
            $existingEn[$row['key']] = $row['en'];
            $existingAr[$row['key']] = $row['ar'];
        }

        // Save the merged full translations back to disk
        File::put(lang_path('en.json'), json_encode($existingEn, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
        File::put(lang_path('ar.json'), json_encode($existingAr, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));

        Notification::make()
            ->title('Translations saved successfully!')
            ->success()
            ->send();
    }


    public function sync(): void
    {
        Artisan::call('translations:sync-frontend');
        $this->loadTranslations();
        Notification::make()
        ->title('Translations synced successfully!')
        ->success()
        ->send();
    }

    protected function getFormSchema(): array
    {
        return [
            TextInput::make('search')
                ->label('Search Key')
                ->placeholder('Search by key...')
                ->live()
                ->debounce(300)
                ->columnSpanFull(),

            Section::make('Translations')
                ->schema([
                    Repeater::make('translations')
                        ->label('Translation Items')
                        ->itemLabel(fn (array $state): ?string => $state['key'] ?? 'Translation')
                        ->schema([
                            Grid::make(3)->schema([
                                TextInput::make('key')
                                    ->label('Key')
                                    ->disabled()
                                    ->required(),

                                Textarea::make('en')
                                    ->label('English')
                                    ->rows(1),

                                Textarea::make('ar')
                                    ->label('Arabic')
                                    ->rows(1),
                            ]),
                        ])
                        ->collapsible(true)
                        ->collapsed(true)
                        ->columns(1)
                        ->addable(false)
                        ->deletable(false)
                        ->reorderable(false)
                        ->columnSpanFull(),
                ])
        ];
    }


    public function form(Form $form): Form
    {
        return $form->schema($this->getFormSchema());
    }

    protected function getHeaderActions(): array
    {
        return [
            Action::make('Sync')
                ->label('Sync Translations')
                ->icon('heroicon-o-arrow-path')
                ->color('gray')
                ->action('sync')
                ->requiresConfirmation(),

            Action::make('Save')
                ->action('save')
                ->color('primary'),
        ];
    }

    public static function shouldRegisterNavigation(): bool
    {
        return true;
    }
}
