package testing

import (
	"math/rand"
	"time"

	"github.com/titansys/appy-builder/internal/models"
)

// RandomTestHelper generates random build configurations for testing
type RandomTestHelper struct {
	rand *rand.Rand
}

// NewRandomTestHelper creates a new random test helper
func NewRandomTestHelper() *RandomTestHelper {
	return &RandomTestHelper{
		rand: rand.New(rand.NewSource(time.Now().UnixNano())),
	}
}

// NewRandomTestHelperWithSeed creates a new random test helper with a specific seed (for reproducible tests)
func NewRandomTestHelperWithSeed(seed int64) *RandomTestHelper {
	return &RandomTestHelper{
		rand: rand.New(rand.NewSource(seed)),
	}
}

var (
	templates        = []string{"blank", "app_bar", "app_bar_tabs", "app_bar_drawer"}
	platforms        = []string{"android-webview"}
	splashAnimations = []string{"none", "fade", "slide", "zoom"}
	textThemes       = []string{"light", "dark"}
	backgroundTypes  = []string{"color", "image"}
	icons            = []string{"home", "search", "person", "settings", "notifications", "info", "mail", "favorite"}
	actionTypes      = []string{"internal", "external"}
	internalURLs     = []string{"/", "/home", "/search", "/profile", "/settings", "/about"}
	externalURLs     = []string{"https://example.com", "https://google.com"}
	splashTitles     = []string{"", "Welcome", "Hello", "Loading", "Please Wait", "Get Started"}
	splashSubtitles  = []string{"", "Just a moment", "Loading your app", "Please wait", "Almost ready"}
)

// RandomTemplate returns a random template name
func (r *RandomTestHelper) RandomTemplate() string {
	return templates[r.rand.Intn(len(templates))]
}

// RandomPlatform returns a random platform
func (r *RandomTestHelper) RandomPlatform() string {
	return platforms[r.rand.Intn(len(platforms))]
}

// RandomSplashAnimation returns a random splash animation type
func (r *RandomTestHelper) RandomSplashAnimation() string {
	return splashAnimations[r.rand.Intn(len(splashAnimations))]
}

// RandomBool returns a random boolean value
func (r *RandomTestHelper) RandomBool() bool {
	return r.rand.Intn(2) == 1
}

// RandomColor returns a random hex color
func (r *RandomTestHelper) RandomColor() string {
	return "#" + randomHex(r.rand, 6)
}

// RandomTextTheme returns a random text theme
func (r *RandomTestHelper) RandomTextTheme() string {
	return textThemes[r.rand.Intn(len(textThemes))]
}

// RandomBackgroundType returns a random background type
func (r *RandomTestHelper) RandomBackgroundType() string {
	return backgroundTypes[r.rand.Intn(len(backgroundTypes))]
}

// RandomDuration returns a random duration between 1-5 seconds
func (r *RandomTestHelper) RandomDuration() int {
	return 1 + r.rand.Intn(5)
}

// RandomString returns a random string from a predefined list
func (r *RandomTestHelper) RandomString(allowEmpty bool) string {
	if allowEmpty {
		return splashTitles[r.rand.Intn(len(splashTitles))]
	}
	// Filter out empty strings
	nonEmpty := []string{}
	for _, s := range splashTitles {
		if s != "" {
			nonEmpty = append(nonEmpty, s)
		}
	}
	return nonEmpty[r.rand.Intn(len(nonEmpty))]
}

// RandomIcon returns a random icon name
func (r *RandomTestHelper) RandomIcon() string {
	return icons[r.rand.Intn(len(icons))]
}

// RandomActionType returns a random action type
func (r *RandomTestHelper) RandomActionType() string {
	return actionTypes[r.rand.Intn(len(actionTypes))]
}

// RandomURL returns a random URL based on action type
func (r *RandomTestHelper) RandomURL(actionType string) string {
	if actionType == "external" {
		return externalURLs[r.rand.Intn(len(externalURLs))]
	}
	return internalURLs[r.rand.Intn(len(internalURLs))]
}

// GenerateRandomNavigationItems generates 1-5 random navigation items
func (r *RandomTestHelper) GenerateRandomNavigationItems() []models.NavigationItem {
	count := 1 + r.rand.Intn(5)
	items := make([]models.NavigationItem, count)

	for i := 0; i < count; i++ {
		actionType := r.RandomActionType()
		items[i] = models.NavigationItem{
			Label:      "Item " + string(rune('A'+i)),
			Icon:       r.RandomIcon(),
			ActionType: actionType,
			URL:        r.RandomURL(actionType),
		}
	}

	return items
}

// GenerateRandomAppBarButtons generates 0-3 random app bar buttons
func (r *RandomTestHelper) GenerateRandomAppBarButtons() []models.NavigationItem {
	count := r.rand.Intn(4)
	if count == 0 {
		return nil
	}

	buttons := make([]models.NavigationItem, count)

	for i := 0; i < count; i++ {
		actionType := r.RandomActionType()
		buttons[i] = models.NavigationItem{
			Icon:       r.RandomIcon(),
			ActionType: actionType,
			URL:        r.RandomURL(actionType),
		}
	}

	return buttons
}

// GenerateRandomBuildRequest creates a random build request for testing
func (r *RandomTestHelper) GenerateRandomBuildRequest() models.BuildRequest {
	template := r.RandomTemplate()
	platform := r.RandomPlatform()

	config := models.BuildConfig{
		LayoutTemplate:         template,
		SplashAnimation:        r.RandomSplashAnimation(),
		SplashTitle:            splashTitles[r.rand.Intn(len(splashTitles))],
		SplashSubtitle:         splashSubtitles[r.rand.Intn(len(splashSubtitles))],
		SplashLogoEnabled:      r.RandomBool(),
		SplashDelay:            r.RandomDuration(),
		SplashBackgroundType:   r.RandomBackgroundType(),
		SplashBackground:       r.RandomColor(),
		SplashTextColorMode:    r.RandomTextTheme(),
		DrawerLogoEnabled:      r.RandomBool(),
		DrawerTextColorMode:    r.RandomTextTheme(),
		DrawerTitle:            splashTitles[r.rand.Intn(len(splashTitles))],
		DrawerSubtitle:         splashSubtitles[r.rand.Intn(len(splashSubtitles))],
		PullToRefresh:          r.RandomBool(),
		SwipeNavigation:        r.RandomBool(),
		ShowPageTitle:          r.RandomBool(),
		ThemeColor:             r.RandomColor(),
		AppName:                "Test App",
		AppID:                  "com.test.randomapp",
		WebsiteURL:             "https://example.com",
		AndroidVersionName:     "1.0.0",
		PermissionLocation:     r.RandomBool(),
		PermissionCamera:       r.RandomBool(),
		PermissionStorage:      r.RandomBool(),
		PermissionRecordAudio:  r.RandomBool(),
		PermissionReadContacts: r.RandomBool(),
		PermissionVibrate:      r.RandomBool(),
	}

	// Add navigation items for tabs/drawer templates
	if template == "app_bar_tabs" || template == "app_bar_drawer" {
		config.BottomTabs = r.GenerateRandomNavigationItems()
	}

	// Add app bar buttons for non-blank templates
	if template != "blank" {
		config.AppBarButtons = r.GenerateRandomAppBarButtons()
	}

	req := models.BuildRequest{
		ID:        string(rune(r.rand.Int())),
		Platform:  platform,
		BuildType: "debug",
		Config:    config,
	}

	return req
}

// GenerateRandomBuildRequests generates multiple random build requests
func (r *RandomTestHelper) GenerateRandomBuildRequests(count int) []models.BuildRequest {
	requests := make([]models.BuildRequest, count)
	for i := 0; i < count; i++ {
		requests[i] = r.GenerateRandomBuildRequest()
	}
	return requests
}

// Helper functions

func randomHex(r *rand.Rand, n int) string {
	const hexChars = "0123456789ABCDEF"
	result := make([]byte, n)
	for i := 0; i < n; i++ {
		result[i] = hexChars[r.Intn(len(hexChars))]
	}
	return string(result)
}
