package main

import (
	"context"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os"
	"strings"
	"time"

	"github.com/dgrijalva/jwt-go"
	"github.com/gorilla/mux"
	"golang.org/x/crypto/bcrypt"
)

// Define contextKey globally within the package
type contextKey string

// Define your key as a constant of the custom type
const userKey contextKey = "user"

// LoginRequest represents the request body for the /login endpoint.
type LoginRequest struct {
	Username string `json:"username"`
	Password string `json:"password"`
}

// LoginResponse represents the response body for the /login endpoint.
type LoginResponse struct {
	Token string `json:"token"`
}

// loginHandler handles the /login endpoint.
// LoginHandler handles the /login endpoint.
func LoginHandler(w http.ResponseWriter, r *http.Request) {
	var req LoginRequest
	fmt.Println(db, config)
	fmt.Println("LoginHandler called")
	err := json.NewDecoder(r.Body).Decode(&req)
	if err != nil {
		http.Error(w, "Invalid request body", http.StatusBadRequest)
		return
	}

	// Check if the user exists and the password matches
	var user User
	db.Where("username = ?", req.Username).First(&user)
	if user.ID == 0 {
		http.Error(w, "Invalid username or password", http.StatusUnauthorized)
		return
	}

	// Compare the provided password with the stored hashed password
	err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(req.Password))
	if err != nil {
		http.Error(w, "Invalid username or password", http.StatusUnauthorized)
		return
	}

	// Generate JWT token
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
		"username": user.Username,
		"exp":      time.Now().Add(time.Hour * 24).Unix(), // Token expires in 24 hours
	})

	tokenString, err := token.SignedString([]byte(config.JWTSecret))
	if err != nil {
		http.Error(w, "Failed to generate token", http.StatusInternalServerError)
		return
	}

	// Return the token in the response
	json.NewEncoder(w).Encode(LoginResponse{Token: tokenString})
}

// getBoxesHandler handles the GET /boxes endpoint.
func GetBoxesHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Printf("Received %s request to %s\n", r.Method, r.URL)
	var boxes []Box
	db.Find(&boxes)
	json.NewEncoder(w).Encode(boxes)
}

func GetBoxHandler(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	id := vars["id"]

	var box Box
	if err := db.First(&box, id).Error; err != nil {
		http.Error(w, "Box not found", http.StatusNotFound)
		return
	}

	json.NewEncoder(w).Encode(box)
}

// createBoxHandler handles the POST /boxes endpoint.
func CreateBoxHandler(w http.ResponseWriter, r *http.Request) {
	var box Box
	err := json.NewDecoder(r.Body).Decode(&box)
	if err != nil {
		http.Error(w, "Invalid request body", http.StatusBadRequest)
		return
	}

	db.Create(&box)

	// Create a response struct to include the ID
	type createBoxResponse struct {
		ID   uint   `json:"id"`
		Name string `json:"name"`
	}

	response := createBoxResponse{
		ID:   box.ID,
		Name: box.Name,
	}

	json.NewEncoder(w).Encode(response)
}

// deleteBoxHandler handles the DELETE /boxes/{id} endpoint.
func DeleteBoxHandler(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	id := vars["id"]

	// Retrieve the box from the database
	var box Box
	if err := db.First(&box, id).Error; err != nil {
		http.Error(w, "Box not found", http.StatusNotFound)
		return
	}

	// Optionally, delete associated items (if you want cascading delete)
	// db.Where("box_id = ?", id).Delete(&Item{})

	// Delete the box
	db.Delete(&box)

	w.WriteHeader(http.StatusNoContent) // 204 No Content
}

// getItemsHandler handles the GET /items endpoint.
func GetItemsHandler(w http.ResponseWriter, r *http.Request) {
	var items []Item
	db.Find(&items)
	json.NewEncoder(w).Encode(items)
}

// createItemHandler handles the POST /items endpoint.
func CreateItemHandler(w http.ResponseWriter, r *http.Request) {
	var item Item

	err := json.NewDecoder(r.Body).Decode(&item)
	if err != nil {
		http.Error(w, "Invalid request body", http.StatusBadRequest)
		return
	}
	fmt.Println(item)

	db.Create(&item)

	// Create a response struct to include the ID
	type createItemResponse struct {
		ID   uint   `json:"id"`
		Name string `json:"name"`
	}

	response := createItemResponse{
		ID:   item.ID,
		Name: item.Name,
	}

	json.NewEncoder(w).Encode(response)
}

// UploadItemImageHandler handles the image upload for an item
func UploadItemImageHandler(w http.ResponseWriter, r *http.Request) {
	// Extract the authenticated user from context (assuming this is how AuthMiddleware works)
	user, ok := r.Context().Value(userKey).(string)
	if !ok || user == "" {
		http.Error(w, "Unauthorized", http.StatusUnauthorized)
		return
	}

	// Parse the form data, 10MB limit for file uploads
	err := r.ParseMultipartForm(10 << 20)
	if err != nil {
		http.Error(w, "Unable to parse form", http.StatusBadRequest)
		return
	}

	// Get the file from the form data
	file, handler, err := r.FormFile("image")
	if err != nil {
		http.Error(w, "Error retrieving the file", http.StatusBadRequest)
		return
	}
	defer file.Close()

	// Get item ID from the URL
	vars := mux.Vars(r)
	itemID := vars["id"]

	// Validate that the item exists (fetch from DB using itemID)
	var item Item
	if err := db.First(&item, itemID).Error; err != nil {
		http.Error(w, "Item not found", http.StatusNotFound)
		return
	}

	// Save the uploaded file locally or to a storage service
	// Ensure the directory exists
	if err := os.MkdirAll(config.ImageStorageDir, 0755); err != nil {
		http.Error(w, "Unable to create image storage directory", http.StatusInternalServerError)
		return
	}

	filePath := fmt.Sprintf("%s/%s", config.ImageStorageDir, handler.Filename)
	outFile, err := os.Create(filePath)
	if err != nil {
		http.Error(w, "Unable to save the file", http.StatusInternalServerError)
		return
	}
	defer outFile.Close()

	// Copy the uploaded file to the destination
	_, err = io.Copy(outFile, file)
	if err != nil {
		http.Error(w, "Unable to save the file", http.StatusInternalServerError)
		return
	}

	// Update the item record in the database with the image path
	item.ImagePath = filePath
	if err := db.Save(&item).Error; err != nil {
		http.Error(w, "Unable to save image path in database", http.StatusInternalServerError)
		return
	}
	fmt.Println("Image upload called")
	// Return the image path in the response
	w.WriteHeader(http.StatusOK)
	json.NewEncoder(w).Encode(map[string]string{"imagePath": filePath})
}

// GetItemImageHandler retrieves an item's image by item ID.
func GetItemImageHandler(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	itemID := vars["id"]
	// fmt.Println("Getting image")
	// Retrieve the item from the database
	var item Item
	if err := db.First(&item, itemID).Error; err != nil {
		item.ImagePath = "images/default.jpg"
	} else if item.ImagePath == "" {
		item.ImagePath = "images/default.jpg"
	}

	// Open the image file
	imageFile, err := os.Open(item.ImagePath)
	if err != nil {
		// Log the error for debugging, but don't return an HTTP error
		fmt.Println("Error opening image.", err)
		item.ImagePath = "images/default.jpg"
		return
	}
	defer imageFile.Close()

	// Determine the content type of the image
	imageData, err := io.ReadAll(imageFile)
	if err != nil {
		fmt.Println("Error reading image")
		item.ImagePath = "images/default.jpg"
		return
	}
	contentType := http.DetectContentType(imageData)

	// Set the content type header and write the image data to the response
	w.Header().Set("Content-Type", contentType)
	w.Write(imageData)
}

// searchItemsHandler handles the GET /items/search endpoint.
func SearchItemsHandler(w http.ResponseWriter, r *http.Request) {
	query := r.URL.Query().Get("q")
	if query == "" {
		http.Error(w, "Search query is required", http.StatusBadRequest)
		return
	}
	fmt.Println(query)
	var items []Item
	db.Where("name GLOB ? OR description GLOB ?", "*"+query+"*", "*"+query+"*").Find(&items)
	json.NewEncoder(w).Encode(items)

}

// getItemHandler handles the GET /items/{id} endpoint.
func GetItemHandler(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	id := vars["id"]

	var item Item
	if err := db.First(&item, id).Error; err != nil {
		http.Error(w, "Item not found", http.StatusNotFound)
		return
	}

	json.NewEncoder(w).Encode(item)
}

// getItemsInBoxHandler handles the GET /boxes/{id}/items endpoint.
func GetItemsInBoxHandler(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	id := vars["id"]

	var items []Item
	if err := db.Where("box_id = ?", id).Find(&items).Error; err != nil {
		http.Error(w, "Items not found", http.StatusNotFound)
		return
	}

	json.NewEncoder(w).Encode(items)
}

// updateItemHandler handles the PUT /items/{id} endpoint.
func UpdateItemHandler(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	id := vars["id"]

	var item Item
	if err := db.First(&item, id).Error; err != nil {
		http.Error(w, "Item not found", http.StatusNotFound)
		return
	}

	err := json.NewDecoder(r.Body).Decode(&item)
	if err != nil {
		http.Error(w, "Invalid request body", http.StatusBadRequest)
		return
	}
	fmt.Println(item)
	db.Save(&item)
	json.NewEncoder(w).Encode(item)
}

// deleteItemHandler handles the DELETE /items/{id} endpoint.
func DeleteItemHandler(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	id := vars["id"]

	var item Item
	if err := db.First(&item, id).Error; err != nil {
		http.Error(w, "Item not found", http.StatusNotFound)
		return
	}

	db.Delete(&item)
	w.WriteHeader(http.StatusNoContent)
}

// authMiddleware is a middleware function that checks for a valid JWT token in the request header and enables CORS.
func AuthMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// Set CORS headers
		w.Header().Set("Access-Control-Allow-Origin", "*") // Replace "*" with your allowed frontend origin if needed
		w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
		w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")

		// Handle preflight request for CORS
		if r.Method == http.MethodOptions {
			w.WriteHeader(http.StatusOK)
			return
		}

		// Get the token from the request header
		tokenString := r.Header.Get("Authorization")
		if tokenString == "" {
			http.Error(w, "Authorization header missing", http.StatusUnauthorized)
			return
		}

		// Remove "Bearer " prefix from token string
		tokenString = strings.Replace(tokenString, "Bearer ", "", 1)

		// Parse and validate the JWT token
		token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
			// Make sure that the signing method is HMAC
			if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
				return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
			}
			return []byte(config.JWTSecret), nil
		})
		if err != nil || !token.Valid {
			http.Error(w, "Invalid token", http.StatusUnauthorized)
			return
		}

		// Extract the user claims from the token
		if claims, ok := token.Claims.(jwt.MapClaims); ok {
			// Add the "user" claim to the request context
			newCtx := context.WithValue(r.Context(), userKey, claims["username"])
			r = r.WithContext(newCtx)
		} else {
			http.Error(w, "Invalid token claims", http.StatusUnauthorized)
			return
		}

		// Call the next handler in the chain
		next.ServeHTTP(w, r)
	})
}
