package ui

import (
	"fmt"
	"os"
	"path/filepath"
	"syscall"
	"testing"
	"time"

	tea "github.com/charmbracelet/bubbletea"
	"github.com/charmbracelet/lipgloss"
	"github.com/muesli/termenv"

	"vcom/internal/config"
	vfs "vcom/internal/fs"
)

var scratch = os.Getenv("VCOM_SCRATCH")

func newTestModel(t testing.TB, left, right string) Model {
	t.Helper()
	os.Setenv("XDG_CONFIG_HOME", filepath.Join(scratch, "xdg"))
	os.Setenv("HOME", filepath.Join(scratch, "home"))
	os.MkdirAll(filepath.Join(scratch, "home"), 0o755)
	cfg := config.Default()
	cfg.UI.IconMode = "ascii"
	cfg.Startup.LeftPath = left
	cfg.Startup.RightPath = right
	m, err := NewModel(cfg, "")
	if err != nil {
		t.Fatal(err)
	}
	mm, _ := m.Update(tea.WindowSizeMsg{Width: 200, Height: 60})
	return asM(mm)
}

func kk(s string) tea.KeyMsg {
	switch s {
	case "enter":
		return tea.KeyMsg{Type: tea.KeyEnter}
	case "esc":
		return tea.KeyMsg{Type: tea.KeyEsc}
	case "pgdown":
		return tea.KeyMsg{Type: tea.KeyPgDown}
	}
	return tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune(s)}
}

// 1. Caret mode panics when color profile is Ascii (NO_COLOR / non-tty).
func TestCaretPanicAscii(t *testing.T) {
	lipgloss.SetColorProfile(termenv.Ascii)
	m := newTestModel(t, scratch, scratch)
	m.previewData = vfs.Preview{Kind: vfs.PreviewKindText, Body: "hello\nworld", PlainBody: "hello\nworld"}
	m.infoMode = true
	defer func() {
		if r := recover(); r != nil {
			t.Logf("CONFIRMED PANIC in caret mode with Ascii profile: %v", r)
		}
	}()
	m.toggleCaretMode()
	t.Logf("no panic")
}

// 2. PgDown does nothing.
func TestPageDown(t *testing.T) {
	m := newTestModel(t, filepath.Join(scratch, "big"), scratch)
	before := m.left.Cursor
	mm, _ := m.Update(kk("pgdown"))
	t.Logf("PgDown: cursor before=%d after=%d", before, asM(mm).left.Cursor)
}

// 3. Cyrillic typed into rename modal is converted to latin.
func TestCyrillicInMkdir(t *testing.T) {
	m := newTestModel(t, scratch, scratch)
	m.openMkdirModal()
	var mm tea.Model = m
	for _, r := range "папка" {
		mm, _ = asM(mm).Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{r}})
	}
	t.Logf("typed 'папка' into mkdir modal -> input value=%q", asM(mm).modal.input.Value())
}

// 4. 'q' in normal mode quits even when filter/info is active.
func TestQQuits(t *testing.T) {
	m := newTestModel(t, scratch, scratch)
	m.infoMode = true
	_, cmd := m.Update(kk("q"))
	if cmd != nil {
		msg := cmd()
		_, isQuit := msg.(tea.QuitMsg)
		t.Logf("q with info pane open -> quit=%v", isQuit)
	}
}

// 5. Symlinked directory: category and enter.
func TestSymlinkDir(t *testing.T) {
	d := filepath.Join(scratch, "symt")
	os.RemoveAll(d)
	os.MkdirAll(filepath.Join(d, "realdir"), 0o755)
	os.Symlink(filepath.Join(d, "realdir"), filepath.Join(d, "linkdir"))
	entries, _ := vfs.ListDir(d, vfs.ListOptions{ShowHidden: true, DirsFirst: true, SortBy: "name"})
	for _, e := range entries {
		t.Logf("entry %q isDir=%v category=%s", e.Name, e.IsDir, e.Category())
	}
}

// 6. Filter + mouse click mismatch.
func TestFilterMouse(t *testing.T) {
	d := filepath.Join(scratch, "filt")
	os.RemoveAll(d)
	os.MkdirAll(d, 0o755)
	for _, n := range []string{"a1", "b1", "b2", "c1", "zz-target"} {
		os.WriteFile(filepath.Join(d, n), []byte("x"), 0o644)
	}
	m := newTestModel(t, d, d)
	m.filterQuery = "zz"
	m.filterPaneID = PaneLeft
	// visible rows: ".." then "zz-target" (2nd row) at y = 3 + 1
	mm, _ := m.Update(tea.MouseMsg{X: 5, Y: 4, Action: tea.MouseActionPress, Button: tea.MouseButtonLeft})
	mm2 := asM(mm); sel, _ := mm2.left.Selected()
	t.Logf("filter=zz, clicked 2nd visible row (zz-target), real selection=%q", sel.Name)
}

// 7. Filter not reset on directory change, and cursor on hidden entry.
func TestFilterHiddenSelection(t *testing.T) {
	d := filepath.Join(scratch, "filt")
	m := newTestModel(t, d, d)
	m.left.Cursor = 2 // b1
	m.filterQuery = "nomatch"
	m.filterPaneID = PaneLeft
	m.snapFilterCursor()
	sel, _ := m.left.Selected()
	fp := m.filteredPane(m.left)
	t.Logf("filter with no match: visible=%d, real selected=%q (operations would target it)", len(fp.Entries), sel.Name)
}

// 8. Preview stale for empty dir ("Nothing selected" never applied).
func TestEmptyDirPreview(t *testing.T) {
	d := filepath.Join(scratch, "emptyroot")
	os.MkdirAll(d, 0o755)
	m := newTestModel(t, scratch, scratch)
	m.previewData = vfs.Preview{Kind: vfs.PreviewKindText, Title: "OLD"}
	m.left.Entries = nil
	msg := m.loadPreviewCmd()()
	mm, _ := m.Update(msg)
	t.Logf("empty pane preview title after previewMsg: %q", asM(mm).previewData.Title)
}

// 9. Passive pane cursor reset after operation reload.
func TestPassiveCursorReset(t *testing.T) {
	d := filepath.Join(scratch, "big")
	m := newTestModel(t, filepath.Join(scratch, "filt"), d)
	m.right.Cursor = 500
	_ = m.reloadPane(PaneRight, selectedName(&m.left))
	t.Logf("passive pane cursor after reload with active selection name: 500 -> %d", m.right.Cursor)
}

// 10. FIFO preview blocks.
func TestFifoPreview(t *testing.T) {
	p := filepath.Join(scratch, "fifo")
	os.Remove(p)
	if err := syscall.Mkfifo(p, 0o644); err != nil {
		t.Skip(err)
	}
	info, _ := os.Lstat(p)
	e := vfs.Entry{Name: "fifo", Path: p, Mode: info.Mode()}
	done := make(chan struct{})
	go func() { vfs.BuildPreview(e, vfs.PreviewOptions{MaxPreviewBytes: 65536}); close(done) }()
	select {
	case <-done:
		t.Logf("fifo preview returned")
	case <-time.After(2 * time.Second):
		t.Logf("CONFIRMED: BuildPreview on FIFO blocked >2s (goroutine leak)")
	}
}

// 11. Delete toggle default
func TestDeleteDefault(t *testing.T) {
	d := filepath.Join(scratch, "filt")
	m := newTestModel(t, d, d)
	m.left.Cursor = 1
	m.handleDelete()
	t.Logf("delete modal title=%q deleteKind=%s", m.modal.title, m.deleteKind)
	_, _ = m.handleModalKey(kk("n"))
	t.Logf("after 'n' modal kind still=%d (0=closed)", m.modal.kind)
}

func benchModel(b *testing.B) Model {
	return newTestModel(b, filepath.Join(scratch, "big"), filepath.Join(scratch, "big"))
}

func BenchmarkView20k(b *testing.B) {
	lipgloss.SetColorProfile(termenv.TrueColor)
	m := benchModel(b)
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		_ = m.View()
	}
}

func BenchmarkView20kFiltered(b *testing.B) {
	lipgloss.SetColorProfile(termenv.TrueColor)
	m := benchModel(b)
	m.filterQuery = "file_1"
	m.filterPaneID = PaneLeft
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		_ = m.View()
	}
}

func BenchmarkKeyDownUpdateView(b *testing.B) {
	lipgloss.SetColorProfile(termenv.TrueColor)
	m := benchModel(b)
	b.ResetTimer()
	var mm tea.Model = m
	for i := 0; i < b.N; i++ {
		mm, _ = asM(mm).Update(kk("j"))
		_ = mm.View()
	}
}

func BenchmarkReloadPane20k(b *testing.B) {
	m := benchModel(b)
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		_ = m.reloadPane(PaneLeft, "")
	}
}

func BenchmarkCaretMove64k(b *testing.B) {
	lipgloss.SetColorProfile(termenv.TrueColor)
	m := newTestModel(b, scratch, scratch)
	src, _ := os.ReadFile(filepath.Join(scratch, "big.go"))
	p := vfs.BuildPreview(vfs.Entry{Name: "big.go", Path: filepath.Join(scratch, "big.go"), Extension: "go", Size: int64(len(src))}, vfs.PreviewOptions{MaxPreviewBytes: 65536, ThemeName: "catppuccin-mocha"})
	m.infoMode = true
	m.resizePreview()
	m.applyPreview(p)
	m.toggleCaretMode()
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		m.moveTextCursorLine(1)
	}
}

func BenchmarkKittyPayload(b *testing.B) {
	path := filepath.Join(scratch, "big.png")
	for i := 0; i < b.N; i++ {
		_, _, err := loadKittyPayload(path, overlayRect{width: 80, height: 40})
		if err != nil {
			b.Fatal(err)
		}
	}
}

var _ = fmt.Sprintf

func asM(x tea.Model) Model {
	if p, ok := x.(*Model); ok {
		return *p
	}
	return x.(Model)
}
