using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEngine;
using VCam.Exporter.Export;
using VCam.Exporter.Pipeline;
using VRC.SDK3.Avatars.Components;

namespace VCam.Exporter
{
    /// <summary>
    /// Main exporter UI (menu Tools > VCam Exporter > 익스포터 창). Lets the user pick the avatar, the state
    /// (scene / in-game default), texture size, meta authors, and fix expression links that automatic mapping got
    /// wrong (e.g. a missing left wink). Settings are saved per avatar to &lt;project&gt;/UserSettings/VirtualCam/&lt;avatar&gt;.json
    /// (ExportOptions), so batch exports reuse them. The export writes the .vrm alone (D-092).
    ///
    /// The expression preview runs on the UNBAKED avatar (instant, no bake). Modular Avatar can merge meshes
    /// during the bake, so overrides are matched by renderer path, then by renderer name (ExpressionMapper).
    /// </summary>
    internal sealed class ExporterWindow : EditorWindow
    {
        private static readonly string[] StateLabels = { "Unity 씬에 보이는 그대로", "VRChat 게임 속 기본 상태" };
        private static readonly string[] TextureLabels = { "512", "1024", "2048 (권장)", "4096", "원본 크기" };
        private static readonly int[] TextureValues = { 512, 1024, 2048, 4096, 0 };
        /// <summary>Presets shown by default; the rest (lookUp …) sit under a foldout because few avatars have them.</summary>
        private const int CommonPresetCount = 13;

        private VRCAvatarDescriptor _avatar;
        private ExportOptions _options;
        private List<MappedExpression> _auto = new List<MappedExpression>();
        private readonly List<(string path, string shape)> _shapes = new List<(string, string)>();
        private string[] _shapeOptions = new string[0];
        private Vector2 _scroll;
        private bool _showAdvanced;
        private bool _showMorePresets;
        private string _lastSummary;
        private string _lastOutput;
        private bool _dirty;
        /// <summary>Shaders of the selected avatar with no dedicated web port (shown in the window, D-073).</summary>
        private string[] _unsupportedShaders = new string[0];
        /// <summary>What the web app will do with this avatar's face, eyes and special materials (D-078).</summary>
        private readonly List<(string text, MessageType type)> _checks = new List<(string, MessageType)>();

        [MenuItem("Tools/Virtual Cam Exporter/익스포터 창", false, 0)]
        private static void Open()
        {
            var w = GetWindow<ExporterWindow>("Virtual Cam Exporter");
            w.minSize = new Vector2(440, 520);
            w.PickSelection();
        }

        private void OnEnable() => PickSelection();

        private void OnSelectionChange()
        {
            if (_avatar != null) return;
            PickSelection();
            Repaint();
        }

        private void PickSelection()
        {
            var go = Selection.activeGameObject;
            var d = go != null ? go.GetComponentInParent<VRCAvatarDescriptor>(true) : null;
            if (d != null) SetAvatar(d);
        }

        private void SetAvatar(VRCAvatarDescriptor d)
        {
            _avatar = d;
            _options = ExportOptions.LoadFor(d.gameObject.name);
            _dirty = false;
            _lastSummary = null;
            Analyze();
        }

        private void Analyze()
        {
            _auto = new List<MappedExpression>();
            _shapes.Clear();
            if (_avatar == null) return;
            var root = _avatar.gameObject;
            var info = DescriptorInfo.Read(root);
            _auto = ExpressionMapper.Map(root, info, new ExportReport());
            CheckAvatar(root, info);
            // lilToon (official and lilToon-based custom) and Poiyomi have web ports; MToon is VRM's own shader.
            _unsupportedShaders = root.GetComponentsInChildren<Renderer>(true)
                .SelectMany(r => r.sharedMaterials)
                .Where(m => m != null && m.shader != null)
                .Select(m => m.shader)
                .Distinct()
                .Where(sh =>
                {
                    var kind = Util.ShaderFamily.Classify(sh);
                    return kind != Util.ShaderKind.LilToon && kind != Util.ShaderKind.LilToonCustom
                        && kind != Util.ShaderKind.Poiyomi && kind != Util.ShaderKind.MToon;
                })
                .Select(sh => sh.name)
                .OrderBy(n => n)
                .ToArray();
            foreach (var smr in root.GetComponentsInChildren<SkinnedMeshRenderer>(true))
            {
                var mesh = smr.sharedMesh;
                if (mesh == null || mesh.blendShapeCount == 0) continue;
                var path = AnimationUtility.CalculateTransformPath(smr.transform, root.transform);
                for (var i = 0; i < mesh.blendShapeCount; i++) _shapes.Add((path, mesh.GetBlendShapeName(i)));
            }
            // "/" in popup labels makes sub-menus: renderer path → blendshape.
            _shapeOptions = new[] { "자동", "없음 (내보내지 않음)" }
                .Concat(_shapes.Select(s => $"{s.path}/{s.shape}"))
                .ToArray();
        }

        /// <summary>
        /// The things the test avatars showed are easy to miss until the web app (D-078): which meshes the face
        /// expressions reach, whether and how far the eyes turn, and materials the web draws differently.
        /// </summary>
        private void CheckAvatar(GameObject root, DescriptorInfo info)
        {
            _checks.Clear();
            foreach (var (text, warning) in AvatarChecks.Run(root, info, _auto))
                _checks.Add((text, warning ? MessageType.Warning : MessageType.None));
        }

        private void OnGUI()
        {
            _scroll = EditorGUILayout.BeginScrollView(_scroll);
            EditorGUILayout.HelpBox("VRChat 아바타를 Virtual Cam 웹앱용 .vrm 파일로 내보냅니다. 업로드 때처럼 MA·VRCFury를 적용한 복제본으로 작업하고, 원본 아바타와 에셋은 바꾸지 않습니다.", MessageType.Info);

            var picked = (VRCAvatarDescriptor)EditorGUILayout.ObjectField("아바타", _avatar, typeof(VRCAvatarDescriptor), true);
            if (picked != _avatar && picked != null) SetAvatar(picked);
            if (_avatar == null)
            {
                EditorGUILayout.HelpBox("Hierarchy에서 아바타(VRC Avatar Descriptor가 있는 오브젝트)를 선택하거나 위 칸에 끌어다 놓으세요.", MessageType.None);
                EditorGUILayout.EndScrollView();
                return;
            }
            if (AvatarBaker.IsBakedCopy(_avatar.gameObject))
                EditorGUILayout.HelpBox("이 오브젝트는 이미 빌드 적용된 복제본입니다. 원본 아바타를 선택하세요.", MessageType.Error);
            EditorGUILayout.HelpBox(_unsupportedShaders.Length == 0
                ? "지원 셰이더: lilToon, Poiyomi. 이 아바타는 모두 지원 셰이더입니다."
                : "지원 셰이더: lilToon, Poiyomi. 다음 셰이더는 전용 변환이 없어 기본 색과 텍스처만 옮기고 VRM 기본 셰이더(MToon)로 비슷하게 보입니다: "
                  + string.Join(", ", _unsupportedShaders),
                _unsupportedShaders.Length == 0 ? MessageType.None : MessageType.Warning);
            foreach (var (text, type) in _checks) EditorGUILayout.HelpBox(text, type);

            EditorGUI.BeginChangeCheck();
            DrawSettings();
            DrawExpressions();
            if (EditorGUI.EndChangeCheck()) _dirty = true;

            DrawExport();
            EditorGUILayout.EndScrollView();
        }

        private void DrawSettings()
        {
            EditorGUILayout.Space(8);
            EditorGUILayout.LabelField("내보내기 설정", EditorStyles.boldLabel);
            _options.state = (ExportState)EditorGUILayout.Popup("상태 기준", (int)_options.state, StateLabels);
            EditorGUILayout.HelpBox(_options.state == ExportState.Scene
                ? "지금 Unity 씬에서 켜져 있는 옷·소품과 쉐이프키 값을 그대로 내보냅니다. 내보내기 전에 씬에서 원하는 모습으로 맞춰 두세요."
                : "VRChat에 처음 들어갔을 때의 모습으로 내보냅니다. FX 애니메이터의 기본 상태와 Expression Parameters 기본값으로 토글을 계산합니다(다른 사람에게 보이는 모습 기준).",
                MessageType.None);
            var texIndex = System.Array.IndexOf(TextureValues, _options.maxTextureSize);
            texIndex = EditorGUILayout.Popup("텍스처 최대 크기", texIndex < 0 ? 2 : texIndex, TextureLabels);
            _options.maxTextureSize = TextureValues[texIndex];
            _options.authors = EditorGUILayout.TextField(new GUIContent("제작자", "VRM 메타 정보의 제작자. 여러 명이면 쉼표로 구분합니다."), _options.authors);

            _showAdvanced = EditorGUILayout.Foldout(_showAdvanced, "고급", true);
            if (_showAdvanced)
            {
                EditorGUI.indentLevel++;
                _options.exportTangents = EditorGUILayout.Toggle("정점 탄젠트 내보내기", _options.exportTangents);
                if (_options.exportTangents)
                    EditorGUILayout.HelpBox("three-vrm 3.6에서는 탄젠트가 있으면 외곽선이 깨집니다. 특별한 이유가 없으면 끄세요.", MessageType.Warning);
                // Development check only, never saved (D-092): the report JSON and Unity reference pictures beside the .vrm.
                var devFiles = EditorGUILayout.Toggle(new GUIContent("개발 확인용 파일도 저장",
                    "보고서(.vcam-report.json)와 Unity 기준 사진(.ref-*.png)을 .vrm 옆에 함께 저장합니다. 웹앱 사용에는 필요 없습니다. 창을 다시 열면 꺼집니다."),
                    _options.writeReport || _options.captureReference);
                _options.writeReport = _options.captureReference = devFiles;
                EditorGUI.indentLevel--;
            }
        }

        private void DrawExpressions()
        {
            EditorGUILayout.Space(8);
            EditorGUILayout.LabelField("표정 연결", EditorStyles.boldLabel);
            EditorGUILayout.HelpBox("자동으로 찾은 쉐이프키를 확인하세요. 틀렸거나 비어 있으면 직접 고릅니다. '자동'은 디스크립터와 이름 규칙으로 찾은 값입니다.", MessageType.None);

            var presets = ExpressionMapper.PresetNames;
            for (var i = 0; i < presets.Length; i++)
            {
                if (i == CommonPresetCount)
                {
                    _showMorePresets = EditorGUILayout.Foldout(_showMorePresets, "시선·기타 표정", true);
                    if (!_showMorePresets) break;
                }
                DrawExpressionRow(presets[i]);
            }

            using (new EditorGUILayout.HorizontalScope())
            {
                if (GUILayout.Button("다시 분석")) Analyze();
                if (GUILayout.Button("설정 저장"))
                {
                    _options.SaveFor(_avatar.gameObject.name);
                    _dirty = false;
                }
            }
            if (_dirty) EditorGUILayout.HelpBox("저장하지 않은 변경이 있습니다. 내보내기를 누르면 함께 저장됩니다.", MessageType.None);
        }

        private void DrawExpressionRow(string preset)
        {
            var auto = _auto.FirstOrDefault(e => e.Name == preset);
            // Every mesh the expression moves counts: a face split into face/beard/eyelash meshes binds all of them.
            var autoLabel = auto != null && auto.Binds.Count > 0
                ? $"{auto.Binds[0].Renderer.name}/{auto.Binds[0].Renderer.sharedMesh.GetBlendShapeName(auto.Binds[0].BlendShapeIndex)}"
                  + (auto.Binds.Count > 1 ? $" 외 메시 {auto.Binds.Count - 1}개" : "")
                : "없음";

            var o = _options.OverrideFor(preset);
            var index = 0;
            if (o != null)
            {
                if (o.disabled) index = 1;
                else
                {
                    var found = _shapes.FindIndex(s => s.path == o.rendererPath && s.shape == o.blendShape);
                    index = found >= 0 ? found + 2 : 0;
                }
            }

            var label = new GUIContent(preset, $"자동으로 찾은 값: {autoLabel}");
            var next = EditorGUILayout.Popup(label, index, _shapeOptions.Length > 0 ? _shapeOptions : new[] { "자동" });
            if (index == 0)
                EditorGUILayout.LabelField(" ", $"자동: {autoLabel}", EditorStyles.miniLabel);
            if (next == index) return;

            _options.expressionOverrides.RemoveAll(x => x.expression == preset);
            if (next == 1) _options.expressionOverrides.Add(new ExpressionOverride { expression = preset, disabled = true });
            else if (next >= 2)
            {
                var s = _shapes[next - 2];
                _options.expressionOverrides.Add(new ExpressionOverride { expression = preset, rendererPath = s.path, blendShape = s.shape });
            }
        }

        private void DrawExport()
        {
            EditorGUILayout.Space(8);
            EditorGUILayout.LabelField("내보내기", EditorStyles.boldLabel);
            var name = _avatar.gameObject.name;
            // The save folder is always on screen (D-073): the user picks it once per avatar and sees where the file goes.
            var folder = _options.ResolvedOutputFolder();
            using (new EditorGUILayout.HorizontalScope())
            {
                EditorGUILayout.PrefixLabel(new GUIContent("저장 폴더", "내보낸 .vrm과 보고서·기준 스크린샷이 저장되는 폴더입니다. 아바타마다 기억합니다."));
                EditorGUILayout.SelectableLabel(folder, EditorStyles.textField, GUILayout.Height(EditorGUIUtility.singleLineHeight));
                if (GUILayout.Button("변경...", GUILayout.Width(58)))
                {
                    var picked = EditorUtility.OpenFolderPanel("VRM을 저장할 폴더 고르기", Directory.Exists(folder) ? folder : "", "");
                    if (!string.IsNullOrEmpty(picked))
                    {
                        _options.outputFolder = picked;
                        _options.SaveFor(name);
                        GUIUtility.ExitGUI();
                    }
                }
                if (GUILayout.Button("열기", GUILayout.Width(44))) OpenFolder(folder);
            }
            var target = Path.Combine(folder, ExportOptions.SafeFileName(name) + ".vrm");
            EditorGUILayout.LabelField(" ", "저장될 파일: " + target, EditorStyles.wordWrappedMiniLabel);
            if (!string.IsNullOrWhiteSpace(_options.outputFolder) && GUILayout.Button("기본 폴더(프로젝트/VCamExport)로 되돌리기", EditorStyles.miniButton))
            {
                _options.outputFolder = "";
                _options.SaveFor(name);
            }
            using (new EditorGUI.DisabledScope(AvatarBaker.IsBakedCopy(_avatar.gameObject)))
            {
                if (GUILayout.Button("VRM 내보내기", GUILayout.Height(32)))
                {
                    if (File.Exists(target) && !EditorUtility.DisplayDialog("Virtual Cam Exporter",
                            "이미 같은 이름의 파일이 있습니다.\n" + target + "\n\n덮어쓸까요?", "덮어쓰기", "취소"))
                        return;
                    Directory.CreateDirectory(folder);
                    _options.SaveFor(name);
                    _dirty = false;
                    var result = VCamExporter.Export(_avatar.gameObject, target, _options);
                    _lastSummary = result.Summary;
                    _lastOutput = result.Ok ? result.OutputPath : result.ReportPath;
                    GUIUtility.ExitGUI();
                }
            }
            if (string.IsNullOrEmpty(_lastSummary)) return;
            EditorGUILayout.Space(4);
            EditorGUILayout.LabelField("마지막 결과", EditorStyles.boldLabel);
            EditorGUILayout.SelectableLabel(_lastSummary, EditorStyles.textArea, GUILayout.MinHeight(160));
            if (_lastOutput != null && GUILayout.Button("결과 폴더 열기")) EditorUtility.RevealInFinder(_lastOutput);
        }

        /// <summary>Opens the folder itself in Explorer (RevealInFinder on a folder opens its parent instead).</summary>
        private static void OpenFolder(string folder)
        {
            Directory.CreateDirectory(folder);
            Application.OpenURL("file:///" + Path.GetFullPath(folder).Replace('\\', '/'));
        }
    }
}
