using System;
using System.Linq;
using _Combo;
using _Combo.Events;
using _Core;
using UnityEngine;
using UnityEngine.UI;

namespace Seayoo.ComboSDK.Windows.Store.View
{
    public class PayMethodView : MonoBehaviour
    {
        public Text productValueText;
        public Text productNameText;
        public Text selectedMethodsTitle;
        public Text weixinPayText;
        public Text alipayPayText;
        public Text sandboxText;
        public Text sandboxTipText;
        public Text payBtnText;
        public Toggle weixinToggle;
        public Toggle alipayToggle;
        public Toggle sandboxToggle;
        public ToggleGroup toggleGroup;
        public Button closeBtn;
        public Button payBtn;
        public GameObject weixinPanel;
        public GameObject alipayPanel;
        public GameObject sandboxPanel;
        public GameObject splitLineOne;
        public GameObject splitLineTwo;
        public Sprite toggleNormalSprite;
        public Sprite toggleSelectedSprite;
        private string[] methods;
        private Order order;
        private string method;
        private string orderToken;
        private PaymentMethods paymentMethod;
        void Awake()
        {
            EventSystem.Register(this);
        }

        void Start()
        {
            selectedMethodsTitle.text = I18n.T("payment_title");
            weixinPayText.text = I18n.T("weixin_pay_button");
            alipayPayText.text = I18n.T("alipay_button");
            sandboxText.text = I18n.T("sandbox_payment_button");
            sandboxTipText.text = I18n.T("sandbox_payment_text");
            payBtnText.text = I18n.T("immediate_payment_button");
            closeBtn.onClick.AddListener(OnClose);
            payBtn.onClick.AddListener(PayProduct);
            weixinToggle.onValueChanged.AddListener((isOn) => { if (isOn) SetMethod(PaymentMethods.WEIXIN_NATIVE); });
            alipayToggle.onValueChanged.AddListener((isOn) => { if (isOn) SetMethod(PaymentMethods.ALIPAY_QR_CODE); });
            sandboxToggle.onValueChanged.AddListener((isOn) => { if (isOn) SetMethod(PaymentMethods.SEAYOO_SANDBOX); });
            Init();
        }

        void OnDestroy()
        {
            EventSystem.UnRegister(this);
            closeBtn.onClick.RemoveListener(OnClose);
            payBtn.onClick.RemoveListener(PayProduct);
            weixinToggle.onValueChanged.RemoveListener((isOn) => { if (isOn) SetMethod(PaymentMethods.WEIXIN_NATIVE); });
            alipayToggle.onValueChanged.RemoveListener((isOn) => { if (isOn) SetMethod(PaymentMethods.ALIPAY_QR_CODE); });
            sandboxToggle.onValueChanged.RemoveListener((isOn) => { if (isOn) SetMethod(PaymentMethods.SEAYOO_SANDBOX); });
        }

        private void SetMethod(PaymentMethods method)
        {
            this.method = SeayooStoreManager.Instance.GetPaymentMethodName(method);
            paymentMethod = method;
        }

        public void OnClose()
        {
            ClosePayViewCommand.Invoke(new ClosePayViewCommand());
            PurchaseFailedEvent.Invoke(new PurchaseFailedEvent { error = new InternalError(I18n.T("user_cancelled_error"), new UserCancelled()) });
        }

        public void PayProduct()
        {
            SeayooStoreManager.Instance.RequestPayment(orderToken, method, onResp: (url, time) =>
            {
                GoToViewCommand.Invoke(new GoToViewCommand
                {
                    type = PayViewType.PAY_QR,
                    order = order,
                    productName = productNameText.text,
                    productValue = productValueText.text,
                    paymentMethod = paymentMethod,
                    orderToken = orderToken,
                    url = url,
                    timeExpire = time
                });
            });
        }

        private void Init()
        {
            if (methods == null || methods.Length == 0)
            {
                PurchaseFailedEvent.Invoke(new PurchaseFailedEvent { error = new InternalError(I18n.T("iap_payment_method_unavailable_error"), new StoreError(order, "seayoo_store")) });
                ClosePayViewCommand.Invoke(new ClosePayViewCommand());
            }
            else if (methods.Length == 1)
            {
                splitLineOne.SetActive(false);
                splitLineTwo.SetActive(false);
                SetPaymentMethodsActive();
            }
            else if (methods.Length == 2)
            {
                SetPaymentMethodsActive();
                if (methods.Contains("weixin_native"))
                {
                    splitLineOne.SetActive(true);
                    splitLineTwo.SetActive(false);
                }
                else if (methods.Contains("alipay_qr_code") && methods.Contains("seayoo_sandbox"))
                {
                    splitLineOne.SetActive(false);
                    splitLineTwo.SetActive(true);
                }
            }
            else if (methods.Length == 3)
            {
                SetPaymentMethodsActive();
                splitLineOne.SetActive(true);
                splitLineTwo.SetActive(true);
            }
            RegisterToggleListeners();
            SetDefaultToggle();
        }

        private void RegisterToggleListeners()
        {
            foreach (var toggle in toggleGroup.GetComponentsInChildren<Toggle>())
            {
                toggle.onValueChanged.AddListener((isOn) =>
                {
                    UpdateToggleBackground(toggle, isOn);
                });
            }
        }

        private void UpdateToggleBackground(Toggle toggle, bool isOn)
        {
            Image backgroundImage = toggle.targetGraphic as Image;

            if (backgroundImage != null)
            {
                backgroundImage.sprite = isOn ? toggleSelectedSprite : toggleNormalSprite;
            }
        }

        private void SetDefaultToggle()
        {
            var toggles = toggleGroup.GetComponentsInChildren<Toggle>();
            foreach (Toggle toggle in toggles)
            {
                toggle.isOn = false;
            }
            if (toggles.Length > 0)
            {
                toggles[0].isOn = true;
                UpdateToggleBackground(toggles[0], true);
            }
        }

        private void SetPaymentMethodsActive()
        {
            weixinPanel.SetActive(methods.Contains("weixin_native"));
            alipayPanel.SetActive(methods.Contains("alipay_qr_code"));
            sandboxPanel.SetActive(methods.Contains("seayoo_sandbox"));
        }

        [EventSystem.BindEvent]
        public void ShowTextInfo(ProductInfoCommand action)
        {
            orderToken = action.orderToken;
            methods = action.seayooPurchaseOptions.paymentMethods;
            order = action.order;
            if (order.quantity > 1)
            {
                productNameText.text = action.order.productName + $" <size=18><color=#ADB5C4>×{order.quantity}</color></size>";
            }
            else
            {
                productNameText.text = action.order.productName;
            }
            double yuanAmount = order.amount / 100.0;

            if (yuanAmount % 1 == 0)
            {
                productValueText.text = "<size=28>￥</size>" + Convert.ToInt32(yuanAmount).ToString("N0");
            }
            else
            {
                productValueText.text = "<size=28>￥</size>" + yuanAmount.ToString("#,##0.##");
            }
        }

        [EventSystem.BindEvent]
        public void OnQueryResult(QueryPaymentResultsCommand action)
        {
            if (action.method != PaymentMethods.SEAYOO_SANDBOX)
            {
                return;
            }
            if (action.status == PaymentStatus.PAID)
            {
                GoToViewCommand.Invoke(new GoToViewCommand
                {
                    type = PayViewType.PAY_SUCCESS,
                    order = order,
                    productName = productNameText.text,
                    productValue = productValueText.text,
                    paymentMethod = paymentMethod
                });
            }
        }

        [EventSystem.BindEvent]
        public void ShowPayView(GoToViewCommand action)
        {
            if (action.type != PayViewType.PAY)
            {
                gameObject.SetActive(false);
                return;
            }
            gameObject.SetActive(true);
            productNameText.text = action.productName;
            productValueText.text = action.productValue;
            order = action.order;
            orderToken = action.orderToken;
        }
    }
}