<?php

namespace KupShop\ConvertorsBundle\Twig\Components\Convertor;

use KupShop\CatalogBundle\Entity\Variation;
use KupShop\ComponentsBundle\Attributes\Component;
use KupShop\ComponentsBundle\Attributes\Version;
use KupShop\ComponentsBundle\Twig\BaseComponent;
use KupShop\ComponentsBundle\Twig\DataProvider\ProductDataTrait;
use KupShop\ConvertorsBundle\Utils\ConvertorsUtil;
use KupShop\KupShopBundle\Config;
use KupShop\KupShopBundle\Util\StringUtil;
use Symfony\Contracts\Translation\TranslatorInterface;
use Symfony\UX\LiveComponent\Attribute\AsLiveComponent;
use Symfony\UX\LiveComponent\Attribute\LiveAction;
use Symfony\UX\LiveComponent\Attribute\LiveProp;
use Symfony\UX\LiveComponent\DefaultActionTrait;

#[AsLiveComponent(template: '@Convertors/components/Convertor/ConvertorTabs/ConvertorTabs.1.html.twig')]
#[Component(1, [
    new Version(1),
])]
class ConvertorTabs extends BaseComponent
{
    use DefaultActionTrait;
    use ProductDataTrait;

    #[LiveProp]
    public string $toggleText;

    #[LiveProp]
    public bool $isHidden = true;

    #[LiveProp]
    public int $id_convertor;

    #[LiveProp]
    public int $id_product;

    public bool $hideAvailability = false;

    public array $deliveryTimeIndexesNotSoldOut = [0];

    private ?array $sizes = null;
    private bool $byLabel = false;
    private array $deliveryVar = [];

    public function __construct(
        private readonly ConvertorsUtil $convertorsUtil, private readonly TranslatorInterface $translator,
    ) {
        $this->toggleText = $this->translator->trans('variation.show', [], 'products');
    }

    public function getSizeTable(): ?array
    {
        if (!$this->sizes) {
            $this->sizes = $this->convertorsUtil->getSizeTable([
                'id_product' => $this->id_product,
                'by_label' => $this->byLabel,
                'id_convertor' => $this->id_convertor,
            ]);
        }

        return $this->sizes;
    }

    /** @return Variation[] */
    public function getVariations(): array
    {
        $this->multiFetch()->fetchVariationsEntities();
        $this->multiFetch()->prefetchPriceTypes();

        return $this->product->variations;
    }

    public function getAllInStore()
    {
        foreach ($this->getVariations() as $variation) {
            if ($variation->isSoldOut()) {
                return false;
            }
        }

        return true;
    }

    public function getAllSoldout()
    {
        foreach ($this->getVariations() as $variation) {
            if (!$variation->isSoldOut()) {
                return false;
            }
        }

        return true;
    }

    public function getIsSoldOutShowTurnedOn($idVariation): bool
    {
        $variation = $this->getVariationById($idVariation);
        if (!in_array($variation->getDeliveryTime(), $this->deliveryTimeIndexesNotSoldOut) && \Settings::getDefault()['prod_show_not_in_store'] == 'N') {
            return false;
        } else {
            if ($variation->getFigure() != 'Y') {
                return false;
            }
        }

        return true;
    }

    public function getVariationEan($idVariation): ?int
    {
        return $this->getVariationById($idVariation)->getEan();
    }

    public function getVariationCode($idVariation): ?string
    {
        return $this->getVariationById($idVariation)->getCode();
    }

    public function isSoldOut($idVariation): bool
    {
        $variation = $this->getVariationById($idVariation);
        $soldOut = true;

        if (in_array($variation->getDeliveryTime(), $this->deliveryTimeIndexesNotSoldOut)) { // varianta je skladem
            $soldOut = false;
        } elseif (
            $this->getAllowSoldoutToCart() && (
                $this->getAllowSoldoutToCart()[$variation->getDeliveryTime()]
                || ($this->getAllowSoldoutToCart()[1] && $variation->getDeliveryTime() > 0)
            )
        ) {
            $soldOut = false;
        }

        return $soldOut;
    }

    private function getAllowSoldoutToCart()
    {
        return Config::get()['Products']['allowSoldoutToCart'] ?? null;
    }

    public function getWatchDogModule()
    {
        return findModule(\Modules::WATCHDOG);
    }

    public function setByLabel(bool $byLabel): void
    {
        $this->byLabel = $byLabel;
    }

    private function loadDeliveryVar(): void
    {
        if (!$this->hideAvailability && empty($this->deliveryVar)) {
            foreach ($this->getProductUnified()->getVariations() as $id => $variation) {
                if (!in_array($variation->getDeliveryTime(), $this->deliveryTimeIndexesNotSoldOut) && \Settings::getDefault()['prod_show_not_in_store'] == 'N') {
                    continue;
                }
                $this->deliveryVar[$variation->getId()]['deliveryTime'] = $variation->getDeliveryTime();
                $this->deliveryVar[$variation->getId()]['deliveryTimeText'] = $variation->getDeliveryTimeText();
                $this->deliveryVar[$variation->getId()]['inStore'] = $variation->getInStore();
            }
        }
    }

    public function formatString(string $value): string
    {
        return StringUtil::slugify($value);
    }

    #[LiveAction]
    public function toggleAction(): void
    {
        if ($this->isHidden) {
            $this->toggleText = $this->translator->trans('variation.hide', [], 'products');
            $this->isHidden = false;
        } else {
            $this->toggleText = $this->translator->trans('variation.show', [], 'products');
            $this->isHidden = true;
        }
    }
}
