package agenda

import (
	"fmt"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
)

type Handler struct {
	service *Service
}

func NewHandler(service *Service) *Handler {
	return &Handler{service: service}
}

// Create godoc
// @Summary      Create a new agenda event
// @Description  Create a new agenda event
// @Tags         agenda
// @Accept       json
// @Produce      json
// @Param        request body CreateAgendaRequest true "Create Agenda Request"
// @Success      201  {object}  map[string]interface{}
// @Failure      400  {object}  map[string]string
// @Failure      500  {object}  map[string]string
// @Router       /api/agenda [post]
func (h *Handler) Create(c *gin.Context) {
	var req CreateAgendaRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Dados inválidos: " + err.Error()})
		return
	}

	userIDStr := c.GetString("userID")
	userID, err := uuid.Parse(userIDStr)
	if err != nil {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "Usuário não autenticado"})
		return
	}

	agenda, err := h.service.Create(c.Request.Context(), userID, req)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Erro ao criar agenda: " + err.Error()})
		return
	}

	c.JSON(http.StatusCreated, agenda)
}

// List godoc
// @Summary      List all agenda events
// @Description  List all agenda events with details
// @Tags         agenda
// @Accept       json
// @Produce      json
// @Success      200  {array}   map[string]interface{}
// @Failure      500  {object}  map[string]string
// @Router       /api/agenda [get]
func (h *Handler) List(c *gin.Context) {
	userIDStr := c.GetString("userID")
	role := c.GetString("role")
	userID, _ := uuid.Parse(userIDStr)

	agendas, err := h.service.List(c.Request.Context(), userID, role)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Erro ao listar agendas: " + err.Error()})
		return
	}

	c.JSON(http.StatusOK, agendas)
}

// Get godoc
// @Summary      Get agenda event by ID
// @Description  Get agenda event details by ID
// @Tags         agenda
// @Accept       json
// @Produce      json
// @Param        id   path      string  true  "Agenda ID"
// @Success      200  {object}  map[string]interface{}
// @Failure      400  {object}  map[string]string
// @Failure      500  {object}  map[string]string
// @Router       /api/agenda/{id} [get]
func (h *Handler) Get(c *gin.Context) {
	idParam := c.Param("id")
	id, err := uuid.Parse(idParam)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "ID inválido: " + err.Error()})
		return
	}

	agenda, err := h.service.Get(c.Request.Context(), id)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Erro ao buscar agenda: " + err.Error()})
		return
	}

	c.JSON(http.StatusOK, agenda)
}

// Update godoc
// @Summary      Update agenda event
// @Description  Update agenda event by ID
// @Tags         agenda
// @Accept       json
// @Produce      json
// @Param        id   path      string  true  "Agenda ID"
// @Param        request body CreateAgendaRequest true "Update Agenda Request"
// @Success      200  {object}  map[string]interface{}
// @Failure      400  {object}  map[string]string
// @Failure      500  {object}  map[string]string
// @Router       /api/agenda/{id} [put]
func (h *Handler) Update(c *gin.Context) {
	idParam := c.Param("id")
	id, err := uuid.Parse(idParam)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "ID inválido: " + err.Error()})
		return
	}

	var req CreateAgendaRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Dados inválidos: " + err.Error()})
		return
	}

	fmt.Printf("Update Payload: %+v\n", req)

	agenda, err := h.service.Update(c.Request.Context(), id, req)
	if err != nil {
		fmt.Printf("Update Error for ID %s: %v\n", id, err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Erro ao atualizar agenda: " + err.Error()})
		return
	}

	c.JSON(http.StatusOK, agenda)
}

// Delete godoc
// @Summary      Delete agenda event
// @Description  Delete agenda event by ID
// @Tags         agenda
// @Accept       json
// @Produce      json
// @Param        id   path      string  true  "Agenda ID"
// @Success      204  {object}  nil
// @Failure      400  {object}  map[string]string
// @Failure      500  {object}  map[string]string
// @Router       /api/agenda/{id} [delete]
func (h *Handler) Delete(c *gin.Context) {
	idParam := c.Param("id")
	id, err := uuid.Parse(idParam)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "ID inválido: " + err.Error()})
		return
	}

	if err := h.service.Delete(c.Request.Context(), id); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Erro ao deletar agenda: " + err.Error()})
		return
	}

	c.Status(http.StatusNoContent)
}

// AssignProfessional godoc
// @Summary      Assign professional to agenda
// @Tags         agenda
// @Router       /api/agenda/{id}/professionals [post]
func (h *Handler) AssignProfessional(c *gin.Context) {
	idParam := c.Param("id")
	agendaID, err := uuid.Parse(idParam)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "ID de agenda inválido"})
		return
	}

	var req struct {
		ProfessionalID string `json:"professional_id" binding:"required"`
	}
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Dados inválidos: " + err.Error()})
		return
	}

	profID, err := uuid.Parse(req.ProfessionalID)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "ID de profissional inválido"})
		return
	}

	if err := h.service.AssignProfessional(c.Request.Context(), agendaID, profID); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Erro ao atribuir profissional: " + err.Error()})
		return
	}

	c.Status(http.StatusOK)
}

// RemoveProfessional godoc
// @Summary      Remove professional from agenda
// @Tags         agenda
// @Router       /api/agenda/{id}/professionals/{profId} [delete]
func (h *Handler) RemoveProfessional(c *gin.Context) {
	idParam := c.Param("id")
	agendaID, err := uuid.Parse(idParam)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "ID de agenda inválido"})
		return
	}

	profIdParam := c.Param("profId")
	profID, err := uuid.Parse(profIdParam)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "ID de profissional inválido"})
		return
	}

	if err := h.service.RemoveProfessional(c.Request.Context(), agendaID, profID); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Erro ao remover profissional: " + err.Error()})
		return
	}

	c.Status(http.StatusNoContent)
}

// GetProfessionals godoc
// @Summary      Get professionals assigned to agenda
// @Tags         agenda
// @Router       /api/agenda/{id}/professionals [get]
func (h *Handler) GetProfessionals(c *gin.Context) {
	idParam := c.Param("id")
	agendaID, err := uuid.Parse(idParam)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "ID de agenda inválido"})
		return
	}

	profs, err := h.service.GetAgendaProfessionals(c.Request.Context(), agendaID)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Erro ao buscar profissionais: " + err.Error()})
		return
	}

	c.JSON(http.StatusOK, profs)
}

// UpdateStatus godoc
// @Summary      Update agenda status
// @Tags         agenda
// @Router       /api/agenda/{id}/status [patch]
func (h *Handler) UpdateStatus(c *gin.Context) {
	idParam := c.Param("id")
	agendaID, err := uuid.Parse(idParam)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "ID de agenda inválido"})
		return
	}

	var req struct {
		Status string `json:"status" binding:"required"`
	}
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Dados inválidos: " + err.Error()})
		return
	}

	agenda, err := h.service.UpdateStatus(c.Request.Context(), agendaID, req.Status)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Erro ao atualizar status: " + err.Error()})
		return
	}

	c.JSON(http.StatusOK, agenda)
}

// UpdateAssignmentStatus godoc
// @Summary      Update professional assignment status
// @Tags         agenda
// @Router       /api/agenda/{id}/professionals/{profId}/status [patch]
func (h *Handler) UpdateAssignmentStatus(c *gin.Context) {
	idParam := c.Param("id")
	agendaID, err := uuid.Parse(idParam)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "ID de agenda inválido"})
		return
	}

	profIdParam := c.Param("profId")
	profID, err := uuid.Parse(profIdParam)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "ID de profissional inválido"})
		return
	}

	var req struct {
		Status string `json:"status" binding:"required"`
		Reason string `json:"reason"`
	}
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Dados inválidos: " + err.Error()})
		return
	}

	if err := h.service.UpdateAssignmentStatus(c.Request.Context(), agendaID, profID, req.Status, req.Reason); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Erro ao atualizar status: " + err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"status": "success"})
}

// UpdateAssignmentPosition godoc
// @Summary      Update professional position in agenda
// @Tags         agenda
// @Router       /api/agenda/{id}/professionals/{profId}/position [patch]
func (h *Handler) UpdateAssignmentPosition(c *gin.Context) {
	idParam := c.Param("id")
	agendaID, err := uuid.Parse(idParam)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "ID de agenda inválido"})
		return
	}

	profIdParam := c.Param("profId")
	profID, err := uuid.Parse(profIdParam)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "ID de profissional inválido"})
		return
	}

	var req struct {
		Posicao string `json:"posicao" binding:"required"`
	}
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Dados inválidos: " + err.Error()})
		return
	}

	if err := h.service.UpdateAssignmentPosition(c.Request.Context(), agendaID, profID, req.Posicao); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Erro ao atualizar posição: " + err.Error()})
		return
	}

	c.Status(http.StatusOK)
}

// ListAvailableProfessionals godoc
// @Summary      List available professionals for agenda date
// @Tags         agenda
// @Router       /api/agenda/{id}/available [get]
func (h *Handler) ListAvailableProfessionals(c *gin.Context) {
	idParam := c.Param("id")
	agendaID, err := uuid.Parse(idParam)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "ID de agenda inválido"})
		return
	}

	// Fetch agenda to get date
	agenda, err := h.service.Get(c.Request.Context(), agendaID)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Erro ao buscar agenda: " + err.Error()})
		return
	}

	// Check if date is valid
	if !agenda.DataEvento.Valid {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Agenda sem data definida"})
		return
	}

	profs, err := h.service.ListAvailableProfessionals(c.Request.Context(), agenda.DataEvento.Time)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Erro ao buscar profissionais disponíveis: " + err.Error()})
		return
	}

	c.JSON(http.StatusOK, profs)
}
