using UnityEngine;
using UnityEngine.UIElements;

namespace LiveOpsExamples
{
  public class OfferModalPanel : MonoBehaviour
  {
    [SerializeField] private PanelRenderer panelRenderer;
    [SerializeField] private CozyCollectorController controller;

    private VisualElement root;
    private Label titleLabel;
    private Label nameLabel;
    private Label priceLabel;
    private Button buyButton;
    private Button declineButton;
    private Button closeButton;

    private void OnEnable()
    {
      panelRenderer.RegisterUIReloadCallback(OnUIReload);
      controller.ModalChanged += ApplyVisibility;
      controller.OfferChanged += Refresh;
    }

    private void OnDisable()
    {
      panelRenderer.UnregisterUIReloadCallback(OnUIReload);
      controller.ModalChanged -= ApplyVisibility;
      controller.OfferChanged -= Refresh;
    }

    private void OnUIReload(PanelRenderer renderer, VisualElement root)
    {
      this.root = root.Q<VisualElement>("offer-modal");
      titleLabel = this.root.Q<Label>("offer-title");
      nameLabel = this.root.Q<Label>("offer-name");
      priceLabel = this.root.Q<Label>("offer-price");
      buyButton = this.root.Q<Button>("offer-buy-button");
      declineButton = this.root.Q<Button>("offer-decline-button");
      closeButton = this.root.Q<Button>("offer-close-button");

      buyButton.clicked -= HandleBuyClicked;
      buyButton.clicked += HandleBuyClicked;
      declineButton.clicked -= HandleDeclineClicked;
      declineButton.clicked += HandleDeclineClicked;
      closeButton.clicked -= HandleCloseClicked;
      closeButton.clicked += HandleCloseClicked;

      ApplyVisibility();
      Refresh();
    }

    private void ApplyVisibility()
    {
      root.style.display = controller.ActiveModal == CozyModal.Offer ? DisplayStyle.Flex : DisplayStyle.None;
    }

    private void Refresh()
    {
      var offerInfo = controller.CurrentOffer;
      if (offerInfo == null)
      {
        titleLabel.text = "Offer";
        nameLabel.text = "—";
        priceLabel.text = string.Empty;
        buyButton.SetEnabled(false);
        return;
      }

      titleLabel.text = string.IsNullOrEmpty(offerInfo.StoreName) ? offerInfo.StoreSlug : offerInfo.StoreName;

      var offer = offerInfo.Offers != null && offerInfo.Offers.Count > 0 ? offerInfo.Offers[0] : null;
      if (offer == null)
      {
        nameLabel.text = "—";
        priceLabel.text = string.Empty;
        buyButton.SetEnabled(false);
        return;
      }

      nameLabel.text = string.IsNullOrEmpty(offer.Name) ? offer.OfferId : offer.Name;
      priceLabel.text = ShopModalPanel.PriceLabel(offer.Price, offer.Currency);
      buyButton.SetEnabled(true);
    }

    private void HandleBuyClicked()
    {
      controller.BuyScenarioOffer();
    }

    private void HandleDeclineClicked()
    {
      controller.DeclineScenarioOffer();
    }

    private void HandleCloseClicked()
    {
      controller.CloseModal();
    }
  }
}
