<?php

declare(strict_types=1);

namespace KupShop\UserAddressesBundle\Twig\Components\Cart;

use KupShop\ComponentsBundle\Attributes\Component;
use KupShop\ComponentsBundle\Attributes\Entrypoint;
use KupShop\ComponentsBundle\Attributes\Version;
use KupShop\ComponentsBundle\Twig\BaseComponent;
use KupShop\UserAddressesBundle\Util\UserAddressesCartUtil;
use Symfony\UX\LiveComponent\Attribute\AsLiveComponent;
use Symfony\UX\LiveComponent\Attribute\LiveAction;
use Symfony\UX\LiveComponent\Attribute\LiveArg;
use Symfony\UX\LiveComponent\Attribute\LiveListener;
use Symfony\UX\LiveComponent\Attribute\LiveProp;
use Symfony\UX\LiveComponent\ComponentToolsTrait;
use Symfony\UX\LiveComponent\DefaultActionTrait;

#[AsLiveComponent(template: '@UserAddresses/components/Cart/HiddenAddressInput/HiddenAddressInput.1.html.twig')]
#[Component(1, [new Version(1, newCss: null)])]
#[Entrypoint('base')]
class HiddenAddressInput extends BaseComponent
{
    use DefaultActionTrait;
    use ComponentToolsTrait;

    #[LiveProp]
    public bool $updateCart = false;
    #[LiveProp]
    public ?string $inputName = null;
    #[LiveProp]
    public ?int $selectedId = null;

    public function __construct(
        private readonly UserAddressesCartUtil $userAddressCartUtil,
    ) {
    }

    #[LiveListener('selectAddress')]
    #[LiveAction]
    public function selectAddress(#[LiveArg] ?int $id): void
    {
        if (!$this->updateCart) {
            return;
        }

        $this->selectedId = $id;
        $this->userAddressCartUtil->saveAddressToCart($id);
    }
}
