<?php

declare(strict_types=1);

namespace KupShop\ComponentsBundle\Twig\Components;

use KupShop\CatalogBundle\Entity\Section;
use KupShop\CatalogElasticBundle\View\SectionView;
use KupShop\ComponentsBundle\Attributes\Component;
use KupShop\ComponentsBundle\Attributes\Version;
use KupShop\ComponentsBundle\Interfaces\Microdata;
use KupShop\ComponentsBundle\Twig\BaseComponent;
use KupShop\ComponentsBundle\Twig\DataProvider\MicrodataProvider;
use KupShop\ComponentsBundle\Twig\DataProvider\ProductDataProvider;
use KupShop\ContentBundle\View\HomeView;
use KupShop\ContentBundle\View\ProductView;
use KupShop\KupShopBundle\Util\System\UrlFinder;
use KupShop\KupShopBundle\Views\View;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\UX\TwigComponent\Attribute\AsTwigComponent;

#[AsTwigComponent(template: '@Components/components/Breadcrumbs/Breadcrumbs.1.html.twig')]
#[Component(1, [
    new Version(1, newJs: null),
])]
class Breadcrumbs extends BaseComponent implements Microdata
{
    public array $path;
    public bool $hide_home = false;
    public bool $hide_last = false;

    public bool $remove_container = false;
    public string $separator_icon = 'caret-right';

    private ?View $view;
    protected array $breadcrumbsToRender;

    public function __construct(
        private readonly UrlFinder $urlFinder,
        private readonly ProductDataProvider $productDataProvider,
        RequestStack $requestStack,
    ) {
        $this->view = $requestStack->getCurrentRequest()?->attributes->get('view');
    }

    public function mount(?array $path = null): void
    {
        if (!isset($path)) {
            if (!$this->view) {
                $this->path = [];

                return;
            }

            $path = $this->view->getBreadcrumbsNew() ?? [];
        }

        $this->path = $path;
    }

    public function getBreadcrumbs(): array
    {
        if (!isset($this->breadcrumbsToRender)) {
            $this->breadcrumbsToRender = $this->path;
            if ($this->hide_home) {
                unset($this->breadcrumbsToRender[0]);
            }
            if ($this->hide_last) {
                array_pop($this->breadcrumbsToRender);
            }
        }

        return $this->breadcrumbsToRender;
    }

    public function getAction(): string
    {
        if ($this->view instanceof SectionView && ($this->view->getCategoryId() > 0 || $this->view->getProducerId()) || $this->view instanceof HomeView) {
            return 'store';
        } elseif ($this->view instanceof ProductView) {
            return 'load';
        }

        return 'no-action';
    }

    public function getProductSections(): array
    {
        assert($this->view instanceof ProductView);

        return array_merge(...array_map(
            fn (Section $section) => array_map(
                fn (Section $section) => (int) $section->getId(),
                $section->getParents(),
            ),
            $this->getProduct()->fetchSections(),
        ));
    }

    private function getProduct(): \Product
    {
        assert($this->view instanceof ProductView);

        $product = $this->productDataProvider->getProduct((int) $this->view->getProductId());
        $this->productDataProvider
            ->multiFetch()
            ->fetchSectionsDirectly(withProductsCount: false);

        return $product;
    }

    public function initMicrodata(): array
    {
        if (count($this->getBreadcrumbs()) <= 1) {
            return [];
        }

        $breadcrumbs = [];
        foreach ($this->getBreadcrumbs() as $index => $breadcrumb) {
            // Domů tam nechci :)
            if ($index === 0) {
                continue;
            }

            $breadcrumbs[] = [
                '@type' => 'ListItem',
                'position' => $index + 1,
                'item' => [
                    '@id' => $this->urlFinder->shopUrlAbsolute($breadcrumb['link'] ?? '/'),
                    'name' => $breadcrumb['text'],
                ],
            ];
        }

        return [MicrodataProvider::BREADCRUMBS => [
            '@context' => 'http://schema.org',
            '@type' => 'BreadcrumbList',
            'itemListElement' => [
                $breadcrumbs,
            ],
        ],
        ];
    }
}
