using System;
using UnityEditor;
using UnityEngine;

public class ExtendEditor
{
    /// <summary>Style for a small checkbox</summary>
    public static readonly GUIStyle smallTickbox;
    /// <summary>Style for a small checkbox in mixed state</summary>
    public static readonly GUIStyle smallMixedTickbox;
    /// <summary>Style for a minilabel button</summary>
    public static readonly GUIStyle miniLabelButton;

    static readonly Texture2D paneOptionsIconDark;
    static readonly Texture2D paneOptionsIconLight;

    /// <summary> PaneOption icon </summary>
    public static Texture2D paneOptionsIcon { get { return EditorGUIUtility.isProSkin ? paneOptionsIconDark : paneOptionsIconLight; } }
    static ExtendEditor()
    {
        smallTickbox = new GUIStyle("ShurikenToggle");
        smallMixedTickbox = new GUIStyle("ShurikenToggleMixed");

        var transparentTexture = new Texture2D(1, 1, TextureFormat.ARGB32, false);
        transparentTexture.SetPixel(0, 0, Color.clear);
        transparentTexture.Apply();

        miniLabelButton = new GUIStyle(EditorStyles.miniLabel);
        miniLabelButton.normal = new GUIStyleState
        {
            background = transparentTexture,
            scaledBackgrounds = null,
            textColor = Color.grey
        };
        var activeState = new GUIStyleState
        {
            background = transparentTexture,
            scaledBackgrounds = null,
            textColor = Color.white
        };
        miniLabelButton.active = activeState;
        miniLabelButton.onNormal = activeState;
        miniLabelButton.onActive = activeState;

        paneOptionsIconDark = (Texture2D)EditorGUIUtility.Load("Builtin Skins/DarkSkin/Images/pane options.png");
        paneOptionsIconLight = (Texture2D)EditorGUIUtility.Load("Builtin Skins/LightSkin/Images/pane options.png");
    }

    /// <summary>Draw a splitter separator</summary>
    /// <param name="isBoxed">[Optional] add margin if the splitter is boxed</param>
    public static void DrawSplitter(bool isBoxed = false)
    {
        var rect = GUILayoutUtility.GetRect(1f, 1f);

        // Splitter rect should be full-width
        rect.xMin = 0f;
        rect.width += 4f;

        if (isBoxed)
        {
            rect.xMin = EditorGUIUtility.singleLineHeight;
            rect.width -= 1;
        }

        if (Event.current.type != EventType.Repaint)
            return;

        EditorGUI.DrawRect(rect, !EditorGUIUtility.isProSkin
            ? new Color(0.6f, 0.6f, 0.6f, 1.333f)
            : new Color(0.12f, 0.12f, 0.12f, 1.333f));
    }



    /// <summary>Draw a header toggle like in Volumes</summary>
    /// <param name="title"> The title of the header </param>
    /// <param name="group"> The group of the header </param>
    /// <param name="activeField">The active field</param>
    /// <param name="contextAction">The context action</param>
    /// <param name="hasMoreOptions">Delegate saying if we have MoreOptions</param>
    /// <param name="toggleMoreOptions">Callback called when the MoreOptions is toggled</param>
    /// <returns>return the state of the foldout header</returns>
    public static bool DrawHeaderToggle(string title, SerializedProperty activeField, bool toggle = false)
        => DrawHeaderToggle(EditorGUIUtility.TrTextContent(title),activeField, toggle);

    /// <summary>Draw a header toggle like in Volumes</summary>
    /// <param name="title"> The title of the header </param>
    /// <param name="group"> The group of the header </param>
    /// <param name="activeField">The active field</param>
    /// <param name="contextAction">The context action</param>
    /// <param name="hasMoreOptions">Delegate saying if we have MoreOptions</param>
    /// <param name="toggleMoreOptions">Callback called when the MoreOptions is toggled</param>
    /// <returns>return the state of the foldout header</returns>
    public static bool DrawHeaderToggle(GUIContent title, SerializedProperty activeField, bool toggle = false)
    {
        var backgroundRect = GUILayoutUtility.GetRect(1f, 17f);

        var labelRect = backgroundRect;
        labelRect.xMin += 32f;
        labelRect.xMax -= 20f + 16 + 5;

        var foldoutRect = backgroundRect;
        foldoutRect.y += 1f;
        foldoutRect.width = 13f;
        foldoutRect.height = 13f;

        var toggleRect = backgroundRect;
        toggleRect.x += 16f;
        toggleRect.y += 2f;
        toggleRect.width = 13f;
        toggleRect.height = 13f;

        // More options 1/2
        //var moreOptionsRect = new Rect();
        //if (hasMoreOptions != null)
        //{
        //    moreOptionsRect = backgroundRect;
        //    moreOptionsRect.x += moreOptionsRect.width - 16 - 1 - 16 - 5;
        //    moreOptionsRect.height = 15;
        //    moreOptionsRect.width = 16;
        //}

        // Background rect should be full-width
        backgroundRect.xMin = 0f;
        backgroundRect.width += 4f;

        // Background
        float backgroundTint = EditorGUIUtility.isProSkin ? 0.1f : 1f;
        EditorGUI.DrawRect(backgroundRect, new Color(backgroundTint, backgroundTint, backgroundTint, 0.2f));

        // Title
        using (new EditorGUI.DisabledScope(!activeField.boolValue))
            EditorGUI.LabelField(labelRect, title, EditorStyles.boldLabel);

        // Foldout
        //group.serializedObject.Update();
        toggle = GUI.Toggle(foldoutRect, toggle, GUIContent.none, EditorStyles.foldout);
        //group.serializedObject.ApplyModifiedProperties();

        // Active checkbox
        //activeField.serializedObject.Update();
        activeField.boolValue = GUI.Toggle(toggleRect, activeField.boolValue, GUIContent.none, smallTickbox);
        //activeField.serializedObject.ApplyModifiedProperties();

        // More options 2/2
        //if (hasMoreOptions != null)
        //{
        //    bool moreOptions = hasMoreOptions();
        //    bool newMoreOptions = Styles.DrawMoreOptions(moreOptionsRect, moreOptions);
        //    if (moreOptions ^ newMoreOptions)
        //        toggleMoreOptions?.Invoke();
        //}

        // Context menu
        var menuIcon = paneOptionsIcon;
        var menuRect = new Rect(labelRect.xMax + 3f + 16 + 5, labelRect.y + 1f, menuIcon.width, menuIcon.height);

        //if (contextAction != null)
        //    GUI.DrawTexture(menuRect, menuIcon);

        // Handle events
        var e = Event.current;

        //if (e.type == EventType.MouseDown)
        //{
        //    if (contextAction != null && menuRect.Contains(e.mousePosition))
        //    {
        //        contextAction(new Vector2(menuRect.x, menuRect.yMax));
        //        e.Use();
        //    }
        //    else if (labelRect.Contains(e.mousePosition))
        //    {
        //        if (e.button == 0)
        //            group.isExpanded = !group.isExpanded;
        //        else if (contextAction != null)
        //            contextAction(e.mousePosition);

        //        e.Use();
        //    }
        //}

        return toggle;
    }
}

// TODO: Should be cleaned up and put into CoreRP/Editor
sealed class TrackballUIDrawer
{
    static readonly int s_ThumbHash = "colorWheelThumb".GetHashCode();
    static GUIStyle s_WheelThumb;
    static Vector2 s_WheelThumbSize;
    static Material s_Material;

    System.Func<Vector4, Vector3> m_ComputeFunc;
    bool m_ResetState;
    Vector2 m_CursorPos;

    static TrackballUIDrawer()
    {
        if (s_Material == null)
            s_Material = new Material(Shader.Find("Hidden/Universal Render Pipeline/Editor/Trackball")) { hideFlags = HideFlags.HideAndDontSave };
    }

    public void OnGUI(SerializedProperty property, GUIContent title, System.Func<Vector4, Vector3> computeFunc)
    {
        if (property.propertyType != SerializedPropertyType.Vector4)
        {
            Debug.LogWarning("TrackballUIDrawer requires a Vector4 property");
            return;
        }

        m_ComputeFunc = computeFunc;
        var value = property.vector4Value;

        using (new EditorGUILayout.VerticalScope())
        {
            using (new EditorGUI.DisabledScope(!true))
                DrawWheel(ref value, true);

            DrawLabelAndOverride(title);
        }

        if (m_ResetState)
        {
            value = new Vector4(1f, 1f, 1f, 0f);
            m_ResetState = false;
        }

        property.vector4Value = value;
    }

    void DrawWheel(ref Vector4 value, bool overrideState)
    {
        var wheelRect = GUILayoutUtility.GetAspectRect(1f);
        float size = wheelRect.width;
        float hsize = size / 2f;
        float radius = 0.38f * size;

        Vector3 hsv;
        Color.RGBToHSV(value, out hsv.x, out hsv.y, out hsv.z);
        float offset = value.w;

        // Thumb
        var thumbPos = Vector2.zero;
        float theta = hsv.x * (Mathf.PI * 2f);
        thumbPos.x = Mathf.Cos(theta + (Mathf.PI / 2f));
        thumbPos.y = Mathf.Sin(theta - (Mathf.PI / 2f));
        thumbPos *= hsv.y * radius;

        // Draw the wheel
        if (Event.current.type == EventType.Repaint)
        {
            // Style init
            if (s_WheelThumb == null)
            {
                s_WheelThumb = new GUIStyle("ColorPicker2DThumb");
                s_WheelThumbSize = new Vector2(
                    !Mathf.Approximately(s_WheelThumb.fixedWidth, 0f) ? s_WheelThumb.fixedWidth : s_WheelThumb.padding.horizontal,
                    !Mathf.Approximately(s_WheelThumb.fixedHeight, 0f) ? s_WheelThumb.fixedHeight : s_WheelThumb.padding.vertical
                );
            }

            // Retina support
            float scale = EditorGUIUtility.pixelsPerPoint;

            // Wheel texture
            var oldRT = RenderTexture.active;
            var rt = RenderTexture.GetTemporary((int)(size * scale), (int)(size * scale), 0, RenderTextureFormat.ARGB32, RenderTextureReadWrite.sRGB);
            s_Material.SetFloat("_Offset", offset);
            s_Material.SetFloat("_DisabledState", overrideState && GUI.enabled ? 1f : 0.5f);
            s_Material.SetVector("_Resolution", new Vector2(size * scale, size * scale / 2f));
            Graphics.Blit(null, rt, s_Material, EditorGUIUtility.isProSkin ? 0 : 1);
            RenderTexture.active = oldRT;

            GUI.DrawTexture(wheelRect, rt);
            RenderTexture.ReleaseTemporary(rt);

            var thumbSize = s_WheelThumbSize;
            var thumbSizeH = thumbSize / 2f;
            s_WheelThumb.Draw(new Rect(wheelRect.x + hsize + thumbPos.x - thumbSizeH.x, wheelRect.y + hsize + thumbPos.y - thumbSizeH.y, thumbSize.x, thumbSize.y), false, false, false, false);
        }

        // Input
        var bounds = wheelRect;
        bounds.x += hsize - radius;
        bounds.y += hsize - radius;
        bounds.width = bounds.height = radius * 2f;
        hsv = GetInput(bounds, hsv, thumbPos, radius);
        value = Color.HSVToRGB(hsv.x, hsv.y, 1f);
        value.w = offset;

        // Offset
        var sliderRect = GUILayoutUtility.GetRect(1f, 17f);
        float padding = sliderRect.width * 0.05f; // 5% padding
        sliderRect.xMin += padding;
        sliderRect.xMax -= padding;
        value.w = GUI.HorizontalSlider(sliderRect, value.w, -1f, 1f);

        if (m_ComputeFunc == null)
            return;

        // Values
        var displayValue = m_ComputeFunc(value);

        using (new EditorGUI.DisabledGroupScope(true))
        {
            var valuesRect = GUILayoutUtility.GetRect(1f, 17f);
            valuesRect.width /= 3f;
            GUI.Label(valuesRect, displayValue.x.ToString("F2"), EditorStyles.centeredGreyMiniLabel);
            valuesRect.x += valuesRect.width;
            GUI.Label(valuesRect, displayValue.y.ToString("F2"), EditorStyles.centeredGreyMiniLabel);
            valuesRect.x += valuesRect.width;
            GUI.Label(valuesRect, displayValue.z.ToString("F2"), EditorStyles.centeredGreyMiniLabel);
            valuesRect.x += valuesRect.width;
        }
    }

    void DrawLabelAndOverride(GUIContent title, SerializedProperty overrideState = null)
    {
        // Title
        var areaRect = GUILayoutUtility.GetRect(1f, 17f);
        var labelSize = EditorStyles.miniLabel.CalcSize(title);
        var labelRect = new Rect(areaRect.x + areaRect.width / 2 - labelSize.x / 2, areaRect.y, labelSize.x, labelSize.y);
        GUI.Label(labelRect, title, EditorStyles.miniLabel);

        // Override checkbox
        var overrideRect = new Rect(labelRect.x - 17, labelRect.y + 3, 17f, 17f);
        GUI.Label(overrideRect, EditorGUIUtility.TrTextContent("", "Override this setting for this volume."));
        //overrideState.boolValue = GUI.Toggle(overrideRect, overrideState.boolValue, EditorGUIUtility.TrTextContent("", "Override this setting for this volume."),ExtendEditor.smallTickbox);
        //Debug.Log($"{overrideState.displayName} toggle : {overrideState.boolValue}");
    }

    Vector3 GetInput(Rect bounds, Vector3 hsv, Vector2 thumbPos, float radius)
    {
        var e = Event.current;
        var id = GUIUtility.GetControlID(s_ThumbHash, FocusType.Passive, bounds);
        var mousePos = e.mousePosition;

        if (e.type == EventType.MouseDown && GUIUtility.hotControl == 0 && bounds.Contains(mousePos))
        {
            if (e.button == 0)
            {
                var center = new Vector2(bounds.x + radius, bounds.y + radius);
                float dist = Vector2.Distance(center, mousePos);

                if (dist <= radius)
                {
                    e.Use();
                    m_CursorPos = new Vector2(thumbPos.x + radius, thumbPos.y + radius);
                    GUIUtility.hotControl = id;
                    GUI.changed = true;
                }
            }
            else if (e.button == 1)
            {
                e.Use();
                GUI.changed = true;
                m_ResetState = true;
            }
        }
        else if (e.type == EventType.MouseDrag && e.button == 0 && GUIUtility.hotControl == id)
        {
            e.Use();
            GUI.changed = true;
            m_CursorPos += e.delta * 0.2f; // Sensitivity
            GetWheelHueSaturation(m_CursorPos.x, m_CursorPos.y, radius, out hsv.x, out hsv.y);
        }
        else if (e.rawType == EventType.MouseUp && e.button == 0 && GUIUtility.hotControl == id)
        {
            e.Use();
            GUIUtility.hotControl = 0;
        }

        return hsv;
    }

    void GetWheelHueSaturation(float x, float y, float radius, out float hue, out float saturation)
    {
        float dx = (x - radius) / radius;
        float dy = (y - radius) / radius;
        float d = Mathf.Sqrt(dx * dx + dy * dy);
        hue = Mathf.Atan2(dx, -dy);
        hue = 1f - ((hue > 0) ? hue : (Mathf.PI * 2f) + hue) / (Mathf.PI * 2f);
        saturation = Mathf.Clamp01(d);
    }
}