<?php

namespace App\Livewire\Products;

use Daylight\Core\Models\Product;
use Daylight\Core\Models\Translations\ProductTranslation;
use Daylight\Core\Models\Variant;
use Illuminate\Support\Collection;
use Illuminate\View\View;
use Livewire\Component;

class VariationSelector extends Component
{
    public ProductTranslation $product;

    public array $selectedOptionValues = [];

    public function getVariantProperty(): ?Variant
    {
        $variant = $this->getProductProperty()
            ->variants
            ->sortBy('order')
            ->first(function ($variant) {
                return ! $variant->optionValues->pluck('id')
                    ->diff(
                        collect($this->selectedOptionValues)->values()
                    )->count();
            });

        $this->dispatch('current-variant-changed', $variant);

        return $variant;
    }

    public function getOptionValuesProperty(): Collection
    {
        return $this->getProductProperty()->variants->pluck('optionValues')->flatten();
    }

    public function getOptionsProperty(): Collection
    {
        return $this->optionValues->sortBy('position')->unique('id')->groupBy('option_id')
            ->map(function ($values, $optionId) {
                return [
                    'option' => $values->first()->option,
                    'values' => $values,
                ];
            })->values();
    }

    public function getProductProperty(): Product
    {
        return $this->product?->product?->loadMissing([
            'media',
            'variants.media',
            'variants.optionValues' => function ($query) {
                $query->with('option', function ($query) {
                    $query->withWhereHas('translations', function ($query) {
                        $query->where('locale', app()->getLocale());
                    });
                });

                $query->withWhereHas('translations', function ($query) {
                    $query->where('locale', app()->getLocale());
                });
            },
        ]);
    }

    public function mount(): void
    {
        $this->selectedOptionValues = $this->options->sortBy('order')->mapWithKeys(function ($data) {
            return [$data['option']->id => $data['values']->first()->id];
        })->toArray();
    }

    public function render(): View
    {
        return view('livewire.products.variation-selector');
    }
}
