using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Stove.StoveSDK;
using UnityEngine.UI;


public class AuthUISample : MonoBehaviour
{
    public Toggle verifyIdentificationToggle;
    bool isVerifyIdentification = false;

    // Start is called before the first frame update
    void Start()
    {
        if (verifyIdentificationToggle != null)
        {
            verifyIdentificationToggle.onValueChanged.AddListener(OnVerifyIdentificationToggleChanged);
        }
    }

    // Update is called once per frame
    void Update()
    {
        
    }

	public void Login()
	{
        Debug.Log("------- [Stove-Sample] AuthUI.Login -------");

        AuthUI.Login((Result result, AccessToken accessToken) =>
        {
            Debug.Log("------- [Stove-Sample] AuthUI.Login : " + result + " -------");

            if (result.IsSuccessful)
            {
                SSTools.ShowMessage("AuthUI.Login Success", SSTools.Position.bottom, SSTools.Time.oneSecond);
            }
            else
            {
                if (result.IsServerError)
                {
                    OperationUI.HandleResult(result, (Result operationResult) =>
                    {
                        if (result.ErrorCode == 44008 || result.ErrorCode == 45006)
                        {
                            PlayerPrefs.DeleteKey("guest");
                            Auth.Logout();
                        }
                    });
                } 
                else if(result.IsCanceled) {
                    MessageDialog.Show("로그인에 실패 하였습니다. 로그인 재 시도 합니다." , () =>
                    {
                        if (Auth.AccessToken != null) {
                            // 로그인 끝난 이후 약관 재동의 or 기기등록 에서 화면을 닫는 상황 or 로그인페이지서 창을 내리는 경우
                            // 토큰이 있는 상황, 무조건 초기화면으로 돌아가서 토큰 검사부터 시작해야함 ( Ex. Touch Screen )
                            Login();
                            SSTools.ShowMessage("AuthUI.Login Fail (Token)", SSTools.Position.bottom, SSTools.Time.oneSecond);
                        } else {
                            // 로그인 완료 전에 화면을 닫는 상황
                            // 토큰이 없는 경우에는 로그인 / 게스트 로그인 버튼 노출 상관 없음
                            SSTools.ShowMessage("AuthUI.Login Fail (Token null) ", SSTools.Position.bottom, SSTools.Time.oneSecond);
                        }
                    });
                } 
                else
                {
                     SSTools.ShowMessage("AuthUI.Login Fail", SSTools.Position.bottom, SSTools.Time.oneSecond);
                }
            }
        });
	}

    public void GuestStart()
    {
        Debug.Log("------- [Stove-Sample] AuthUI.GuestStart -------");

        AuthUI.GuestStart((Result result, AccessToken accessToken) =>
        {
            Debug.Log("------- [Stove-Sample] AuthUI.GuestStart : " + result + " -------");

            if (result.IsSuccessful)
            {
                SSTools.ShowMessage("AuthUI.GuestStart Success", SSTools.Position.bottom, SSTools.Time.oneSecond);
            }
            else
            {
                SSTools.ShowMessage("AuthUI.GuestStart Fail", SSTools.Position.bottom, SSTools.Time.oneSecond);
            }
        });
    }

    public void SetProviders()
    {
        SetProviderDialog.Show(providers =>
        {
            Debug.Log("------- [Stove-Sample] AuthUI.Providers : " + providers + " -------");

            AuthUI.Providers = providers;
        });
    }

    public void Withdraw()
    {
        Debug.Log("------- [Stove-Sample] AuthUI.Withdraw -------");

        AuthUI.Withdraw((Result result) =>
        {
            Debug.Log("------- [Stove-Sample] AuthUI.Withdraw : " + result + " -------");

            if (result.IsSuccessful)
            {
                SSTools.ShowMessage("AuthUI.Withdraw Success", SSTools.Position.bottom, SSTools.Time.oneSecond);
            }
            else
            {
                SSTools.ShowMessage("AuthUI.Withdraw Fail", SSTools.Position.bottom, SSTools.Time.oneSecond);
            }
        });
    }

    public void Link()
    {
        Debug.Log("------- [Stove-Sample] AuthUI.Link -------");

        AuthUI.Link((Result result) =>
        {
            Debug.Log("------- [Stove-Sample] AuthUI.Link : " + result + " -------");

            if (Auth.AccessToken != null)
            {
                if (Auth.AccessToken.User.IsGuest())
                {
                    Debug.Log("------- [Stove-Sample] AuthUI.Link : GUEST -------");
                } else
                {
                    Debug.Log("------- [Stove-Sample] AuthUI.Link : NOT GUEST -------");
                }
            }

            if (result.IsSuccessful)
            {
                SSTools.ShowMessage("AuthUI.Link Success", SSTools.Position.bottom, SSTools.Time.oneSecond);
            }
            else
            {
                SSTools.ShowMessage("AuthUI.Link Fail", SSTools.Position.bottom, SSTools.Time.oneSecond);
            }
        });
    }

    public void ManageAccount()
    {
        Debug.Log("------- [Stove-Sample] AuthUI.ManageAccount -------");

        bool isGuest = false;
        if (Auth.AccessToken != null)
        {
            isGuest = Auth.AccessToken.User.IsGuest();
        }

        AuthUI.ManageAccount((Result result) =>
        {
            Debug.Log("------- [Stove-Sample] AuthUI.ManageAccount : " + result + " -------");

            if (result.IsSuccessful)
            {
                if (result.UserInfo != null && result.UserInfo.TryGetValue("userAction", out string userAction))
                {
                    if (!string.IsNullOrEmpty(userAction) && userAction.Equals("withdraw"))
                    {
                        PlayerPrefs.DeleteKey("guest");
                    }
                }

                SSTools.ShowMessage("AuthUI.ManageAccount Success", SSTools.Position.bottom, SSTools.Time.oneSecond);
            }
            else
            {              
                if (Auth.AccessToken != null)
                {
                    if (!Auth.AccessToken.User.IsGuest() && isGuest)
                    {
                        SSTools.ShowMessage("AuthUI.ManageAccount Conversion to regular membership", SSTools.Position.bottom, SSTools.Time.oneSecond);

                        PlayerPrefs.DeleteKey("guest");

                        bool enable_guid = Constants.Get("enable_guid", true);
                        if (enable_guid) //차후 정회원 전환 API에서 기기등록 여부 결과 주면 적용 임시 GUID 노출
                        {
                            MessageDialog.Show("기기등록을 위해 초기 화면으로 돌아갑니다.(로그인재시도)" , () =>
                            {
                                //기기등록이 필요한 게임의 경우 정회원 전환 이후 초기화 화면으로 전환 ( 기기등록을 하기 위해 )
                                Login();
                            });
                        }
                    } else {
                        SSTools.ShowMessage("AuthUI.ManageAccount Fail", SSTools.Position.bottom, SSTools.Time.oneSecond);

                    }
                } else {
                    SSTools.ShowMessage("AuthUI.ManageAccount Token null", SSTools.Position.bottom, SSTools.Time.oneSecond);
                }
            }
        });
    }

    public void ManageDevices()
    {
        Debug.Log("------- [Stove-Sample] AuthUI.ManageDevices -------");
        if (Auth.AccessToken != null) {
            AuthUI.ManageDevices((Result result) =>
            {
                Debug.Log("------- [Stove-Sample] AuthUI.ManageDevices : " + result + " -------");
                if (Auth.GetVerifiedDevice()) {
                    MessageDialog.Show("등록된 기기 입니다." , () =>
                    {

                    });
                } else {
                    MessageDialog.Show("기기등록 필요합니다. 초기화면으로 돌아갑니다." , () =>
                    {

                    });
                }
            });
        }
    }

    public void VerifyIdentification()
    {
        Debug.Log("------- [Stove-Sample] AuthUI.VerifyIdentification -------");

        if (isVerifyIdentification)
        {
            SSTools.ShowMessage("isVerifyIdentification ON", SSTools.Position.bottom, SSTools.Time.oneSecond);
        } else
        {
            SSTools.ShowMessage("isVerifyIdentification OFF", SSTools.Position.bottom, SSTools.Time.oneSecond);
        }

        if (Auth.AccessToken != null) {
            AuthUI.VerifyIdentification(isVerifyIdentification, (Result result, string state) =>
            {
                Debug.Log("------- [Stove-Sample] AuthUI.VerifyIdentification : " + result + "state : "+ state +" -------");
                if (result.IsSuccessful)
                {
                    SSTools.ShowMessage("AuthUI.VerifyIdentification Success", SSTools.Position.bottom, SSTools.Time.oneSecond);
                }
                else
                {
                    SSTools.ShowMessage("AuthUI.VerifyIdentification Fail", SSTools.Position.bottom, SSTools.Time.oneSecond);
                }
            });
        }
    }

    // VerifyIdentificationByType 에서만 ListDialog inner Panel 사이즈를 임시로 줄였다가 복구하기 위한 상태
    private RectTransform _listInnerPanelRect;
    private Vector2 _origAnchorMin;
    private Vector2 _origAnchorMax;
    private Vector2 _origSizeDelta;
    private Vector2 _origAnchoredPosition;
    private bool _listSizeOverridden;

    public void VerifyIdentificationByType()
    {
        Debug.Log("------- [Stove-Sample] AuthUI.VerifyIdentification(IdentificationType) -------");

        if (Auth.AccessToken == null)
        {
            return;
        }

        // IdentificationType enum 값을 매번 선택하도록 ListDialog 노출
        List<string> typeList = new List<string> { "CI", "SDI" };
        ListDialog.Show(typeList, (string selected) =>
        {
            // 다음 ListDialog 호출자(FetchGPGProvider 등)에 영향 없도록 원상복구
            RestoreListDialogPanelSize();

            if (selected == null)
            {
                // cancel
                Debug.Log("------- [Stove-Sample] VerifyIdentificationByType Cancel -------");
                return;
            }

            IdentificationType type = selected.Equals("SDI")
                ? IdentificationType.SDI
                : IdentificationType.CI;

            SSTools.ShowMessage("IdentificationType : " + type, SSTools.Position.bottom, SSTools.Time.oneSecond);

            AuthUI.VerifyIdentification(type, (Result result, string state) =>
            {
                Debug.Log("------- [Stove-Sample] AuthUI.VerifyIdentification(IdentificationType) : " + result + " state : " + state + " -------");
                if (result.IsSuccessful)
                {
                    SSTools.ShowMessage("AuthUI.VerifyIdentification(Type) Success", SSTools.Position.bottom, SSTools.Time.oneSecond);
                }
                else
                {
                    SSTools.ShowMessage("AuthUI.VerifyIdentification(Type) Fail", SSTools.Position.bottom, SSTools.Time.oneSecond);
                }
            });
        });

        // 본인인증 케이스(2개 항목)에 한해 팝업 자체 높이를 축소
        ShrinkListDialogPanel(580f, 500f);

        // Panel 재배치 직후 viewport 좌표 동기화
        Canvas.ForceUpdateCanvases();

        // 항목들을 (축소된) viewport 세로 중앙으로 재배치
        CenterListDialogItems();
    }

    private void ShrinkListDialogPanel(float width, float height)
    {
        GameObject panel = GameObject.Find("ListDialogPanel");
        if (panel == null) return;
        ListDialog dlg = panel.GetComponent<ListDialog>();
        if (dlg == null || dlg.Panel == null) return;

        _listInnerPanelRect = dlg.Panel.GetComponent<RectTransform>();
        if (_listInnerPanelRect == null) return;

        // 원본 anchor/size 백업
        _origAnchorMin = _listInnerPanelRect.anchorMin;
        _origAnchorMax = _listInnerPanelRect.anchorMax;
        _origSizeDelta = _listInnerPanelRect.sizeDelta;
        _origAnchoredPosition = _listInnerPanelRect.anchoredPosition;
        _listSizeOverridden = true;

        // stretch 모드를 중앙 고정 + 명시 사이즈로 임시 전환
        _listInnerPanelRect.anchorMin = new Vector2(0.5f, 0.5f);
        _listInnerPanelRect.anchorMax = new Vector2(0.5f, 0.5f);
        _listInnerPanelRect.sizeDelta = new Vector2(width, height);
        _listInnerPanelRect.anchoredPosition = Vector2.zero;
    }

    private void RestoreListDialogPanelSize()
    {
        if (!_listSizeOverridden) return;
        if (_listInnerPanelRect != null)
        {
            _listInnerPanelRect.anchorMin = _origAnchorMin;
            _listInnerPanelRect.anchorMax = _origAnchorMax;
            _listInnerPanelRect.sizeDelta = _origSizeDelta;
            _listInnerPanelRect.anchoredPosition = _origAnchoredPosition;
        }
        _listSizeOverridden = false;
        _listInnerPanelRect = null;
    }

    private void CenterListDialogItems()
    {
        GameObject panel = GameObject.Find("ListDialogPanel");
        if (panel == null) return;

        Transform viewport = panel.transform.Find("Panel/Scroll View/Viewport");
        if (viewport == null) return;
        Transform content = viewport.Find("Content");
        if (content == null) return;

        RectTransform viewportRect = viewport as RectTransform;
        if (viewportRect == null) return;

        // ListDialog.Show 에서 사용하는 항목 간격과 동일하게 유지
        const float ITEM_HEIGHT = 150f;

        // Viewport pivot 이 (0, 1) top-left 이라 viewport.position.y 는 상단 Y.
        // 정확한 세로 중앙은 world corners 평균으로 계산.
        // corners[0]=bottom-left, [1]=top-left, [2]=top-right, [3]=bottom-right
        Vector3[] corners = new Vector3[4];
        viewportRect.GetWorldCorners(corners);
        float centerY = (corners[0].y + corners[1].y) * 0.5f;

        int n = content.childCount;
        if (n == 0) return;

        // 그룹을 viewport 세로 중앙에 정렬: i 번째 항목 Y = centerY + ((n-1)/2 - i) * ITEM_HEIGHT
        for (int i = 0; i < n; i++)
        {
            Transform child = content.GetChild(i);
            Vector3 p = child.position;
            float y = centerY + ((n - 1) * 0.5f - i) * ITEM_HEIGHT;
            child.position = new Vector3(p.x, y, p.z);
        }
    }

    public void SwitchAccount()
    {
        Debug.Log("------- [Stove-Sample] AuthUI.SwitchAccount -------");
	    if (Auth.AccessToken != null) {
	        AuthUI.SwitchAccount((Result result) =>
        	{
                Debug.Log("------- [Stove-Sample] AuthUI.SwitchAccount : " + result + " -------");
                if (result.IsSuccessful)
                {
                    SSTools.ShowMessage("AuthUI.SwitchAccount Success", SSTools.Position.bottom, SSTools.Time.oneSecond);
                }
                else
                {
                    SSTools.ShowMessage("AuthUI.SwitchAccount Fail", SSTools.Position.bottom, SSTools.Time.oneSecond);
                }
        	});
	    }
    }

    public void OnVerifyIdentificationToggleChanged(bool isOn)
    {
        isVerifyIdentification = isOn;
    }

    public void Version()
    {
        SSTools.ShowMessage("AuthUI Version : " + AuthUI.GetVersion(), SSTools.Position.bottom, SSTools.Time.oneSecond);
    }
}
