package web

import (
	"net/http"
	"strconv"
	"strings"

	"github.com/gin-gonic/gin"

	"github.com/z/tg-apicreator-bot/internal/database"
)

// ---- pages ----

func (s *Server) dashboard(c *gin.Context) {
	st, err := s.repo.Stats()
	if err != nil {
		s.logger.Warnf("web", "stats: %v", err)
	}
	s.render(c, "dashboard.html", http.StatusOK, pageData{
		Title:  "Dashboard",
		Active: "dashboard",
		Stats:  st,
	})
}

func (s *Server) usersPage(c *gin.Context) {
	page := atoiDefault(c.Query("page"), 1)
	limit := 25
	offset := (page - 1) * limit
	users, total, err := s.repo.ListUsers(limit, offset)
	if err != nil {
		s.logger.Warnf("web", "list users: %v", err)
	}
	s.render(c, "users.html", http.StatusOK, pageData{
		Title:      "Users",
		Active:     "users",
		Users:      users,
		UsersTotal: total,
	})
}

func (s *Server) apikeysPage(c *gin.Context) {
	page := atoiDefault(c.Query("page"), 1)
	limit := 25
	offset := (page - 1) * limit
	keys, total, err := s.repo.ListAPIKeys(limit, offset)
	if err != nil {
		s.logger.Warnf("web", "list keys: %v", err)
	}
	s.render(c, "apikeys.html", http.StatusOK, pageData{
		Title:     "API Keys",
		Active:    "apikeys",
		Keys:      keys,
		KeysTotal: total,
	})
}

func (s *Server) proxiesPage(c *gin.Context) {
	ps, err := s.repo.ListProxies()
	if err != nil {
		s.logger.Warnf("web", "list proxies: %v", err)
	}
	s.render(c, "proxies.html", http.StatusOK, pageData{
		Title:    "Proxies",
		Active:   "proxies",
		Proxies:  ps,
	})
}

func (s *Server) settingsPage(c *gin.Context) {
	s.render(c, "settings.html", http.StatusOK, pageData{
		Title:  "Settings",
		Active: "settings",
		Settings: settingsView{
			Daily:            s.cfg.Limits.Daily,
			Cooldown:         s.cfg.Limits.CooldownSeconds,
			WhitelistEnabled: s.cfg.Bot.WhitelistEnabled,
			WhitelistCount:   len(s.cfg.Bot.Whitelist),
			ProxyMode:        s.cfg.Proxy.Mode,
			ProxyTimeout:     s.cfg.Proxy.TimeoutSeconds,
		},
	})
}

func (s *Server) logsPage(c *gin.Context) {
	page := atoiDefault(c.Query("page"), 1)
	limit := 50
	offset := (page - 1) * limit
	logs, total, err := s.repo.ListLogs(limit, offset, c.Query("level"))
	if err != nil {
		s.logger.Warnf("web", "list logs: %v", err)
	}
	s.render(c, "logs.html", http.StatusOK, pageData{
		Title:    "Logs",
		Active:   "logs",
		Logs:     logs,
		LogsTotal: total,
	})
}

// ---- JSON API ----

func (s *Server) apiStats(c *gin.Context) {
	st, err := s.repo.Stats()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"ok": false, "error": err.Error()})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"ok":            true,
		"users":         st.Users,
		"keys":          st.Keys,
		"keys_today":    st.KeysToday,
		"proxies":       st.Proxies,
		"active_prox":   st.ActiveProx,
		"banned":        st.Banned,
		"whitelist_on":  s.cfg.Bot.WhitelistEnabled,
		"proxy_mode":    s.cfg.Proxy.Mode,
	})
}

func (s *Server) apiLogs(c *gin.Context) {
	limit := atoiDefault(c.Query("limit"), 50)
	logs, _, err := s.repo.ListLogs(limit, 0, c.Query("level"))
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"ok": false, "error": err.Error()})
		return
	}
	out := make([]gin.H, 0, len(logs))
	for _, l := range logs {
		uid := ""
		if l.UserID.Valid {
			uid = strconv.FormatInt(l.UserID.Int64, 10)
		}
		out = append(out, gin.H{
			"id":         l.ID,
			"level":      l.Level,
			"source":     l.Source,
			"user_id":    uid,
			"message":    l.Message,
			"created_at": l.CreatedAt,
		})
	}
	c.JSON(http.StatusOK, gin.H{"ok": true, "logs": out})
}

func (s *Server) apiBanUser(c *gin.Context) {
	tg, err := strconv.ParseInt(c.Param("tg"), 10, 64)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"ok": false, "error": "bad id"})
		return
	}
	if err := s.repo.SetBanned(tg, true); err != nil {
		c.JSON(http.StatusNotFound, gin.H{"ok": false, "error": "user not found"})
		return
	}
	s.logger.Infof("web", "user %d banned via panel", tg)
	c.JSON(http.StatusOK, gin.H{"ok": true})
}

func (s *Server) apiUnbanUser(c *gin.Context) {
	tg, err := strconv.ParseInt(c.Param("tg"), 10, 64)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"ok": false, "error": "bad id"})
		return
	}
	if err := s.repo.SetBanned(tg, false); err != nil {
		c.JSON(http.StatusNotFound, gin.H{"ok": false, "error": "user not found"})
		return
	}
	s.logger.Infof("web", "user %d unbanned via panel", tg)
	c.JSON(http.StatusOK, gin.H{"ok": true})
}

func (s *Server) apiRevokeKey(c *gin.Context) {
	id, err := strconv.ParseInt(c.Param("id"), 10, 64)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"ok": false, "error": "bad id"})
		return
	}
	if err := s.repo.RevokeAPIKey(id); err != nil {
		c.JSON(http.StatusNotFound, gin.H{"ok": false, "error": "key not found"})
		return
	}
	s.logger.Infof("web", "key %d revoked via panel", id)
	c.JSON(http.StatusOK, gin.H{"ok": true})
}

func (s *Server) apiDeleteKey(c *gin.Context) {
	id, err := strconv.ParseInt(c.Param("id"), 10, 64)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"ok": false, "error": "bad id"})
		return
	}
	if err := s.repo.DeleteAPIKey(id); err != nil {
		c.JSON(http.StatusNotFound, gin.H{"ok": false, "error": "key not found"})
		return
	}
	s.logger.Infof("web", "key %d deleted via panel", id)
	c.JSON(http.StatusOK, gin.H{"ok": true})
}

func (s *Server) apiAddProxy(c *gin.Context) {
	p := database.Proxy{
		Kind:     strings.ToLower(strings.TrimSpace(c.PostForm("kind"))),
		Host:     strings.TrimSpace(c.PostForm("host")),
		Port:     atoiDefault(c.PostForm("port"), 0),
		Username: strings.TrimSpace(c.PostForm("username")),
		Password: strings.TrimSpace(c.PostForm("password")),
		Enabled:  true,
	}
	if p.Kind == "" {
		p.Kind = "http"
	}
	if !(p.Kind == "http" || p.Kind == "https" || p.Kind == "socks5") {
		c.JSON(http.StatusBadRequest, gin.H{"ok": false, "error": "kind must be http/https/socks5"})
		return
	}
	if p.Host == "" || p.Port <= 0 || p.Port > 65535 {
		c.JSON(http.StatusBadRequest, gin.H{"ok": false, "error": "host and a valid port are required"})
		return
	}
	id, err := s.repo.CreateProxy(p)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"ok": false, "error": err.Error()})
		return
	}
	_ = s.proxies.Reload()
	s.logger.Infof("web", "proxy %d added (%s://%s:%d)", id, p.Kind, p.Host, p.Port)
	c.JSON(http.StatusOK, gin.H{"ok": true, "id": id})
}

func (s *Server) apiToggleProxy(c *gin.Context) {
	id, err := strconv.ParseInt(c.Param("id"), 10, 64)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"ok": false, "error": "bad id"})
		return
	}
	enabled := c.PostForm("enabled") == "1"
	if err := s.repo.ToggleProxy(id, enabled); err != nil {
		c.JSON(http.StatusNotFound, gin.H{"ok": false, "error": "proxy not found"})
		return
	}
	_ = s.proxies.Reload()
	s.logger.Infof("web", "proxy %d enabled=%v", id, enabled)
	c.JSON(http.StatusOK, gin.H{"ok": true})
}

func (s *Server) apiDeleteProxy(c *gin.Context) {
	id, err := strconv.ParseInt(c.Param("id"), 10, 64)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"ok": false, "error": "bad id"})
		return
	}
	if err := s.repo.DeleteProxy(id); err != nil {
		c.JSON(http.StatusNotFound, gin.H{"ok": false, "error": "proxy not found"})
		return
	}
	_ = s.proxies.Reload()
	s.logger.Infof("web", "proxy %d deleted", id)
	c.JSON(http.StatusOK, gin.H{"ok": true})
}

// apiSaveSettings updates the runtime-overridable config knobs both in memory
// (so the bot picks them up immediately) and in the settings table (so they
// survive a restart). main.go overlays the stored values onto cfg on boot.
func (s *Server) apiSaveSettings(c *gin.Context) {
	if v := c.PostForm("daily"); v != "" {
		if n, err := strconv.Atoi(v); err == nil && n >= 0 {
			s.cfg.Limits.Daily = n
			_ = s.repo.SetSetting("daily_limit", strconv.Itoa(n))
		}
	}
	if v := c.PostForm("cooldown"); v != "" {
		if n, err := strconv.Atoi(v); err == nil && n >= 0 {
			s.cfg.Limits.CooldownSeconds = n
			s.limiter.SetCooldown(n)
			_ = s.repo.SetSetting("cooldown_seconds", strconv.Itoa(n))
		}
	}
	if v := c.PostForm("whitelist_enabled"); v != "" {
		on := v == "1" || v == "true"
		s.cfg.Bot.WhitelistEnabled = on
		_ = s.repo.SetSetting("whitelist_enabled", boolStr(on))
	}
	if v := c.PostForm("proxy_mode"); v != "" {
		if v == "none" || v == "round_robin" {
			s.cfg.Proxy.Mode = v
			_ = s.repo.SetSetting("proxy_mode", v)
		}
	}
	if v := c.PostForm("proxy_timeout"); v != "" {
		if n, err := strconv.Atoi(v); err == nil && n > 0 {
			s.cfg.Proxy.TimeoutSeconds = n
			_ = s.repo.SetSetting("proxy_timeout", strconv.Itoa(n))
		}
	}
	s.logger.Infof("web", "settings updated via panel")
	c.JSON(http.StatusOK, gin.H{"ok": true})
}

// ---- helpers ----

func atoiDefault(s string, def int) int {
	if s == "" {
		return def
	}
	n, err := strconv.Atoi(s)
	if err != nil || n < 1 {
		return def
	}
	return n
}

func boolStr(b bool) string {
	if b {
		return "1"
	}
	return "0"
}
