<?php

declare(strict_types=1);

namespace KupShop\PreordersBundle\Twig\Components\Preorders;

use KupShop\ComponentsBundle\Attributes\Component;
use KupShop\ComponentsBundle\Attributes\Version;
use KupShop\ComponentsBundle\GTM\PostMount\GTMViewData;
use KupShop\ComponentsBundle\Twig\BaseComponent;
use KupShop\PreordersBundle\Dto\DateInfo;
use KupShop\PreordersBundle\Dto\PreorderOrDate;
use KupShop\PreordersBundle\Entity\Preorder;
use KupShop\PreordersBundle\GTM\PageViews\Preorders;
use KupShop\PreordersBundle\Service\PreorderUtil;
use Symfony\Contracts\Service\Attribute\Required;
use Symfony\UX\TwigComponent\Attribute\AsTwigComponent;

#[AsTwigComponent(template: '@Preorders/components/View/View.1.html.twig')]
#[Component(1, [
    new Version(1, newJs: null),
])]
class View extends BaseComponent
{
    use GTMViewData;

    #[Required]
    public Preorders $gtmClass;

    public DateInfo $dateInfo;

    /**
     * @return PreorderOrDate[]
     */
    public function getLinks(): iterable
    {
        if (PreorderUtil::useMultipleDates()) {
            foreach ($this->dateInfo->getValidPreorders() as $preorder) {
                yield new PreorderOrDate(
                    $preorder->id,
                    $preorder['name'],
                    '',
                    $this->findDateEnd($preorder)
                        ?? (new \DateTimeImmutable())->sub(new \DateInterval('P1D')),
                );
            }

            return;
        }

        foreach ($this->dateInfo->getValidDates() as $date) {
            yield new PreorderOrDate(
                $date['id'],
                $date['name'], $date['date_shipment'] ?? $date['description'] ?? '',
                \DateTimeImmutable::createFromFormat('Y-m-d', $date['date_end']),
            );
        }
    }

    private function findDateEnd(Preorder $preorder): ?\DateTimeInterface
    {
        $dateEnd = null;

        foreach ($preorder->getDates() as $date) {
            $current = \DateTimeImmutable::createFromFormat('Y-m-d', $date['date_end']);

            if ($current > $dateEnd) {
                $dateEnd = $current;
            }
        }

        return $dateEnd;
    }

    public function getActiveId(): int
    {
        return $this->dateInfo->getId();
    }

    public function getGTMPlaceholders(): array
    {
        return ['item_list_name' => 'preorders', 'item_list_id' => $this->dateInfo->getId()];
    }
}
