package ui

import (
	"errors"
	"fmt"
	"strings"
	"time"

	"fes/modules/config"

	"github.com/fatih/color"
)

const (
	hintColor = 0xbda02a
)

func formatTimestamp() string {
	return time.Now().Format("02 Jan 2006 15:04")
}

func logMessage(prefix string, msg string, args ...any) {
	formatted := fmt.Sprintf(msg, args...)
	if prefix == "" {
		fmt.Printf("%s * %s\n", formatTimestamp(), formatted)
	} else {
		fmt.Printf("%s * %s: %s\n", formatTimestamp(), prefix, formatted)
	}
}

// Generic log
func Log(msg string, args ...any) {
	logMessage("", msg, args...)
}

// OK message (green)
func OK(msg string, args ...any) {
	formatted := fmt.Sprintf(msg, args...)
	color.Green("%s * %s\n", formatTimestamp(), formatted)
}

// Warning message (magenta)
func WARN(msg string, args ...any) {
	formatted := fmt.Sprintf(msg, args...)
	color.Magenta("%s # %s\n", formatTimestamp(), formatted)
}

// Warning message (magenta)
func WARNING(msg string, args ...any) {
	formatted := fmt.Sprintf(msg, args...)
	color.Magenta("%s # WARNING %s\n", formatTimestamp(), formatted)
}

// Error message (red)
func ERROR(msg string, args ...any) {
	formatted := fmt.Sprintf(msg, args...)
	color.Red("%s ! %s\n", formatTimestamp(), formatted)
}

// Fatal message and panic
func FATAL(msg string, args ...any) {
	formatted := fmt.Sprintf(msg, args...)
	color.Red("%s % %s\n", formatTimestamp(), formatted)
	panic(formatted)
}

// Hint message (custom color)
func Hint(msg string, args ...any) {
	formatted := fmt.Sprintf(msg, args...)
	color.RGB(func(hex int) (r, g, b int) {
		r = (hex >> 16) & 0xFF
		g = (hex >> 8) & 0xFF
		b = hex & 0xFF
		return
	}(hintColor)).Printf("hint: %s\n", formatted)
}

// Path logging: prints route and status
func Path(path string, err error) {
	path = strings.TrimPrefix(path, "/")
	if path == "" {
		path = "(null)"
	}

	if err == nil {
		OK("Route: %s - ok", path)
	} else if errors.Is(err, config.ErrRouteMiss) {
		WARN("Route: %s - %s", path, config.ErrRouteMiss.Error())
	} else {
		ERROR("Route: %s - bad", path)
	}
}

// System warning with prefix
func Warning(msg string, err error) error {
	WARN("%s: %v", msg, err)
	return err
}

// System error with prefix
func Error(msg string, err error) error {
	ERROR("%s: %v", msg, err)
	return err
}

// Fatal system error
func Fatal(msg string, err error) error {
	FATAL("%s: %v", msg, err)
	return err
}

// Log on Verbose
func LogVerbose(msg string, args ...any) {
	if *config.Verbose {
		Log(msg, args...)
	}
}
