package processors

import (
	"fmt"
	"strings"

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

// NavigationProcessor processes navigation items
type NavigationProcessor struct{}

// NewNavigationProcessor creates a new navigation processor
func NewNavigationProcessor() *NavigationProcessor {
	return &NavigationProcessor{}
}

// ProcessNavigationItems converts Appy navigation items to template format
func (n *NavigationProcessor) ProcessNavigationItems(items []models.NavigationItem) []templateModels.NavItem {
	result := make([]templateModels.NavItem, 0, len(items))

	for i, item := range items {
		navItem := templateModels.NavItem{
			Label:      item.Label,
			Icon:       n.mapIconToMaterial(item.Icon),
			IconImport: n.getIconImport(item.Icon),
			ActionType: item.ActionType,
			URL:        item.URL,
			Route:      n.generateRoute(item.Label, i),
		}

		result = append(result, navItem)
	}

	return result
}

// mapIconToMaterial maps Appy icon names to Material Icons
func (n *NavigationProcessor) mapIconToMaterial(appyIcon string) string {
	iconMap := map[string]string{
		"home":          "Icons.Default.Home",
		"shopping-cart": "Icons.Default.ShoppingCart",
		"heart":         "Icons.Default.Favorite",
		"flame":         "Icons.Default.Whatshot",
		"newspaper":     "Icons.Default.Article",
		"server":        "Icons.Default.Storage",
		"mobile":        "Icons.Default.PhoneAndroid",
		"globe":         "Icons.Default.Language",
		"chart":         "Icons.Default.BarChart",
		"info":          "Icons.Default.Info",
		"user":          "Icons.Default.Person",
		"settings":      "Icons.Default.Settings",
		"mail":          "Icons.Default.Email",
	}

	if materialIcon, ok := iconMap[appyIcon]; ok {
		return materialIcon
	}

	// Default fallback
	return "Icons.Default.Circle"
}

// getIconImport returns the import statement for an icon (if needed)
func (n *NavigationProcessor) getIconImport(appyIcon string) string {
	// Icons.Default.* are all in androidx.compose.material.icons.filled
	// which is already imported in templates
	// Special icons might need additional imports in the future
	return ""
}

// generateRoute generates a route name from label
func (n *NavigationProcessor) generateRoute(label string, index int) string {
	// Convert label to lowercase, replace spaces with underscores
	route := strings.ToLower(label)
	route = strings.ReplaceAll(route, " ", "_")
	route = strings.ReplaceAll(route, "-", "_")

	// Remove special characters
	result := ""
	for _, char := range route {
		if (char >= 'a' && char <= 'z') || (char >= '0' && char <= '9') || char == '_' {
			result += string(char)
		}
	}

	if result == "" {
		result = fmt.Sprintf("tab_%d", index)
	}

	return result
}

// FindHomeItem finds the home navigation item
func (n *NavigationProcessor) FindHomeItem(items []templateModels.NavItem) *templateModels.NavItem {
	for i := range items {
		if items[i].IsHome {
			return &items[i]
		}
	}

	// If no explicit home, return first item
	if len(items) > 0 {
		return &items[0]
	}

	return nil
}

// GenerateDefaultNavigationItems creates default navigation items if none provided
func (n *NavigationProcessor) GenerateDefaultNavigationItems(layoutTemplate string) []templateModels.NavItem {
	switch layoutTemplate {
	case "app_bar_tabs", "tabs":
		return []templateModels.NavItem{
			{Label: "Home", Icon: "Icons.Default.Home", Route: "home", ActionType: "internal", IsHome: true},
		}
	case "app_bar_drawer", "drawer":
		return []templateModels.NavItem{
			{Label: "Home", Icon: "Icons.Default.Home", Route: "home", ActionType: "internal", IsHome: true},
		}
	default:
		return []templateModels.NavItem{}
	}
}

// ValidateNavigationItems validates and fixes navigation items
func (n *NavigationProcessor) ValidateNavigationItems(items []templateModels.NavItem) []templateModels.NavItem {
	if len(items) == 0 {
		return items
	}

	// Track used routes to prevent duplicates
	usedRoutes := make(map[string]bool)
	validated := make([]templateModels.NavItem, 0, len(items))

	for i := range items {
		item := items[i]

		// Skip items with empty labels
		if strings.TrimSpace(item.Label) == "" {
			continue
		}

		// Trim label to max 20 characters for better UI
		if len(item.Label) > 20 {
			item.Label = item.Label[:17] + "..."
		}

		// Ensure route is unique
		originalRoute := item.Route
		counter := 1
		for usedRoutes[item.Route] {
			item.Route = fmt.Sprintf("%s_%d", originalRoute, counter)
			counter++
		}
		usedRoutes[item.Route] = true

		// Validate URL for external/share/email/call actions
		if item.ActionType == "external" || item.ActionType == "share" {
			if item.URL == "" {
				// Skip items with invalid URLs
				continue
			}
		}

		validated = append(validated, item)
	}

	// Cap to reasonable limits (5 for tabs, 10 for drawer)
	// Calling code should specify limit, but we'll cap at 10 as absolute max
	if len(validated) > 10 {
		validated = validated[:10]
	}

	// Ensure at least one home item if we have any items
	if len(validated) > 0 {
		hasHome := false
		homeIndex := -1
		for i := range validated {
			if validated[i].IsHome {
				hasHome = true
				homeIndex = i
				break
			}
		}

		if !hasHome {
			// Home tab should always be at index 0
			// If missing, mark first item as home
			validated[0].IsHome = true
			validated[0].Route = "home"
		} else if homeIndex > 0 {
			// Ensure home tab is at index 0
			// Move home to index 0 if it's not already there
			homeItem := validated[homeIndex]
			validated = append(validated[:homeIndex], validated[homeIndex+1:]...)
			validated = append([]templateModels.NavItem{homeItem}, validated...)
		}
	}

	return validated
}
