<?php

namespace App\Livewire\Admin\Pages;

use Livewire\Component;
use App\Models\Admin\Page;
use Illuminate\Support\Str;
use Livewire\Attributes\On;
use App\Models\Admin\Language;
use App\Models\Admin\PageImage;
use Livewire\Attributes\Validate;

class Edit extends Component
{
    public $selectedLanguage;
    public $defaultLanguage;
    public $translations = [];

    public $selectedPage;
    public $selectedPageName;

    #[Validate('required|min:3|max:255|string')]
    public $title;

    #[Validate('required|min:3|max:255|string|unique:pages,slug')]
    public $slug;

    public $description;
    public $content;
    public $alternative_content;

    public $meta_title;
    public $meta_description;
    public $meta_keywords;

    public $status;
    public $display_in_navigation;

    public $query;
    public $pages = [];
    public $highlightIndex = 0;

    public Page $page;

    public $inputs = [];

    public function mount(Page $page)
    {
        $this->page = $page;

        if($page->parent_id){
            $this->selectedPage = $page->parent->id;
            $this->selectedPageName = $page->parent->title;
        }
        $this->defaultLanguage = Language::where('default', 1)->first()->short;
        $this->selectedLanguage = $this->defaultLanguage;

        $this->translations = array_fill_keys(Language::where('status', 1)->orderByDesc('default')->pluck('short')->toArray(), '');

        foreach ($this->translations as $locale => &$title) {
            $this->translations[$locale] = [
                'title' => $this->page->getTranslation('title', $locale, false),
                'slug' => $this->page->getTranslation('slug', $locale, false),
                'description' => $this->page->getTranslation('description', $locale, false),
                'content' => $this->page->getTranslation('content', $locale, false),
                'alternative_content' => $this->page->getTranslation('alternative_content', $locale, false),
                'meta_title' => $this->page->getTranslation('meta_title', $locale, false),
                'meta_description' => $this->page->getTranslation('meta_description', $locale, false),
                'meta_keywords' => $this->page->getTranslation('meta_keywords', $locale, false),
            ];
        }

        $this->inputs = $page->images()->orderBy('ordernum')->get()->map(function ($image) {
            return [
                'id' => $image->id,
                'filePath' => $image->file_path,
                'fileName' => $image->file_name,
                'title' => $image->title,
            ];
        })->toArray();

        $this->title = $this->page->getTranslation('title', $this->selectedLanguage, false) ?? '';
        $this->slug = $this->page->getTranslation('slug', $this->selectedLanguage, false) ?? '';
        $this->description = $this->page->getTranslation('description', $this->selectedLanguage, false) ?? '';
        $this->content = $this->page->getTranslation('content', $this->selectedLanguage, false) ?? '';
        $this->alternative_content = $this->page->getTranslation('alternative_content', $this->selectedLanguage, false) ?? '';
        $this->meta_title = $this->page->getTranslation('meta_title', $this->selectedLanguage, false) ?? '';
        $this->meta_description = $this->page->getTranslation('meta_description', $this->selectedLanguage, false) ?? '';
        $this->meta_keywords = $this->page->getTranslation('meta_keywords', $this->selectedLanguage, false) ?? '';

        $this->status = $this->page->status;
        $this->display_in_navigation = $this->page->display_in_navigation;

        $this->dispatch('languageChanged', content: $this->content, alternative_content: $this->alternative_content);
    }

    public function changeLanguage($language)
    {
        $this->selectedLanguage = $language;

        $this->title = $this->translations[$language]['title'];
        $this->slug = $this->translations[$language]['slug'];
        $this->description = $this->translations[$language]['description'];
        $this->content = $this->translations[$language]['content'];
        $this->alternative_content = $this->translations[$language]['alternative_content'];
        $this->meta_title = $this->translations[$language]['meta_title'];
        $this->meta_description = $this->translations[$language]['meta_description'];
        $this->meta_keywords = $this->translations[$language]['meta_keywords'];

        $this->dispatch('languageChanged', content: $this->content, alternative_content: $this->alternative_content);
    }

    #[On('addInput')]
    public function addInput($filePath = null, $fileName = null)
    {
        $this->inputs[] = ['filePath' => $filePath, 'fileName' => $fileName, 'id' => null];
    }

    public function removeInput($index)
    {
        unset($this->inputs[$index]);
        $this->inputs = array_values($this->inputs);
    }

    public function updatedTitle($value)
    {
        $this->slug = Str::slug($value);

        $this->translations[$this->selectedLanguage]['title'] = $value;
        $this->translations[$this->selectedLanguage]['slug'] = $this->slug;
    }

    public function updatedSlug($value)
    {
        $this->translations[$this->selectedLanguage]['slug'] = $value;
    }

    public function updatedDescription($value)
    {
        $this->translations[$this->selectedLanguage]['description'] = $value;
    }

    public function updatedContent($value)
    {
        $this->translations[$this->selectedLanguage]['content'] = $value;
    }

    public function updatedAlternativeContent($value)
    {
        $this->translations[$this->selectedLanguage]['alternative_content'] = $value;
    }

    public function updatedMetaTitle($value)
    {
        $this->translations[$this->selectedLanguage]['meta_title'] = $value;
    }

    public function updatedMetaDescription($value)
    {
        $this->translations[$this->selectedLanguage]['meta_description'] = $value;
    }

    public function updatedMetaKeywords($value)
    {
        $this->translations[$this->selectedLanguage]['meta_keywords'] = $value;
    }

    public function updatedQuery()
    {
        $this->pages = Page::where('title', 'like', '%' . $this->query . '%')
            ->where('id', '!=', $this->page->id)
            ->get();
        $this->highlightIndex = 0;
    }

    public function resetSearch()
    {
        $this->query = '';
        $this->highlightIndex = 0;
        $this->pages = [];
    }

    public function incrementHighlight()
    {
        if ($this->highlightIndex === count($this->pages) - 1) {
            $this->highlightIndex = 0;
            return;
        }
        $this->highlightIndex++;
        $this->dispatch('highlight-updated', id: $this->highlightIndex);
    }

    public function decrementHighlight()
    {
        if ($this->highlightIndex === 0) {
            $this->highlightIndex = count($this->pages) - 1;
            return;
        }
        $this->highlightIndex--;
        $this->dispatch('highlight-updated', id: $this->highlightIndex);
    }

    public function selectPage($id = null)
    {
        $page = $this->pages[$id ? $id : $this->highlightIndex] ?? null;

        if ($page) {
            $this->selectedPage = $page->id;
            $this->selectedPageName = $page->title;
            $this->resetSearch();
        }
    }

    public function updateOrder($orderedIds)
    {
        foreach ($orderedIds as $index => $id) {
            PageImage::where('id', $id['value'])->update(['ordernum' => $id['order']]);
        }

        $this->inputs = $this->page->images()->orderBy('ordernum')->get()->map(function ($image) {
            return [
                'id' => $image->id,
                'filePath' => str_replace(config('app.url'),'',$image->file_path),
                'fileName' => $image->file_name,
                'title' => $image->title,
            ];
        })->toArray();

        $this->dispatch('showAlert', [
            'title' => 'Başarılı!', 'text' => 'Resim sıralaması başarıyla güncellendi.', 'icon' => 'success'
        ]);

    }

    public function save()
    {
        $this->validate();

        foreach ($this->translations as $language => $translation) {
            $this->page->setTranslation('title', $language, $translation['title']);
            $this->page->setTranslation('slug', $language, $translation['slug']);
            $this->page->setTranslation('description', $language, $translation['description']);
            $this->page->setTranslation('content', $language, $translation['content']);
            $this->page->setTranslation('alternative_content', $language, $translation['alternative_content']);
            $this->page->setTranslation('meta_title', $language, $translation['meta_title']);
            $this->page->setTranslation('meta_description', $language, $translation['meta_description']);
            $this->page->setTranslation('meta_keywords', $language, $translation['meta_keywords']);
        }

        $this->page->parent_id = $this->selectedPage;

        $this->page->status = ($this->status == 1 ? 1 : 0);
        $this->page->display_in_navigation = ($this->display_in_navigation == 1 ? 1 : 0);

        $this->page->save();

        $this->page->images()->delete();

        foreach ($this->inputs as $input) {
            $this->page->images()->create([
                'file_name' => $input['fileName'],
                'file_path' => str_replace(config('app.url'),'',$input['filePath']),
                'title' => $input['title'] ?? ''
            ]);
        }

        activity()->performedOn($this->page)->causedBy(auth()->id())->log('Sayfa güncellendi');

        $this->dispatch('showAlert', [
            'title' => 'Başarılı!', 'text' => 'Sayfa başarıyla güncellendi.', 'icon' => 'success'
        ]);
    }

    public function render()
    {
        return view('livewire.admin.pages.edit');
    }
}