<?php

declare(strict_types=1);

namespace CpCreation\VitiCore\Bridge\Symfony\Bundle\Twig\Components\Cart;

use CpCreation\VitiCore\Bridge\Symfony\Bundle\Context\GroupContext;
use CpCreation\VitiCore\Cart\CartService;
use CpCreation\VitiCore\Cart\Repository\CartRepository;
use CpCreation\VitiCore\Product\Repository\ProductPriceCodeRepository;
use CpCreation\VitiCore\Product\Repository\ProductPriceGroupRepository;
use CpCreation\VitiCore\Shop\Repository\ShopConfigRepository;
use CpCreation\VitiCore\User\Model\User;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\HttpFoundation\RequestStack;
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\ComponentToolsTrait;
use Symfony\UX\LiveComponent\DefaultActionTrait;

#[AsLiveComponent('shop:PartnerCode', template: 'components/shop/PartnerCode.html.twig')]
final class PartnerCode extends AbstractController
{
    use ComponentToolsTrait;
    use DefaultActionTrait;

    #[LiveProp(writable: true)]
    public string $code = '';

    public ?string $currentCode = null;

    public ?string $errorMessage = null;

    public function __construct(
        private readonly RequestStack $requestStack,
        private readonly ProductPriceCodeRepository $productPriceCodeRepository,
        private readonly ProductPriceGroupRepository $productPriceGroupRepository,
        private readonly ShopConfigRepository $shopConfigRepository,
        private readonly CartService $cartService,
        private readonly CartRepository $cartRepository,
        private readonly TranslatorInterface $translator,
        private readonly Security $security,
    ) {
    }

    public function mount(): void
    {
        $this->refreshState();
    }

    #[LiveAction]
    public function apply(): ?Response
    {
        $this->errorMessage = null;

        $submittedCode = mb_strtoupper(trim($this->code));
        if ('' === $submittedCode) {
            $this->errorMessage = $this->translator->trans('shop.group_code_required');

            return null;
        }

        $priceCode = $this->productPriceCodeRepository->findOneCode($submittedCode);
        if (null === $priceCode || null === $priceCode->getGroup()) {
            $this->errorMessage = $this->translator->trans('shop.group_code_invalid');

            return null;
        }

        $session = $this->requestStack->getSession();
        $session->set('groupPrice', $priceCode->getGroup()->getId()->toString());
        $session->set('codePrice', $priceCode->getId()->toString());
        $session->set('partnerCode', $priceCode->getCode());
        $session->set('groupByDefault', false);

        GroupContext::$groupId = $priceCode->getGroup()->getId()->toString();
        GroupContext::$partnerCode = $priceCode->getCode();

        $this->syncCart();
        $this->code = '';
        $this->currentCode = $priceCode->getCode();

        return $this->redirectToCurrentPage();
    }

    #[LiveAction]
    public function reset(): Response
    {
        $this->errorMessage = null;

        $session = $this->requestStack->getSession();
        $session->remove('groupPrice');
        $session->remove('codePrice');
        $session->remove('partnerCode');
        $session->set('groupByDefault', true);

        GroupContext::$groupId = $this->resolveFallbackGroupId();
        GroupContext::$partnerCode = null;

        $this->syncCart();
        $this->code = '';
        $this->currentCode = null;

        return $this->redirectToCurrentPage();
    }

    public function isActive(): bool
    {
        return null !== $this->currentCode && '' !== $this->currentCode;
    }

    public function isEnabled(): bool
    {
        return $this->shopConfigRepository->findOne()?->isEnablePartnerCodeFront() ?? true;
    }

    private function syncCart(): void
    {
        $cart = $this->cartService->getCart();
        if (null === $cart) {
            return;
        }

        $this->cartService->hydrateCart($cart);
        $this->cartRepository->save($cart);
    }

    private function refreshState(): void
    {
        $partnerCode = $this->requestStack->getSession()?->get('partnerCode');
        $this->currentCode = \is_string($partnerCode) && '' !== $partnerCode
            ? $partnerCode
            : GroupContext::$partnerCode;
    }

    private function resolveFallbackGroupId(): ?string
    {
        $user = $this->security->getUser();
        if ($user instanceof User && null !== $user->getGroup()) {
            return $user->getGroup()->getId()->toString();
        }

        return $this->productPriceGroupRepository->getGroupByDefault()?->getId()?->toString();
    }

    private function redirectToCurrentPage(): Response
    {
        $request = $this->requestStack->getCurrentRequest();
        $url = $request?->headers->get('X-Live-Url')
            ?? $request?->headers->get('referer')
            ?? '/';

        return $this->redirect($url);
    }
}
