package corporate_handlers

import (
	sidebaruserprofile "cpone/component/sidebar_user_profile"
	customtoastv2 "cpone/component/toastbootstrap"
	"cpone/models"
	"cpone/utils"
	"net/http"
	"strings"
	"time"

	"github.com/a-h/templ"
	"github.com/golang-jwt/jwt/v5"
	"github.com/labstack/echo/v4"
)

type AccountService interface {
	ChangePasswordPIC(host string, token string, currPassword string, newPassword string) (models.ResponseStatus, error)
	ChangePasswordPAT(token string, currPassword string, newPassword string) (models.ResponseStatus, error)
}

func NewAccountHandler(as AccountService) *AccountHandler {
	return &AccountHandler{
		AccountService: as,
	}
}

type AccountHandler struct {
	AccountService AccountService
}

func (as *AccountHandler) HandleChangePassword(c echo.Context) error {
	var response models.ResponseStatus
	userToken := c.Get("user").(*jwt.Token)
	token := userToken.Raw
	claims := userToken.Claims.(jwt.MapClaims)
	userGroup := claims["M_UserGroupDashboard"].(string)
	h := c.Request().Host

	old_pass := c.FormValue("oldpassid")
	new_pass := c.FormValue("newpassid")
	re_new_pass := c.FormValue("renewpassid")
	// logger.Info("params", zap.Any("old", old_pass), zap.Any("new", new_pass), zap.Any("re-new", re_new_pass))

	old_validation := ""
	new_validation := ""
	renew_validation := ""
	errorPop := ""

	if strings.TrimSpace(old_pass) == "" {
		old_validation = "Tidak boleh kosong"
		errorPop = "Tidak boleh kosong"
	}
	if strings.TrimSpace(new_pass) == "" {
		new_validation = "Tidak boleh kosong"
		errorPop = "Tidak boleh kosong"
	}
	if strings.TrimSpace(re_new_pass) == "" {
		renew_validation = "Tidak boleh kosong"
		errorPop = "Tidak boleh kosong"
	}
	if strings.TrimSpace(new_pass) != strings.TrimSpace(re_new_pass) {
		new_validation = "Password tidak sama"
		renew_validation = "Password tidak sama"
		errorPop = "Password tidak sama"
	}

	if old_validation != "" || new_validation != "" || renew_validation != "" {
		newBody := sidebaruserprofile.RetModalGantiPassword(
			models.CustomTextFieldv2Prm{
				ID:          "oldPassID",
				Name:        "oldpassid",
				Type:        "password",
				Placeholder: "Masukan password lama",
				Label:       "Password Lama",
				ErrorMsg:    old_validation,
			},
			models.CustomTextFieldv2Prm{
				ID:          "newPassID",
				Name:        "newpassid",
				Type:        "password",
				Placeholder: "Masukan password baru",
				Label:       "Password Baru",
				ErrorMsg:    new_validation,
			},
			models.CustomTextFieldv2Prm{
				ID:          "reNewPassID",
				Name:        "renewpassid",
				Type:        "password",
				Placeholder: "Masukan ulang password baru",
				Label:       "Ulangi Password Baru",
				ErrorMsg:    renew_validation,
			},
			sidebaruserprofile.JSHideModal(""),
		)
		toast := customtoastv2.CustomToastV2Show("Warning", errorPop, "warning")
		return utils.ViewMulti(c, []templ.Component{toast, newBody})
	}

	if userGroup == "pic" {
		resp, err := as.AccountService.ChangePasswordPIC(h, token, old_pass, new_pass)
		if err != nil {
			newBody := sidebaruserprofile.ModalGantiPassword()
			toast := customtoastv2.CustomToastV2Show("Warning", err.Error(), "warning")
			return utils.ViewMulti(c, []templ.Component{toast, newBody})
		}
		response = resp
	}

	if userGroup == "patient" {
		resp, err := as.AccountService.ChangePasswordPAT(token, old_pass, new_pass)
		if err != nil {
			newBody := sidebaruserprofile.ModalGantiPassword()
			toast := customtoastv2.CustomToastV2Show("Warning", "Error ganti password pat", "warning")
			return utils.ViewMulti(c, []templ.Component{toast, newBody})
		}
		response = resp
	}

	if response.Status == "ERR" {
		newBody := sidebaruserprofile.ModalGantiPassword()
		toast := customtoastv2.CustomToastV2Show("Warning", response.Message, "warning")
		return utils.ViewMulti(c, []templ.Component{toast, newBody})
	}

	expire := time.Now().Add(-7 * 24 * time.Hour)
	cookie := new(http.Cookie)
	cookie.Name = "token"
	cookie.Value = ""
	cookie.Path = "/"
	cookie.Expires = expire
	cookie.HttpOnly = true
	c.SetCookie(cookie)

	ret := `
	<script>
		$("#body-ganti-pass").modal('hide')
		console.log("signout")
		localStorage.removeItem("token")
		localStorage.removeItem("user")

		setTimeout(() => {
			window.location.replace("/login");
		}, 200)
	</script>
	`

	c.Response().Header().Set("HX-Trigger", "script")
	return c.String(http.StatusOK, ret)
}

func (as *AccountHandler) HandleCloseChangePassword(c echo.Context) error {
	newBody := sidebaruserprofile.ModalGantiPassword()

	return utils.View(c, newBody)
}
