package channel

import (
	"context"
	"database/sql"
	"encoding/json"
	"net/http"

	"git.dustin.coffee/hobokenchicken/dumpsterChat/internal/middleware"
	"git.dustin.coffee/hobokenchicken/dumpsterChat/internal/permissions"
	"github.com/go-chi/chi/v5"
)

type calendarEvent struct {
	ID              string  `json:"id"`
	ChannelID       string  `json:"channel_id"`
	CreatorID       string  `json:"creator_id"`
	Title           string  `json:"title"`
	Description     *string `json:"description"`
	StartTime       string  `json:"start_time"`
	EndTime         *string `json:"end_time"`
	RecurrenceRule  *string `json:"recurrence_rule"`
	Location        *string `json:"location"`
	Color           *string `json:"color"`
	GoingCount      int     `json:"going_count"`
	MaybeCount      int     `json:"maybe_count"`
	NoCount         int     `json:"no_count"`
	UserStatus      string  `json:"user_status"`
	CreatedAt       string  `json:"created_at"`
}

type createEventRequest struct {
	Title          string  `json:"title"`
	Description    *string `json:"description"`
	StartTime      string  `json:"start_time"`
	EndTime        *string `json:"end_time"`
	RecurrenceRule *string `json:"recurrence_rule"`
	Location       *string `json:"location"`
	Color          *string `json:"color"`
}

func (h *Handler) registerCalendarRoutes(r chi.Router) {
	r.Get("/{channelID}/events", h.ListEvents)
	r.Post("/{channelID}/events", h.CreateEvent)
	r.Patch("/events/{eventID}", h.UpdateEvent)
	r.Delete("/events/{eventID}", h.DeleteEvent)
	r.Post("/events/{eventID}/rsvp", h.SetRSVP)
}

func (h *Handler) CreateEvent(w http.ResponseWriter, r *http.Request) {
	channelID := chi.URLParam(r, "channelID")
	userID, ok := middleware.UserIDFromContext(r.Context())
	if !ok {
		http.Error(w, `{"error":"unauthorized"}`, http.StatusUnauthorized)
		return
	}
	serverID, err := h.serverIDForChannel(r.Context(), channelID)
	if err != nil {
		http.Error(w, `{"error":"channel not found"}`, http.StatusNotFound)
		return
	}
	if ok, _ := h.isMember(r.Context(), userID, serverID); !ok {
		http.Error(w, `{"error":"forbidden"}`, http.StatusForbidden)
		return
	}
	allowed, _ := h.checker.CheckPermission(r.Context(), serverID, userID, permissions.SEND_MESSAGES)
	if !allowed {
		http.Error(w, `{"error":"forbidden"}`, http.StatusForbidden)
		return
	}

	var req createEventRequest
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.Title == "" || req.StartTime == "" {
		http.Error(w, `{"error":"invalid request"}`, http.StatusBadRequest)
		return
	}

	event, err := h.scanEvent(h.db.QueryRowContext(r.Context(), `
		INSERT INTO events (channel_id, creator_id, title, description, start_time, end_time, recurrence_rule, location, color)
		VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
		RETURNING id, channel_id, creator_id, title, description, start_time, end_time, recurrence_rule, location, color, created_at
	`, channelID, userID, req.Title, req.Description, req.StartTime, req.EndTime, req.RecurrenceRule, req.Location, req.Color))
	if err != nil {
		http.Error(w, `{"error":"failed to create event"}`, http.StatusInternalServerError)
		return
	}
	h.respondEvent(w, r, event, userID)
}

func (h *Handler) ListEvents(w http.ResponseWriter, r *http.Request) {
	channelID := chi.URLParam(r, "channelID")
	userID, ok := middleware.UserIDFromContext(r.Context())
	if !ok {
		http.Error(w, `{"error":"unauthorized"}`, http.StatusUnauthorized)
		return
	}
	serverID, err := h.serverIDForChannel(r.Context(), channelID)
	if err != nil {
		http.Error(w, `{"error":"channel not found"}`, http.StatusNotFound)
		return
	}
	if ok, _ := h.isMember(r.Context(), userID, serverID); !ok {
		http.Error(w, `{"error":"forbidden"}`, http.StatusForbidden)
		return
	}

	from := r.URL.Query().Get("from")
	to := r.URL.Query().Get("to")
	if from == "" || to == "" {
		http.Error(w, `{"error":"from and to required"}`, http.StatusBadRequest)
		return
	}

	rows, err := h.db.QueryContext(r.Context(), `
		SELECT id, channel_id, creator_id, title, description, start_time, end_time, recurrence_rule, location, color, created_at
		FROM events
		WHERE channel_id = $1 AND start_time >= $2 AND start_time <= $3
		ORDER BY start_time
	`, channelID, from, to)
	if err != nil {
		http.Error(w, `{"error":"server error"}`, http.StatusInternalServerError)
		return
	}
	defer rows.Close()

	events := make([]calendarEvent, 0)
	for rows.Next() {
		e, err := h.scanEvent(rows)
		if err != nil {
			continue
		}
		events = append(events, h.withRSVPCounts(r.Context(), e, userID))
	}
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(events)
}

func (h *Handler) UpdateEvent(w http.ResponseWriter, r *http.Request) {
	eventID := chi.URLParam(r, "eventID")
	userID, ok := middleware.UserIDFromContext(r.Context())
	if !ok {
		http.Error(w, `{"error":"unauthorized"}`, http.StatusUnauthorized)
		return
	}

	var channelID, creatorID string
	err := h.db.QueryRowContext(r.Context(), `SELECT channel_id, creator_id FROM events WHERE id = $1`, eventID).Scan(&channelID, &creatorID)
	if err != nil {
		http.Error(w, `{"error":"event not found"}`, http.StatusNotFound)
		return
	}
	serverID, err := h.serverIDForChannel(r.Context(), channelID)
	if err != nil {
		http.Error(w, `{"error":"channel not found"}`, http.StatusNotFound)
		return
	}
	allowed, _ := h.checker.CheckPermission(r.Context(), serverID, userID, permissions.MANAGE_CHANNELS)
	if !allowed && creatorID != userID {
		http.Error(w, `{"error":"forbidden"}`, http.StatusForbidden)
		return
	}

	var req createEventRequest
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		http.Error(w, `{"error":"invalid request"}`, http.StatusBadRequest)
		return
	}

	var nullEnd, nullRecurrence, nullLocation, nullColor, nullDesc interface{}
	var query string
	if req.Title != "" {
		query = `
			UPDATE events SET title = $3, description = COALESCE($4, description), start_time = COALESCE($5, start_time),
				end_time = COALESCE($6, end_time), recurrence_rule = COALESCE($7, recurrence_rule), location = COALESCE($8, location),
				color = COALESCE($9, color), updated_at = NOW()
			WHERE id = $1
			RETURNING id, channel_id, creator_id, title, description, start_time, end_time, recurrence_rule, location, color, created_at
		`
	} else {
		// patch partial
		query = `
			UPDATE events SET description = COALESCE($4, description), start_time = COALESCE($5, start_time),
				end_time = COALESCE($6, end_time), recurrence_rule = COALESCE($7, recurrence_rule), location = COALESCE($8, location),
				color = COALESCE($9, color), updated_at = NOW()
			WHERE id = $1
			RETURNING id, channel_id, creator_id, title, description, start_time, end_time, recurrence_rule, location, color, created_at
		`
	}
	// ponytail: pass nil where omitted; decoder will give zero values and COALESCE preserves existing
	event, err := h.scanEvent(h.db.QueryRowContext(r.Context(), query, eventID, nullDesc, req.Title, req.Description, req.StartTime, nullEnd, nullRecurrence, nullLocation, nullColor))
	if err != nil {
		http.Error(w, `{"error":"failed to update event"}`, http.StatusInternalServerError)
		return
	}
	h.respondEvent(w, r, h.withRSVPCounts(r.Context(), event, userID), userID)
}

func (h *Handler) DeleteEvent(w http.ResponseWriter, r *http.Request) {
	eventID := chi.URLParam(r, "eventID")
	userID, ok := middleware.UserIDFromContext(r.Context())
	if !ok {
		http.Error(w, `{"error":"unauthorized"}`, http.StatusUnauthorized)
		return
	}

	var channelID, creatorID string
	err := h.db.QueryRowContext(r.Context(), `SELECT channel_id, creator_id FROM events WHERE id = $1`, eventID).Scan(&channelID, &creatorID)
	if err != nil {
		http.Error(w, `{"error":"event not found"}`, http.StatusNotFound)
		return
	}
	serverID, err := h.serverIDForChannel(r.Context(), channelID)
	if err != nil {
		http.Error(w, `{"error":"channel not found"}`, http.StatusNotFound)
		return
	}
	allowed, _ := h.checker.CheckPermission(r.Context(), serverID, userID, permissions.MANAGE_CHANNELS)
	if !allowed && creatorID != userID {
		http.Error(w, `{"error":"forbidden"}`, http.StatusForbidden)
		return
	}

	_, err = h.db.ExecContext(r.Context(), `DELETE FROM events WHERE id = $1`, eventID)
	if err != nil {
		http.Error(w, `{"error":"failed to delete event"}`, http.StatusInternalServerError)
		return
	}
	w.WriteHeader(http.StatusNoContent)
}

func (h *Handler) SetRSVP(w http.ResponseWriter, r *http.Request) {
	eventID := chi.URLParam(r, "eventID")
	userID, ok := middleware.UserIDFromContext(r.Context())
	if !ok {
		http.Error(w, `{"error":"unauthorized"}`, http.StatusUnauthorized)
		return
	}

	var req struct {
		Status string `json:"status"`
	}
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil || (req.Status != "going" && req.Status != "maybe" && req.Status != "no") {
		http.Error(w, `{"error":"invalid status"}`, http.StatusBadRequest)
		return
	}

	var channelID string
	err := h.db.QueryRowContext(r.Context(), `SELECT channel_id FROM events WHERE id = $1`, eventID).Scan(&channelID)
	if err != nil {
		http.Error(w, `{"error":"event not found"}`, http.StatusNotFound)
		return
	}
	serverID, err := h.serverIDForChannel(r.Context(), channelID)
	if err != nil {
		http.Error(w, `{"error":"channel not found"}`, http.StatusNotFound)
		return
	}
	if ok, _ := h.isMember(r.Context(), userID, serverID); !ok {
		http.Error(w, `{"error":"forbidden"}`, http.StatusForbidden)
		return
	}

	_, err = h.db.ExecContext(r.Context(), `
		INSERT INTO event_rsvps (event_id, user_id, status) VALUES ($1, $2, $3)
		ON CONFLICT (event_id, user_id) DO UPDATE SET status = $3, responded_at = NOW()
	`, eventID, userID, req.Status)
	if err != nil {
		http.Error(w, `{"error":"failed to save rsvp"}`, http.StatusInternalServerError)
		return
	}
	w.WriteHeader(http.StatusNoContent)
}

func (h *Handler) scanEvent(row interface{ Scan(dest ...any) error }) (calendarEvent, error) {
	var e calendarEvent
	var desc, endTime, recurrence, location, color sql.NullString
	err := row.Scan(&e.ID, &e.ChannelID, &e.CreatorID, &e.Title, &desc, &e.StartTime, &endTime, &recurrence, &location, &color, &e.CreatedAt)
	if err != nil {
		return e, err
	}
	if desc.Valid {
		e.Description = &desc.String
	}
	if endTime.Valid {
		e.EndTime = &endTime.String
	}
	if recurrence.Valid {
		e.RecurrenceRule = &recurrence.String
	}
	if location.Valid {
		e.Location = &location.String
	}
	if color.Valid {
		e.Color = &color.String
	}
	return e, nil
}

func (h *Handler) withRSVPCounts(ctx context.Context, e calendarEvent, userID string) calendarEvent {
	row := h.db.QueryRowContext(ctx, `
		SELECT
			SUM(CASE WHEN status = 'going' THEN 1 ELSE 0 END),
			SUM(CASE WHEN status = 'maybe' THEN 1 ELSE 0 END),
			SUM(CASE WHEN status = 'no' THEN 1 ELSE 0 END),
			COALESCE(MAX(CASE WHEN user_id = $2 THEN status END), '')
		FROM event_rsvps WHERE event_id = $1
	`, e.ID, userID)
	var userStatus sql.NullString
	_ = row.Scan(&e.GoingCount, &e.MaybeCount, &e.NoCount, &userStatus)
	if userStatus.Valid {
		e.UserStatus = userStatus.String
	}
	return e
}

func (h *Handler) respondEvent(w http.ResponseWriter, r *http.Request, e calendarEvent, userID string) {
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(h.withRSVPCounts(r.Context(), e, userID))
}
