<?php

namespace Daylight\Core\Livewire\Store\Products;

use Daylight\Core\Models\Variant;
use Illuminate\Support\Collection;
use Livewire\Component;

class SkuInput extends Component
{
    public ?string $sku;

    public array $selectedVariant = [];

    public bool $showAutocomplete = false;

    public array|Collection $results = [];

    public function search(string $query)
    {
        $variants = (daylightModel('variant'))::query()
            ->where('sku', 'like', "%$query%")
            ->where('purchasable', 1)
            ->whereNull('product_id')
            ->with('media')
            ->limit(10)
            ->get();

        $exactVariant = (daylightModel('variant'))::query()
            ->where('sku', $query)
            ->whereNull('product_id')
            ->with('media')
            ->first();

        if ($exactVariant && ! $exactVariant->isPurchasable()) {
            $this->addError('sku', __('The selected SKU is not purchasable.'));

            return [
                'exactMatch' => null,
                'variants' => collect(),
            ];
        }

        return [
            'exactMatch' => $exactVariant
                ? [
                    'id' => $exactVariant->id,
                    'sku' => $exactVariant->sku,
                    'name' => $exactVariant->name,
                    'description' => $exactVariant->description,
                    'image' => $exactVariant->media->first()?->getUrl('thumbnail'),
                ]
                : null,
            'variants' => $variants->map(function (Variant $variant) {
                return [
                    'id' => $variant->id,
                    'sku' => $variant->sku,
                    'name' => $variant->name,
                    'description' => $variant->description,
                    'image' => $variant->media->first()?->getUrl('thumbnail'),
                ];
            }),
        ];
    }

    public function updatedSku($value)
    {
        $this->resetErrorBag('sku');

        if (strlen($this->sku) <= 2) {
            $this->results = collect();
            $this->showAutocomplete = false;

            return;
        }

        $results = $this->search($value);

        $this->results = collect($results['variants']);

        if ($results['exactMatch']) {
            $this->selectVariant($results['exactMatch']['sku']);

            return;
        }

        $this->showAutocomplete = true;
    }

    public function selectVariant($sku)
    {
        $this->selectedVariant = $this->results->firstWhere('sku', $sku);

        $this->dispatch('variant-selected', [
            'variant' => $this->selectedVariant,
        ]);

        $this->sku = $sku;
        $this->showAutocomplete = false;
    }

    public function mount()
    {
        if ($this->sku) {
            $variant = (daylightModel('variant'))::query()->where('sku', $this->sku)->first();

            if ($variant) {
                $this->selectedVariant = [
                    'id' => $variant->id,
                    'sku' => $variant->sku,
                    'name' => $variant->name,
                    'image' => $variant->media->first()?->getUrl('thumbnail'),
                ];
            }
        }
    }

    public function render()
    {
        return view('daylight::livewire.store.products.sku-input');
    }
}
