using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Gtk;
using UI = Gtk.Builder.ObjectAttribute;

/// Controller for notebook page 2 (SoundBox). Not a Gtk.Window — same
/// arrangement as SettingsWindow: it drives widgets inside the shared root.
///
/// Design "Mix":
///   level 0  : 種別を選択 title + big icon tiles (one per top-level branch)
///   level 1+ : the same tiles, small, as tabs + a 3-column grid of sounds
public class SoundWindow
{
    [UI] private Label  ConditionNameLabel = null;
    [UI] private Grid   SoundButtonGrid    = null;
    [UI] private Button SoundBackButton    = null;
    // NEW — optional, so an older glade without them still loads
    [UI] private Box    SoundTabBox        = null;
    [UI] private Label  SoundSubtitleLabel = null;

    private const int TopColumns  = 2;    // big tiles on level 0
    private const int ListColumns = 3;    // sound grid on level 1+
    private const int ListRowsFit = 7;    // more rows than this -> compact buttons
    private const int TopTileHeight = 400;

    // "fine crackle(捻髪音)" -> main "捻髪音", sub "fine crackle"
    private static readonly Regex NameRx = new Regex(@"^(.*?)\((.*)\)\s*$", RegexOptions.Compiled);

    // Subtitle per branch index (same index rule as the lung/heart colours)
    private static readonly string[] BranchSubtitles = { "Breath sounds", "Heart sounds" };

    private readonly List<CaseDefinition> _allCases;
    private readonly List<string> _path = new List<string>();

    /// Raised when the drill-down reaches a leaf case.
    public event EventHandler<CaseDefinition> CaseSelected;

    /// Raised when Back is pressed at the top level.
    public event EventHandler BackRequested;

    public SoundWindow(Builder builder)
    {
        builder.Autoconnect(this);
        if (ConditionNameLabel == null || SoundButtonGrid == null || SoundBackButton == null)
            throw new InvalidOperationException(
                "Glade id mismatch — ConditionNameLabel=" + (ConditionNameLabel != null) +
                " SoundButtonGrid=" + (SoundButtonGrid != null) +
                " SoundBackButton=" + (SoundBackButton != null));

        // GTK3 Builder does not set the CSS name from the glade id — do it here
        // so the #ConditionNameLabel / #SoundBackButton rules actually match.
        ConditionNameLabel.Name = "ConditionNameLabel";
        SoundButtonGrid.Name    = "SoundButtonGrid";
        SoundBackButton.Name    = "SoundBackButton";
        if (SoundSubtitleLabel != null) SoundSubtitleLabel.Name = "SoundSubtitleLabel";

Console.WriteLine("SoundWindow ctor: AppMode.Legacy = " + AppMode.Legacy);
        _allCases = AppMode.Legacy
            ? CaseDefinition.LoadLegacyCasesFromCsv(AppMode.CasesCsv)
            : CaseDefinition.LoadCasesFromCsv(AppMode.CasesCsv);

        if (_allCases.Count == 0)
            Console.WriteLine("WARNING: no cases loaded — check " + AppMode.CasesCsv);

        SoundBackButton.Clicked += OnBackClicked;
    }

    /// Call every time the page becomes visible.
    public void Reset()
    {
        _path.Clear();
        Render();
    }

    /// Resolve next to the .exe, NOT the working directory.
    public static string AppFile(string relative)
    {
        string dir = Path.GetDirectoryName(
            System.Reflection.Assembly.GetExecutingAssembly().Location);
        return Path.Combine(dir, relative);
    }

    // ── one method covers all three levels ─────────────────────────────

    private void Render()
    {
        var matches = _allCases.Where(MatchesPath).ToList();

        // Distinct values one level deeper than where we currently are.
        var options = matches
            .Where(c => c.TreePath.Length > _path.Count)
            .Select(c => c.TreePath[_path.Count])
            .Distinct()
            .ToList();

        UpdateHeader();

        BuildButtons(options, picked =>
        {
            _path.Add(picked);

            // Landed on a leaf? Play it and stay put.
            var leaf = _allCases.FirstOrDefault(
                c => c.TreePath.Length == _path.Count && MatchesPath(c));

            if (leaf != null)
            {
                Play(leaf);
                _path.RemoveAt(_path.Count - 1);
                return;
            }

            Render();
        });
    }

    private bool MatchesPath(CaseDefinition c)
    {
        string[] p = c.TreePath;
        if (p.Length < _path.Count) return false;
        for (int i = 0; i < _path.Count; i++)
            if (!string.Equals(p[i], _path[i], StringComparison.Ordinal)) return false;
        return true;
    }

    // ── header: title on level 0, tile tabs + hint below that ──────────

    private List<string> TopLevel()
    {
        // Colour by branch index rather than a literal, so renaming or
        // translating the CSV's top level doesn't silently turn everything blue.
        return _allCases
            .Where(c => c.TreePath.Length > 0)
            .Select(c => c.TreePath[0])
            .Distinct()
            .ToList();
    }

    private int CaseCount(string branch)
    {
        return _allCases.Count(c => c.TreePath.Length > 0 &&
                                    string.Equals(c.TreePath[0], branch, StringComparison.Ordinal));
    }

    private void UpdateHeader()
    {
        bool top = _path.Count == 0;
        var ctx = ConditionNameLabel.StyleContext;

        if (top)
        {
            ConditionNameLabel.Text = "種別を選択";
            ConditionNameLabel.Xalign = 0;
            ctx.RemoveClass("page-hint");
            ctx.AddClass("page-title");
        }
        else
        {
            // The tabs already say 呼吸音 / 心音; show deeper levels as a trail.
            ConditionNameLabel.Text = _path.Count == 1
                ? "音源をタッチして開始"
                : string.Join(" › ", _path.Skip(1));
            ConditionNameLabel.Xalign = 1;
            ctx.RemoveClass("page-title");
            ctx.AddClass("page-hint");
        }

        if (SoundSubtitleLabel != null) SoundSubtitleLabel.Visible = top;
        BuildTabs(top);
    }

    private void BuildTabs(bool top)
    {
        if (SoundTabBox == null) return;

        foreach (var child in SoundTabBox.Children)
        {
            SoundTabBox.Remove(child);
            child.Destroy();
        }

        SoundTabBox.Visible = !top;
        if (top) return;

        var branches = TopLevel();
        for (int k = 0; k < branches.Count; k++)
        {
            string branch = branches[k];
            bool active = string.Equals(branch, _path[0], StringComparison.Ordinal);

            var tab = MakeTypeTile(branch, k, active, true);
            tab.Clicked += (s, e) =>
            {
                if (_path.Count == 1 && active) return;      // already here
                _path.Clear();
                _path.Add(branch);
                Render();
            };
            // SoundTabBox is no-show-all (so a window-wide ShowAll can't reveal
            // it on level 0) — which also makes SoundTabBox.ShowAll() a no-op.
            // Show each tab itself instead.
            tab.ShowAll();
            SoundTabBox.PackStart(tab, false, false, 0);
        }
    }

    // ── buttons ────────────────────────────────────────────────────────

    private void BuildButtons(IEnumerable<string> labels, Action<string> onPick)
    {
        // MUST be first. Attach() stacks; without this every Render() adds a layer
        // of live buttons whose closures corrupt _path.
        foreach (var child in SoundButtonGrid.Children)
        {
            SoundButtonGrid.Remove(child);
            child.Destroy();
        }

        var list = labels.ToList();
        if (list.Count == 0) { SoundButtonGrid.ShowAll(); return; }

        bool top = _path.Count == 0;
        var branches = TopLevel();

        if (top)
        {
            // Level 0: big icon tiles, centred vertically.
            SoundButtonGrid.Valign        = Align.Center;
            SoundButtonGrid.ColumnSpacing = 28;
            SoundButtonGrid.RowSpacing    = 28;

            int i = 0;
            foreach (string text in list)
            {
                string captured = text;
                var tile = MakeTypeTile(captured, branches.IndexOf(captured), false, false);
                tile.HeightRequest = TopTileHeight;
                tile.Hexpand = true;
                tile.Clicked += (s, e) => onPick(captured);
                SoundButtonGrid.Attach(tile, i % TopColumns, i / TopColumns, 1, 1);
                i++;
            }
        }
        else
        {
            // Level 1+: 3-column grid, row by row.
            SoundButtonGrid.Valign        = Align.Start;
            SoundButtonGrid.ColumnSpacing = 10;
            SoundButtonGrid.RowSpacing    = 10;

            int rows     = (list.Count + ListColumns - 1) / ListColumns;
            bool compact = rows > ListRowsFit;
            int branchIx = branches.IndexOf(_path[0]);

            int i = 0;
            foreach (string text in list)
            {
                string captured = text;
                var btn = MakeClipButton(captured, branchIx, compact);
                btn.Clicked += (s, e) => onPick(captured);
                SoundButtonGrid.Attach(btn, i % ListColumns, i / ListColumns, 1, 1);
                i++;
            }
        }

        SoundButtonGrid.ShowAll();
    }

    /// Big tile (level 0) or small tab (level 1+): icon + name + subtitle.
    private Button MakeTypeTile(string name, int branchIx, bool active, bool small)
    {
        var btn = new Button();
        var ctx = btn.StyleContext;
        ctx.AddClass(small ? "type-tab" : "type-tile");
        if (branchIx == 0)      ctx.AddClass("lung");
        else if (branchIx == 1) ctx.AddClass("heart");
        if (active)             ctx.AddClass("active");

        var icon = new SoundIcon(branchIx == 1 ? SoundIcon.Kind.Heart : SoundIcon.Kind.Lungs,
                                 small ? 54 : 140, active);

        string sub = (branchIx >= 0 && branchIx < BranchSubtitles.Length
                        ? BranchSubtitles[branchIx] + " · " : "")
                     + CaseCount(name) + " 音源";

        var title = new Label(name);
        title.StyleContext.AddClass("tile-title");
        var subtitle = new Label(sub);
        subtitle.StyleContext.AddClass("tile-sub");

        if (small)
        {
            title.Xalign = 0;
            subtitle.Xalign = 0;
            var text = new Box(Orientation.Vertical, 0);
            text.Valign = Align.Center;
            text.PackStart(title, false, false, 0);
            text.PackStart(subtitle, false, false, 0);

            var row = new Box(Orientation.Horizontal, 14);
            icon.Valign = Align.Center;
            row.PackStart(icon, false, false, 0);
            row.PackStart(text, false, false, 0);
            btn.Add(row);
        }
        else
        {
            var col = new Box(Orientation.Vertical, 18);
            col.Halign = Align.Center;
            col.Valign = Align.Center;
            icon.Halign = Align.Center;
            col.PackStart(icon, false, false, 0);
            col.PackStart(title, false, false, 0);
            col.PackStart(subtitle, false, false, 0);
            btn.Add(col);
        }
        return btn;
    }

    /// White card: Japanese name bold on top, English name small below.
    private Button MakeClipButton(string text, int branchIx, bool compact)
    {
        string main = text, sub = null;
        var m = NameRx.Match(text);
        if (m.Success && m.Groups[2].Value.Trim().Length > 0)
        {
            main = m.Groups[2].Value.Trim();
            sub  = m.Groups[1].Value.Trim();
        }

        var btn = new Button();
        btn.Hexpand = true;
        btn.Vexpand = false;
        btn.TooltipText = text;

        var ctx = btn.StyleContext;
        ctx.AddClass("sound-clip");
        if (compact)            ctx.AddClass("compact");
        if (branchIx == 0)      ctx.AddClass("lung");
        else if (branchIx == 1) ctx.AddClass("heart");

        var col = new Box(Orientation.Vertical, 2);
        col.Valign = Align.Center;

        var l1 = new Label(main);
        l1.Xalign = 0;
        l1.Ellipsize = Pango.EllipsizeMode.End;
        l1.StyleContext.AddClass("clip-main");
        col.PackStart(l1, false, false, 0);

        if (!string.IsNullOrEmpty(sub))
        {
            var l2 = new Label(sub);
            l2.Xalign = 0;
            l2.Ellipsize = Pango.EllipsizeMode.End;
            l2.StyleContext.AddClass("clip-sub");
            col.PackStart(l2, false, false, 0);
        }

        btn.Add(col);
        return btn;
    }

    private void Play(CaseDefinition c)
    {
        if (c.IsLegacy)
        {
            // Legacy audio lives in RegionSounds[0..6], not SoundPath
            int found = 0;
            for (int k = 0; k < 7; k++)
            {
                string p = AppMode.ResolveSound(c.RegionSounds[k]);
                if (p == null) continue;                       // "none" / empty = region disabled
                if (File.Exists(p)) found++;
                else Console.WriteLine("Region " + k + " sound missing for case " + c.Number + ": " + p);
            }
            if (found == 0)
            {
                Console.WriteLine("No region sounds found for legacy case " + c.Number);
                return;
            }
        }
        else if (string.IsNullOrWhiteSpace(c.SoundPath))
        {
            Console.WriteLine("No Sound_File for case " + c.Number);
            return;
        }

        WavePlayer.Stop();   // the map page owns audio from here on

        var h = CaseSelected;
        if (h != null) h(this, c);

        if (!c.IsLegacy)
        {
            string full = AppMode.ResolveSound(c.SoundPath);
            if (full == null || !File.Exists(full))
                Console.WriteLine("Sound file missing for case " + c.Number);
        }
    }

    private void OnBackClicked(object sender, EventArgs e)
    {
        if (_path.Count > 0)
        {
            _path.RemoveAt(_path.Count - 1);
            Render();
        }
        else
        {
            WavePlayer.Stop();
            if (BackRequested != null) BackRequested(this, EventArgs.Empty);
        }
    }
}

/// Lungs / heart icon in a circle, drawn with Cairo (no image files needed).
/// Inactive: tinted circle + coloured stroke. Active: solid circle + white stroke.
public class SoundIcon : DrawingArea
{
    public enum Kind { Lungs, Heart }

    private readonly Kind _kind;
    private readonly bool _active;

    public SoundIcon(Kind kind, int size, bool active)
    {
        _kind = kind;
        _active = active;
        SetSizeRequest(size, size);
        Drawn += OnDrawn;
    }

    private void OnDrawn(object o, DrawnArgs args)
    {
        var cr = args.Cr;
        int w = AllocatedWidth, h = AllocatedHeight;
        double s = Math.Min(w, h);

        bool heart = _kind == Kind.Heart;
        double r = heart ? 0.753 : 0.122, g = heart ? 0.224 : 0.435, b = heart ? 0.169 : 0.698;   // #C0392B / #1F6FB2

        // circle
        cr.Arc(w / 2.0, h / 2.0, s / 2.0, 0, 2 * Math.PI);
        if (_active) cr.SetSourceRGB(r, g, b);
        else if (heart) cr.SetSourceRGB(0.984, 0.906, 0.906);   // #FBE7E7
        else cr.SetSourceRGB(0.890, 0.933, 0.976);              // #E3EEF9
        cr.Fill();

        // glyph, authored on a 64x64 grid, scaled to 60% of the circle
        double k = s * 0.6 / 64.0;
        cr.Save();
        cr.Translate((w - 64 * k) / 2.0, (h - 64 * k) / 2.0);
        cr.Scale(k, k);
        cr.LineWidth = 3.2;
        cr.LineCap = Cairo.LineCap.Round;
        cr.LineJoin = Cairo.LineJoin.Round;
        if (_active) cr.SetSourceRGB(1, 1, 1);
        else cr.SetSourceRGB(r, g, b);

        if (heart) HeartPath(cr); else LungsPath(cr);
        cr.Stroke();
        cr.Restore();

        args.RetVal = true;
    }

    private static void LungsPath(Cairo.Context cr)
    {
        // trachea + bronchi
        cr.MoveTo(32, 6);  cr.LineTo(32, 28);
        cr.MoveTo(32, 28); cr.CurveTo(29, 28, 26, 31, 24, 31);
        cr.MoveTo(32, 28); cr.CurveTo(35, 28, 38, 31, 40, 31);
        // left lobe
        cr.MoveTo(24, 31);
        cr.CurveTo(22, 23, 18, 18, 14, 18);
        cr.CurveTo(8, 18, 5, 30, 5, 42);
        cr.CurveTo(5, 51, 8, 57, 14, 57);
        cr.CurveTo(21, 57, 24, 52, 24, 45);
        cr.ClosePath();
        // right lobe
        cr.MoveTo(40, 31);
        cr.CurveTo(42, 23, 46, 18, 50, 18);
        cr.CurveTo(56, 18, 59, 30, 59, 42);
        cr.CurveTo(59, 51, 56, 57, 50, 57);
        cr.CurveTo(43, 57, 40, 52, 40, 45);
        cr.ClosePath();
    }

    private static void HeartPath(Cairo.Context cr)
    {
        cr.MoveTo(32, 54);
        cr.CurveTo(32, 54, 8, 40, 8, 22);
        cr.CurveTo(8, 14, 14, 9, 20, 9);
        cr.CurveTo(25, 9, 29, 12, 32, 16);
        cr.CurveTo(35, 12, 39, 9, 44, 9);
        cr.CurveTo(50, 9, 56, 14, 56, 22);
        cr.CurveTo(56, 40, 32, 54, 32, 54);
        cr.ClosePath();
        // ECG trace
        cr.MoveTo(14, 30);
        cr.LineTo(24, 30);
        cr.LineTo(28, 23);
        cr.LineTo(34, 37);
        cr.LineTo(38, 30);
        cr.LineTo(50, 30);
    }
}