<?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\Entity\DeliveryAddressEntity;
use KupShop\UserAddressesBundle\Util\UserAddressesUtil;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\UX\LiveComponent\Attribute\AsLiveComponent;
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/UserAddressSelect/UserAddressSelect.1.html.twig')]
#[Component(1, [new Version(1)])]
#[Entrypoint('base')]
class UserAddressSelect extends BaseComponent
{
    use DefaultActionTrait;
    use ComponentToolsTrait;

    /** @var DeliveryAddressEntity[] */
    private array $addresses = [];
    #[LiveProp(writable: true)]
    public ?int $selectedId = null;
    #[LiveProp]
    public ?bool $allowAddNew = false;

    public function __construct(
        private readonly UserAddressesUtil $userAddressesUtil,
        private readonly \Cart $cart,
        private readonly SessionInterface $session,
    ) {
    }

    public function getAddresses(bool $force = false): array
    {
        if ($this->addresses && !$force) {
            return $this->addresses;
        }

        $this->addresses = $this->userAddressesUtil->getDeliveryAddresses();

        if ($this->selectedId === null) {
            if (count($this->addresses) == 1) {
                $this->selectedId = $this->addresses[0]->getId();
            } else {
                $this->selectedId = 0;
            }

            $this->emit('selectAddress', ['id' => $this->selectedId]);
        }

        return $this->addresses;
    }

    #[LiveListener('reloadAddresses')]
    public function reloadAddresses(): void
    {
        $this->getAddresses(true);
    }
}
