<?php

namespace App\Http\Controllers\Core;

use App\Enums\BulkActionEnum;
use App\Enums\StatusEnum;
use App\Http\Controllers\Controller;
use App\Models\Core\Language;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Illuminate\Validation\Rule;

class LanguageController extends Controller
{
    /**
     * Summary of store
     * @param \Illuminate\Http\Request $request
     * @return RedirectResponse
     */
    public function store(Request $request): RedirectResponse
    {
        $request->validate([
            "name" => "required|string",
            "code" => "required|string",
            "ltr" => "required|integer",
            "lang_code" => "required|string"
        ]);


        try {
            $language = Language::create([
                "name" => $request->input("name"),
                "code" => $request->input("code"),
                "ltr" => $request->input("ltr"),
                "lang_code" => $request->input("lang_code"),
            ]);

            $langPath = resource_path("lang/{$language->lang_code}");

            if (!File::exists($langPath)) {
                File::makeDirectory($langPath, 0755, true);
            }

            $filePath = $langPath . "/messages.php";

            if (!File::exists($filePath)) {
                // Get English translations as base
                $this->createLanguageFileWithTranslations($language, $filePath);
            }
        } catch (\Throwable $th) {
            return back()->with("error", $th->getMessage());
        }



        return redirect()->back()->with("success", "Language saved");
    }



    /**
     * Summary of delete
     * @param \Illuminate\Http\Request $request
     * @return RedirectResponse
     */
    public function delete(Request $request): RedirectResponse
    {
        $request->validate([
            'id' => 'required|exists:languages,id'
        ]);

        $language = Language::findOrFail($request->input('id'));

        // Prevent deletion of default language
        if ($language->is_default == StatusEnum::true->status()) {
            return redirect()->back()->with('error', 'Cannot delete the default language. Please set another language as default first.');
        }

        try {
            $langPath = resource_path("lang/{$language->lang_code}");

            if (File::exists($langPath)) {
                File::deleteDirectory($langPath);
            }

            $language->delete();

        } catch (\Throwable $th) {
            return redirect()->back()->with('error', $th->getMessage());
        }

        return redirect()->back()->with('success', 'Language Deleted');

    }

    /**
     * Summary of statusUpdate
     * @param \Illuminate\Http\Request $request
     * @return RedirectResponse
     */
    public function statusUpdate(Request $request): RedirectResponse
    {
        $request->validate([
            'id' => 'required|exists:languages,id',
            'status' => 'required',
        ]);

        try {
            $language = Language::findOrFail($request->id);
            $language->status = $request->status;
            $language->save();

            return back()->with('success', 'Language status updated successfully');
        } catch (\Exception $e) {
            return back()->with('error', 'Language status did not change');

        }
    }


    /**
     * Summary of bulk
     * @param \Illuminate\Http\Request $request
     * @return RedirectResponse
     */
    public function bulk(Request $request): RedirectResponse
    {
        $validated = $request->validate([
            'action' => ['required', Rule::in(BulkActionEnum::values())],
            'ids' => 'required|array',
            'ids.*' => 'integer'
        ]);

        $query = Language::whereIn('id', $validated['ids']);

        match (BulkActionEnum::from($validated['action'])) {
            BulkActionEnum::ACTIVATE => $query->update(['status' => StatusEnum::true->status()]),
            BulkActionEnum::INACTIVATE => $query->update(['status' => StatusEnum::false->status()]),
            BulkActionEnum::DELETE => $this->handleBulkDelete($validated['ids']),
        };

        return back()->with('success', "Bulk {$validated['action']} completed.");
    }

    /**
     * Handle bulk delete with default language protection
     * @param array $ids
     * @return void
     */
    private function handleBulkDelete(array $ids): void
    {
        // Check if any of the languages to be deleted is the default language
        $defaultLanguage = Language::whereIn('id', $ids)
            ->where('is_default', StatusEnum::true->status())
            ->first();

        if ($defaultLanguage) {
            // Remove the default language from the deletion list
            $ids = array_filter($ids, function($id) use ($defaultLanguage) {
                return $id != $defaultLanguage->id;
            });
        }

        if (!empty($ids)) {
            // Delete non-default languages and their directories
            $languages = Language::whereIn('id', $ids)->get();
            
            foreach ($languages as $language) {
                $langPath = resource_path("lang/{$language->lang_code}");
                if (File::exists($langPath)) {
                    File::deleteDirectory($langPath);
                }
            }
            
            Language::whereIn('id', $ids)->delete();
        }
    }


    /**
     * Summary of makeDefault
     * @param int $id
     * @throws \Exception
     * @return RedirectResponse
     */
    public function makeDefault(Request $request): RedirectResponse
    {
        $request->validate([
            "id" => "required|exists:languages,id"
        ]);

        DB::beginTransaction();

        try {
            DB::table('languages')
                ->where('is_default', StatusEnum::true->status())
                ->update(['is_default' => StatusEnum::false->status()]);

            $updated = DB::table('languages')
                ->where('id', $request->input("id"))
                ->update(['is_default' => StatusEnum::true->status()]);

            if (!$updated) {
                throw new \Exception("Language not found.");
            }

            DB::commit();

            return back()->with('success', 'Language set as default successfully.');
        } catch (\Throwable $th) {
            DB::rollBack();

            return back()->with('error', 'Failed to set default language: ' . $th->getMessage());
        }
    }

    public function switch(Request $request)
    {
        $request->validate([
            'code' => 'required|string'
        ]);

        $language = Language::where('code', $request->input("code"))
                          ->where('status', StatusEnum::true->status())
                          ->first();

        if (!$language) {
            return back()->with('error', 'Language not found or not active');
        }

        session([
            'locale' => $language->lang_code,
            'country_code' => $language->code,
        ]);

        // Update application locale
        app()->setLocale($language->lang_code);

        return back()->with('success', 'Language switched successfully');
    }

    public function translation(Request $request)
    {
        $request->validate([
            'id' => 'required|exists:languages,id'
        ]);

        $language = Language::findOrFail($request->input('id'));
        
        // Get existing translations
        $filePath = resource_path("lang/{$language->lang_code}/messages.php");
        $translations = File::exists($filePath) ? require $filePath : [];

        return inertia('LanguageTranslation', [
            'language' => $language,
            'translations' => $translations
        ]);
    }

    public function translationAdd(Request $request)
    {
        $request->validate([
            'translations' => 'required|array',
            'translations.*.key' => 'required|string',
            'translations.*.value' => 'required|string',
        ]);

        $locale = session('locale', config('app.locale'));
        $filePath = resource_path("lang/{$locale}/messages.php");

        $translationsFile = File::exists($filePath) ? require $filePath : [];

        foreach ($request->translations as $t) {
            if (!array_key_exists($t['key'], $translationsFile)) {
                $translationsFile[$t['key']] = $t['value'];
            }
        }

        $export = "<?php\n\nreturn " . var_export($translationsFile, true) . ";\n";
        File::put($filePath, $export);

        return back();

    }

    /**
     * Create comprehensive language file with base English translations
     * 
     * @param Language $language
     * @param string $filePath
     * @return void
     */
    private function createLanguageFileWithTranslations($language, $filePath)
    {
        // Get English translations as base
        $englishPath = resource_path("lang/en/messages.php");
        $baseTranslations = [];
        
        if (File::exists($englishPath)) {
            $baseTranslations = require $englishPath;
        }

        // If no English file exists, create basic translations
        if (empty($baseTranslations)) {
            $baseTranslations = [
                'welcome' => 'Welcome',
                'hello' => 'Hello',
                'dashboard' => 'Dashboard',
                'settings' => 'Settings',
                'profile' => 'Profile',
                'logout' => 'Logout',
                'login' => 'Login',
                'register' => 'Register',
                'save' => 'Save',
                'cancel' => 'Cancel',
                'delete' => 'Delete',
                'edit' => 'Edit',
                'create' => 'Create',
                'update' => 'Update',
                'search' => 'Search',
                'filter' => 'Filter',
                'all' => 'All',
                'active' => 'Active',
                'inactive' => 'Inactive',
                'status' => 'Status',
                'actions' => 'Actions',
                'name' => 'Name',
                'email' => 'Email',
                'password' => 'Password',
                'username' => 'Username',
                'phone' => 'Phone',
                'address' => 'Address',
                'country' => 'Country',
                'submit' => 'Submit',
                'close' => 'Close',
                'loading' => 'Loading...',
                'no_data' => 'No data available',
                'language_saved' => 'Language saved',
                'language_deleted' => 'Language deleted',
                'error' => 'Error',
                'success' => 'Success',
            ];
        }

        // For new languages (not English), keep English values as placeholders
        // Software buyers can translate these manually or use auto-translate feature
        $translations = $baseTranslations;

        // Add meta information
        $content = "<?php\n\n";
        $content .= "// Language: {$language->name}\n";
        $content .= "// Code: {$language->lang_code}\n";
        $content .= "// Direction: " . ($language->ltr == '1' ? 'LTR' : 'RTL') . "\n";
        $content .= "// Created: " . now()->format('Y-m-d H:i:s') . "\n\n";
        $content .= "return " . var_export($translations, true) . ";\n";

        File::put($filePath, $content);
    }

    /**
     * Auto-translate language file using Google Translate or similar service
     * 
     * @param Request $request
     * @return RedirectResponse
     */
    public function autoTranslate(Request $request): RedirectResponse
    {
        $request->validate([
            'id' => 'required|exists:languages,id',
            'lang_code' => 'required|string'
        ]);

        try {
            $language = Language::findOrFail($request->input('id'));
            $targetLangCode = $request->input('lang_code');

            // Get English translations as source
            $englishPath = resource_path("lang/en/messages.php");
            if (!File::exists($englishPath)) {
                return back()->with('error', 'English translation file not found. Please create English translations first.');
            }

            $sourceTranslations = require $englishPath;
            
            // Create target language directory if it doesn't exist
            $targetLangPath = resource_path("lang/{$targetLangCode}");
            if (!File::exists($targetLangPath)) {
                File::makeDirectory($targetLangPath, 0755, true);
            }

            $targetFilePath = $targetLangPath . "/messages.php";
            
            // For now, create a placeholder auto-translation
            // In a real implementation, you would integrate with Google Translate API or similar
            $translatedContent = $this->createAutoTranslatedContent($sourceTranslations, $language, 'en', $targetLangCode);
            
            File::put($targetFilePath, $translatedContent);

            return back()->with('success', "Auto-translation completed for {$language->name}. Please review and edit translations as needed.");

        } catch (\Exception $e) {
            return back()->with('error', 'Auto-translation failed: ' . $e->getMessage());
        }
    }

    /**
     * Create auto-translated content (placeholder implementation)
     * In production, this would integrate with Google Translate API
     */
    private function createAutoTranslatedContent($sourceTranslations, $language, $sourceLang, $targetLang)
    {
        // This is a placeholder implementation
        // In production, you would integrate with Google Translate API or similar service
        
        $translatedTexts = [];
        
        foreach ($sourceTranslations as $key => $value) {
            // For demonstration, we'll add a prefix to show it's auto-translated
            // In production, this would be actual translation via API
            if ($targetLang !== 'en') {
                $translatedTexts[$key] = "[AUTO] " . $value;
            } else {
                $translatedTexts[$key] = $value;
            }
        }

        // Add meta information
        $content = "<?php\n\n";
        $content .= "// Language: {$language->name}\n";
        $content .= "// Code: {$targetLang}\n";
        $content .= "// Direction: " . ($language->ltr == '1' ? 'LTR' : 'RTL') . "\n";
        $content .= "// Auto-translated: " . now()->format('Y-m-d H:i:s') . "\n";
        $content .= "// NOTE: This is auto-translated content. Please review and edit as needed.\n\n";
        $content .= "return " . var_export($translatedTexts, true) . ";\n";

        return $content;
    }
}
