package tui

import (
	"encoding/base64"
	"fmt"
	"log"
	"strings"
	"time"

	"whspbrd/pkg/cell_size"
	"whspbrd/pkg/clean_image"
	"whspbrd/pkg/render_image"

	"github.com/jroimartin/gocui"
)

func updateChatView(v *gocui.View) {
	v.Clear()

	clear := cleanimage.NewKittyImageCleaner()
	// TODO: In future optimize this to only clear certain part of screen
	fmt.Print(clear.DeleteByColumn(23, false))

	for i, msg := range chatData.Messages {
		decoded, err := base64.StdEncoding.DecodeString(msg.Content)
		if err != nil {
			log.Printf("Error decoding message: %v", err)
			continue
		}
		if strings.HasSuffix(string(decoded), "\n") {
			decoded = []byte(strings.TrimSuffix(string(decoded), "\n"))
		}

		t, _ := time.Parse(time.RFC3339, msg.Timestamp)
		formattedTime := t.Format("2006-01-02 15:04")

		w, h, err := cell_size.GetTerminalCellSizePixels()
		if err != nil {
			log.Println("Error getting terminal cell size:", err)
			continue
		}
		if h > w {
			h = h * 2
			w = 0
		} else {
			w = w*3 - (w / 10)
			h = 0
		}
		if !strings.EqualFold(msg.Sender, users[selectedUserIdx]) {

			fmt.Fprintf(v, "%s", "\t\t\t\t\t"+Colors.Text(Colors.Base02)+"You ("+formattedTime+"):"+Colors.Reset+"\n\t\t\t\t\t"+string(decoded)+"\n\n")
			render_image.RenderImage("./configs/icon.png", i*3+2, 23, w, h, false)

		} else {
			fmt.Fprintf(v, "%s", "\t\t\t\t\t"+Colors.Text(Colors.Base05)+msg.Sender+" ("+formattedTime+"):"+Colors.Reset+"\n\t\t\t\t\t"+string(decoded)+"\n\n")
			icon_path := fmt.Sprintf("./configs/servers/default/users/%s/icon.png", strings.ToLower(msg.Sender))
			render_image.RenderImage(icon_path, i*3+2, 23, w, h, false)
		}
	}
}

// TODO: Rewrite This Code
func sendMessage(g *gocui.Gui, v *gocui.View) error {
	input := v.Buffer()
	v.Clear()
	v.SetCursor(0, 0)
	v.SetOrigin(0, 0)

	WriteMessage(users[selectedUserIdx], "You", users[selectedUserIdx], input)
	LoadMessages(users[selectedUserIdx])

	updateChatView(g.Views()[1])
	return nil
}
