package handlers

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
	"strings"
	"time"

	"mgit.msbls.de/m/paliad/internal/auth"
	"mgit.msbls.de/m/paliad/internal/checklists"
)

type ChecklistFeedback struct {
	FeedbackType string `json:"feedback_type"`
	Checklist    string `json:"checklist"`
	Message      string `json:"message"`
}

func handleChecklistsPage(w http.ResponseWriter, r *http.Request) {
	http.ServeFile(w, r, "dist/checklists.html")
}

func handleChecklistDetailPage(w http.ResponseWriter, r *http.Request) {
	slug := r.PathValue("slug")
	if _, ok := checklists.Find(slug); !ok {
		http.NotFound(w, r)
		return
	}
	http.ServeFile(w, r, "dist/checklists-detail.html")
}

func handleChecklistInstancePage(w http.ResponseWriter, r *http.Request) {
	http.ServeFile(w, r, "dist/checklists-instance.html")
}

func handleChecklistsAPI(w http.ResponseWriter, r *http.Request) {
	writeJSON(w, http.StatusOK, checklists.Summaries())
}

func handleChecklistAPI(w http.ResponseWriter, r *http.Request) {
	slug := r.PathValue("slug")
	c, ok := checklists.Find(slug)
	if !ok {
		writeJSON(w, http.StatusNotFound, map[string]string{"error": "Checkliste nicht gefunden."})
		return
	}
	writeJSON(w, http.StatusOK, c)
}

func handleChecklistsFeedback(w http.ResponseWriter, r *http.Request) {
	var feedback ChecklistFeedback
	if err := json.NewDecoder(r.Body).Decode(&feedback); err != nil {
		writeJSON(w, http.StatusBadRequest, map[string]string{"error": "Ungültige Anfrage."})
		return
	}

	feedback.FeedbackType = strings.TrimSpace(feedback.FeedbackType)
	feedback.Checklist = strings.TrimSpace(feedback.Checklist)
	feedback.Message = strings.TrimSpace(feedback.Message)

	if feedback.Message == "" || feedback.FeedbackType == "" {
		writeJSON(w, http.StatusBadRequest, map[string]string{"error": "Nachricht und Art sind erforderlich."})
		return
	}

	accessToken := ""
	email := ""
	if cookie, err := r.Cookie(auth.SessionCookieName); err == nil {
		accessToken = cookie.Value
		email = extractEmailFromJWT(cookie.Value)
	}

	payload := map[string]string{
		"feedback_type": feedback.FeedbackType,
		"checklist":     feedback.Checklist,
		"message":       feedback.Message,
		"submitted_by":  email,
	}

	jsonBody, err := json.Marshal(payload)
	if err != nil {
		log.Printf("checklists feedback marshal error: %v", err)
		writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "Interner Fehler."})
		return
	}

	endpoint := fmt.Sprintf("%s/rest/v1/checklist_feedback", authClient.URL)
	req2, err := http.NewRequest("POST", endpoint, bytes.NewReader(jsonBody))
	if err != nil {
		log.Printf("checklists feedback request error: %v", err)
		writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "Interner Fehler."})
		return
	}
	req2.Header.Set("Content-Type", "application/json")
	req2.Header.Set("apikey", authClient.AnonKey)
	if accessToken != "" {
		req2.Header.Set("Authorization", "Bearer "+accessToken)
	} else {
		req2.Header.Set("Authorization", "Bearer "+authClient.AnonKey)
	}
	req2.Header.Set("Prefer", "return=minimal")

	client := &http.Client{Timeout: 5 * time.Second}
	resp, err := client.Do(req2)
	if err != nil {
		log.Printf("checklists feedback supabase error: %v", err)
		writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "Fehler beim Speichern."})
		return
	}
	defer resp.Body.Close()

	if resp.StatusCode >= 300 {
		body, _ := io.ReadAll(resp.Body)
		log.Printf("checklists feedback supabase status %d: %s", resp.StatusCode, string(body))
		writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "Fehler beim Speichern."})
		return
	}

	writeJSON(w, http.StatusCreated, map[string]string{"ok": "true"})
}
