<?php

namespace App\Livewire\Admin\Products;

use Livewire\Component;
use Illuminate\Support\Str;
use Livewire\Attributes\On;
use App\Models\Admin\Product;
use Livewire\WithFileUploads;
use App\Models\Admin\Language;
use App\Models\Admin\Taxonomy;
use App\Enums\ProductCategories;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Validate;

class Create extends Component
{
    use WithFileUploads;

    public $selectedLanguage;
    public $defaultLanguage;

    public $translations = [];

    public $technical_features;
    public $pressure_temperature_ranges;
    public $material_specs;
    public $figure_options;
    public $dimensions;

    public $title;
    public $slug;

    #[Validate('required', message: 'Dikkan Figure is required!')]
    public $dikkan_figure;

    public $impa_code;
    public $icons_id;

    public $image_path;
    public $td_image_path;
    public $datasheet_path;
    public $glb_file_path;

    public $youtube_video_id;

    public $selectedTaxonomies = [];

    public $variantInputs = [];

    public $inputs = [];

    public function mount()
    {
        $this->defaultLanguage = Language::where('default', 1)->first()->short;
        $this->selectedLanguage = $this->defaultLanguage;

        $this->translations = Language::where('status', 1)
            ->orderByDesc('default')
            ->pluck('short')
            ->mapWithKeys(function ($short) {
                return [$short => ['title' => '', 'slug' => '', 'technical_features' => '', 'pressure_temperature_ranges' => '', 'material_specs' => '', 'figure_options' => '', 'dimensions' => '']];
            })
            ->toArray();

        $this->addVariantInput();
    }

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

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

    public function addVariantInput()
    {
        $inputSet = [];

        foreach ($this->variants as $variant) {
            $inputSet[$variant->handle] = '';
        }

        $this->variantInputs[] = $inputSet;
    }

    public function removeVariantInput($index)
    {
        if (count($this->variantInputs) > 1) {
            unset($this->variantInputs[$index]);
            $this->variantInputs = array_values($this->variantInputs);
        }
    }

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

        $this->title = $this->translations[$language]['title'];
        $this->slug = $this->translations[$language]['slug'] ?? '';
        $this->technical_features = $this->translations[$language]['technical_features'];
        $this->pressure_temperature_ranges = $this->translations[$language]['pressure_temperature_ranges'];
        $this->material_specs = $this->translations[$language]['material_specs'];
        $this->figure_options = $this->translations[$language]['figure_options'];
        $this->dimensions = $this->translations[$language]['dimensions'];

        $this->dispatch('languageChanged', technical_features: $this->technical_features, pressure_temperature_ranges: $this->pressure_temperature_ranges, material_specs: $this->material_specs, figure_options: $this->figure_options, dimensions: $this->dimensions);
    }

    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 updatedTechnicalFeatures($value)
    {
        $this->translations[$this->selectedLanguage]['technical_features'] = $value;
    }

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

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

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

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

    public function renderCategoryOptions($category, $depth = 0)
    {
        $output = '';

        if ($category->children->isNotEmpty()) {
            if ($depth > 0) {
                $output .= '<optgroup label="' . str_repeat('--', $depth) . ' ' . $category->name . '">';
            }

            foreach ($category->children as $child) {
                $output .= $this->renderCategoryOptions($child, $depth + 1);
            }

            if ($depth > 0) {
                $output .= '</optgroup>';
            }
        } else {
            $output .= '<option value="' . $category->id . '">' . str_repeat('--', $depth) . ' ' . $category->name . '</option>';
        }

        return $output;
    }

    #[Computed()]
    public function taxonomies()
    {
        return Taxonomy::with('children')->whereParentId(config('app.taxonomy.products'))->orderBy('ordernum')->get();
    }

    #[Computed()]
    public function variants()
    {
        return Taxonomy::with('children')->whereParentId(config('app.taxonomy.variants'))->orderBy('ordernum')->get();
    }

    #[Computed()]
    public function icons()
    {
        return Taxonomy::with('children')->whereParentId(config('app.taxonomy.icons'))->orderBy('ordernum')->get();
    }

    private function getMainCategoryShortName()
    {
        if (!empty($this->selectedTaxonomies)) {
            foreach ($this->selectedTaxonomies as $taxonomyId) {
                if ($taxonomyId) {
                    $taxonomy = Taxonomy::find($taxonomyId);
                    if ($taxonomy) {
                        $mainCategory = $taxonomy->parent;
                        if ($mainCategory) {
                            switch ($mainCategory->id) {
                                case ProductCategories::MARINE->value:
                                    return 'mrn';
                                case ProductCategories::WATERWORKS->value:
                                    return 'wtr';
                                case ProductCategories::MARITIME->value:
                                    return 'mrt';
                                case ProductCategories::REMOTE->value:
                                    return 'rmt';
                            }
                        }
                    }
                }
            }
        }

        return 'default';
    }

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

        $mainCategoryShortName = $this->getMainCategoryShortName();

        if($mainCategoryShortName == 'default') {
            $this->dispatch('showAlert', [
                'title' => 'Başarısız!', 'text' => 'Lütfen ana kategori seçimini yapın.', 'icon' => 'error'
            ]);
            return;
        }

        $product = new Product();

        foreach ($this->translations as $language => $translation) {
            $product->setTranslation('title', $language, $translation['title']);
            $product->setTranslation('slug', $language, $translation['slug']);
            $product->setTranslation('technical_features', $language, $translation['technical_features']);
            $product->setTranslation('pressure_temperature_ranges', $language, $translation['pressure_temperature_ranges']);
            $product->setTranslation('material_specs', $language, $translation['material_specs']);
            $product->setTranslation('figure_options', $language, $translation['figure_options']);
            $product->setTranslation('dimensions', $language, $translation['dimensions']);
        }

        $product->dikkan_figure = $this->dikkan_figure;
        $product->impa_code = $this->impa_code;
        $product->youtube_video_id = $this->youtube_video_id;

        if (is_array($this->icons_id) && !empty($this->icons_id)) {
            $product->icons = implode(',', $this->icons_id);
        } else {
            $product->icons = null;
        }

        if ($this->image_path) {
            $imagePath = get_relative_image_path($this->image_path);
            $newImageName = $product->dikkan_figure . '.' . pathinfo($imagePath, PATHINFO_EXTENSION);
            $newImagePath = dirname($imagePath) . '/' . $newImageName;

            if (file_exists(public_path($imagePath))) {
            rename(public_path($imagePath), public_path($newImagePath));
            $product->image_path = $newImagePath;
            }
        }

        if($this->td_image_path) {
            $tdImagePath = get_relative_image_path($this->td_image_path);
            $newTdImageName = $product->dikkan_figure . '_td.' . pathinfo($tdImagePath, PATHINFO_EXTENSION);
            $newTdImagePath = dirname($tdImagePath) . '/' . $newTdImageName;

            if (file_exists(public_path($tdImagePath))) {
            rename(public_path($tdImagePath), public_path($newTdImagePath));
            $product->td_image_path = $newTdImagePath;
            }
        }

        if ($this->datasheet_path) {
            $datasheetPath = get_relative_image_path($this->datasheet_path);
            $newDatasheetName = $product->dikkan_figure . "_ds_{$mainCategoryShortName}." . pathinfo($datasheetPath, PATHINFO_EXTENSION);
            $newDatasheetPath = dirname($datasheetPath) . '/' . $newDatasheetName;

            if (file_exists(public_path($datasheetPath))) {
                rename(public_path($datasheetPath), public_path($newDatasheetPath));
                $product->datasheet_path = $newDatasheetPath;
            }
        }

        if ($this->glb_file_path) {
            $glbFileName = time() . $product->dikkan_figure . '_glb_' . $this->glb_file_path->getClientOriginalName();
            $this->glb_file_path->storeAs('glb_file', $glbFileName, 'upload');
            $product->glb_file_path = 'upload/glb_file/' . $glbFileName;
        }

        $product->save();

        foreach ($this->inputs as $input) {
            $product->images()->create([
                'file_name' => $input['fileName'],
                'file_path' => $input['filePath'],
                'title' => $input['title'] ?? ''
            ]);
        }

        $selectedTaxonomies = [];

        foreach ($this->selectedTaxonomies as $categoryId) {
            if ($categoryId)
                $selectedTaxonomies[] = [
                    'taxonomy_id' => $categoryId,
                ];
        }

        if (!empty($selectedTaxonomies))
            $product->taxonomies()->attach($selectedTaxonomies);

        foreach ($this->variantInputs as $variantInput) {
            foreach ($variantInput as $key => $value) {
                if ($value) {
                    $taxonomyId = Taxonomy::where('handle', $key)->value('id');

                    if ($taxonomyId) {
                        $product->taxonomies()->attach($taxonomyId, ['value' => $value]);
                    }
                }
            }
        }

        activity()->performedOn($product)->causedBy(auth()->id())->log('Ürün oluşturuldu');

        $this->dispatch('showAlert', [
            'title' => 'Başarılı!', 'text' => 'Ürün oluşturuldu.', 'icon' => 'success'
        ]);

        $this->reset();
    }

    public function saveAndRedirect()
    {
        $this->save();
        return redirect()->route('admin.products.index');
    }

    public function render()
    {
        return view('livewire.admin.products.create');
    }
}
