package scheduling

import (
	"encoding/json"
	"fmt"
	"net/http"
	"time"

	"crussell/db"
	"crussell/mw"
	"log"
)

// --- Types ---
type DefaultHours struct {
	Weekday   int    `json:"weekday"`
	StartTime string `json:"startTime"`
	EndTime   string `json:"endTime"`
	IsOpen    bool   `json:"isOpen"`
}

type DayWorkingHours struct {
	Date      string `json:"date"`
	Weekday   int    `json:"weekday"`
	StartTime string `json:"startTime"`
	EndTime   string `json:"endTime"`
	IsOpen    bool   `json:"isOpen"`
	Source    string `json:"source"` // "default" or "exceptional"
}

// --- Default Hours Handlers ---
func GetDefaultHours(w http.ResponseWriter, r *http.Request) {
	rows, err := db.DB.Query(r.Context(), `
		SELECT weekday, start_time::text, end_time::text, is_open
		FROM working_hours ORDER BY weekday
	`)
	if err != nil {
		http.Error(w, "failed to fetch default hours", http.StatusInternalServerError)
		return
	}
	defer rows.Close()

	var hours []DefaultHours
	for rows.Next() {
		var h DefaultHours
		if err := rows.Scan(&h.Weekday, &h.StartTime, &h.EndTime, &h.IsOpen); err != nil {
			http.Error(w, "failed to scan default hours", http.StatusInternalServerError)
			return
		}
		hours = append(hours, h)
	}

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(hours)
}

func UpdateDefaultHours(w http.ResponseWriter, r *http.Request) {
	var hours []DefaultHours
	if err := json.NewDecoder(r.Body).Decode(&hours); err != nil {
		http.Error(w, "invalid payload", http.StatusBadRequest)
		return
	}

	tx, err := db.DB.Begin(r.Context())
	if err != nil {
		http.Error(w, "failed to start tx", http.StatusInternalServerError)
		return
	}
	defer tx.Rollback(r.Context())

	for _, h := range hours {
		_, err := tx.Exec(r.Context(), `
			UPDATE working_hours
			SET start_time=$1,end_time=$2,is_open=$3
			WHERE weekday=$4
		`, h.StartTime, h.EndTime, h.IsOpen, h.Weekday)
		if err != nil {
			http.Error(w, "failed to update default hours", http.StatusInternalServerError)
			return
		}
	}

	if err := tx.Commit(r.Context()); err != nil {
		http.Error(w, "failed to commit", http.StatusInternalServerError)
		return
	}

	w.WriteHeader(http.StatusNoContent)
}

// --- GetWorkingHours (merged default + applied exceptions, UK-local) ---
func GetWorkingHours(w http.ResponseWriter, r *http.Request) {
	startStr := r.URL.Query().Get("start")
	endStr := r.URL.Query().Get("end")
	if startStr == "" || endStr == "" {
		http.Error(w, "start and end query params required", http.StatusBadRequest)
		return
	}

	ukLocation, _ := time.LoadLocation("Europe/London")
	start, err := time.ParseInLocation("2006-01-02", startStr, ukLocation)
	if err != nil {
		http.Error(w, "invalid start date", http.StatusBadRequest)
		return
	}
	end, err := time.ParseInLocation("2006-01-02", endStr, ukLocation)
	if err != nil {
		http.Error(w, "invalid end date", http.StatusBadRequest)
		return
	}

	// Set to local start/end of day
	start = time.Date(start.Year(), start.Month(), start.Day(), 0, 0, 0, 0, ukLocation)
	end = time.Date(end.Year(), end.Month(), end.Day(), 23, 59, 59, 999999999, ukLocation)

	// Load default hours
	defaultMap := map[int]DefaultHours{}
	defRows, _ := db.DB.Query(r.Context(), `
		SELECT weekday, start_time::text, end_time::text, is_open
		FROM working_hours
	`)
	for defRows.Next() {
		var d DefaultHours
		if err := defRows.Scan(&d.Weekday, &d.StartTime, &d.EndTime, &d.IsOpen); err == nil {
			defaultMap[d.Weekday] = d
		}
	}
	defRows.Close()

	// Load exceptional applications for Mondays in range
	appRows, _ := db.DB.Query(r.Context(), `
		SELECT group_id, week_start
		FROM exceptional_group_applications
		WHERE week_start BETWEEN $1 AND $2
	`, start, end)
	type appEntry struct {
		GroupID   int
		WeekStart time.Time
	}
	apps := []appEntry{}
	groupIDs := []int{}
	for appRows.Next() {
		var a appEntry
		if err := appRows.Scan(&a.GroupID, &a.WeekStart); err == nil {
			a.WeekStart = time.Date(a.WeekStart.Year(), a.WeekStart.Month(), a.WeekStart.Day(), 0, 0, 0, 0, ukLocation)
			apps = append(apps, a)
			groupIDs = append(groupIDs, a.GroupID)
		}
	}
	appRows.Close()

	exHoursMap := map[int]map[int]ExceptionalHours{}
	if len(groupIDs) > 0 {
		query, args, _ := sqlIn("SELECT group_id, weekday, start_time::text, end_time::text, is_open FROM exceptional_working_hours WHERE group_id IN (%s)", groupIDs)
		rows, _ := db.DB.Query(r.Context(), query, args...)
		for rows.Next() {
			var h ExceptionalHours
			if err := rows.Scan(&h.GroupID, &h.Weekday, &h.StartTime, &h.EndTime, &h.IsOpen); err == nil {
				if _, ok := exHoursMap[h.GroupID]; !ok {
					exHoursMap[h.GroupID] = map[int]ExceptionalHours{}
				}
				exHoursMap[h.GroupID][h.Weekday] = h
			}
		}
		rows.Close()
	}

	// Generate final result per day
	var results []DayWorkingHours
	for d := start; !d.After(end); d = d.AddDate(0, 0, 1) {
		weekday := int(d.Weekday())
		if weekday == 0 {
			weekday = 6 // Go Sunday=0 -> our Sunday=6
		} else {
			weekday -= 1
		}

		// Calculate the Monday of this week
		daysSinceMonday := int(d.Weekday()) - 1
		if daysSinceMonday < 0 {
			daysSinceMonday = 6 // Sunday
		}
		weekStart := d.AddDate(0, 0, -daysSinceMonday)
		weekStart = time.Date(weekStart.Year(), weekStart.Month(), weekStart.Day(), 0, 0, 0, 0, ukLocation)

		var applied *ExceptionalHours
		weekStartStr := weekStart.Format("2006-01-02")
		for _, a := range apps {
			appWeekStartStr := a.WeekStart.Format("2006-01-02")
			if appWeekStartStr == weekStartStr {
				if dayHours, ok := exHoursMap[a.GroupID][weekday]; ok {
					applied = &dayHours
				}
				break
			}
		}

		var day DayWorkingHours
		day.Date = d.Format("2006-01-02")
		day.Weekday = weekday

		if applied != nil {
			day.StartTime = applied.StartTime
			day.EndTime = applied.EndTime
			day.IsOpen = applied.IsOpen
			day.Source = "exceptional"
		} else if def, ok := defaultMap[weekday]; ok {
			day.StartTime = def.StartTime
			day.EndTime = def.EndTime
			day.IsOpen = def.IsOpen
			day.Source = "default"
		} else {
			day.StartTime = "00:00"
			day.EndTime = "00:00"
			day.IsOpen = false
			day.Source = "default"
		}

		results = append(results, day)
	}

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(results)
}

// --- helper: sqlIn generates IN queries dynamically for Postgres ---
func sqlIn(query string, args []int) (string, []interface{}, error) {
	inArgs := []interface{}{}
	placeholders := ""
	for i, arg := range args {
		if i > 0 {
			placeholders += ","
		}
		placeholders += fmt.Sprintf("$%d", i+1)
		inArgs = append(inArgs, arg)
	}
	query = fmt.Sprintf(query, placeholders)
	return query, inArgs, nil
}

// --- Types for Available Hours ---
type TimeSlot struct {
	StartTime string `json:"startTime"`
	EndTime   string `json:"endTime"`
}

type DayAvailableHours struct {
	Date     string     `json:"date"`
	Weekday  int        `json:"weekday"`
	IsOpen   bool       `json:"isOpen"`
	Slots    []TimeSlot `json:"slots"`
	Source   string     `json:"source"`
	Blockers []TimeSlot `json:"blockers,omitempty"`
}

// --- GetAvailableHours (with bookings, UK-local) ---
func GetAvailableHours(w http.ResponseWriter, r *http.Request) {
	startStr := r.URL.Query().Get("start")
	endStr := r.URL.Query().Get("end")
	if startStr == "" || endStr == "" {
		http.Error(w, "start and end query params required", http.StatusBadRequest)
		return
	}

	ukLocation, _ := time.LoadLocation("Europe/London")
	start, _ := time.ParseInLocation("2006-01-02", startStr, ukLocation)
	end, _ := time.ParseInLocation("2006-01-02", endStr, ukLocation)

	// set start/end of day
	start = time.Date(start.Year(), start.Month(), start.Day(), 0, 0, 0, 0, ukLocation)
	end = time.Date(end.Year(), end.Month(), end.Day(), 23, 59, 59, 999999999, ukLocation)

	// Clean up old reservations (older than 1 hour)
	if err := CleanupOldReservations(r.Context()); err != nil {
		log.Printf("Failed to cleanup old reservations: %v", err)
	}

	// Anonymize stale guest accounts (6+ months after last booking)
	if err := AnonymizeStaleGuestAccounts(r.Context()); err != nil {
		log.Printf("Failed to anonymize stale guest accounts: %v", err)
	}

	// Load default hours
	defaultMap := map[int]DefaultHours{}
	defRows, _ := db.DB.Query(r.Context(), `SELECT weekday, start_time::text, end_time::text, is_open FROM working_hours`)
	for defRows.Next() {
		var d DefaultHours
		if err := defRows.Scan(&d.Weekday, &d.StartTime, &d.EndTime, &d.IsOpen); err == nil {
			defaultMap[d.Weekday] = d
		}
	}
	defRows.Close()

	// Load exceptional applications for Mondays in range
	appRows, _ := db.DB.Query(r.Context(), `
		SELECT group_id, week_start
		FROM exceptional_group_applications
		WHERE week_start BETWEEN $1 AND $2
	`, start, end)
	type appEntry struct {
		GroupID   int
		WeekStart time.Time
	}
	apps := []appEntry{}
	groupIDs := []int{}
	for appRows.Next() {
		var a appEntry
		if err := appRows.Scan(&a.GroupID, &a.WeekStart); err == nil {
			a.WeekStart = time.Date(a.WeekStart.Year(), a.WeekStart.Month(), a.WeekStart.Day(), 0, 0, 0, 0, ukLocation)
			apps = append(apps, a)
			groupIDs = append(groupIDs, a.GroupID)
		}
	}
	appRows.Close()

	exHoursMap := map[int]map[int]ExceptionalHours{}
	if len(groupIDs) > 0 {
		query, args, _ := sqlIn("SELECT group_id, weekday, start_time::text, end_time::text, is_open FROM exceptional_working_hours WHERE group_id IN (%s)", groupIDs)
		rows, _ := db.DB.Query(r.Context(), query, args...)
		for rows.Next() {
			var h ExceptionalHours
			if err := rows.Scan(&h.GroupID, &h.Weekday, &h.StartTime, &h.EndTime, &h.IsOpen); err == nil {
				if _, ok := exHoursMap[h.GroupID]; !ok {
					exHoursMap[h.GroupID] = map[int]ExceptionalHours{}
				}
				exHoursMap[h.GroupID][h.Weekday] = h
			}
		}
		rows.Close()
	}

	// Load bookings
	bookingRows, _ := db.DB.Query(r.Context(), `
		SELECT
			b.start_time,
			COALESCE(SUM(
				CASE
					WHEN bs.override_duration_minutes IS NOT NULL AND bs.override_duration_minutes > 0
						THEN bs.override_duration_minutes
					ELSE s.duration_minutes
				END
			), 0) AS total_duration
		FROM bookings b
		LEFT JOIN booking_services bs ON b.id = bs.booking_id
		LEFT JOIN services s ON bs.service_id = s.id
		WHERE b.start_time >= $1 AND b.start_time <= $2
		GROUP BY b.id, b.start_time
		ORDER BY b.start_time
	`, start, end)

	bookings := map[string][]TimeSlot{}
	for bookingRows.Next() {
		var t time.Time
		var dur int
		if err := bookingRows.Scan(&t, &dur); err == nil {
			t = t.In(ukLocation)
			dateStr := t.Format("2006-01-02")
			endTime := t.Add(time.Duration(dur) * time.Minute)
			bookings[dateStr] = append(bookings[dateStr], TimeSlot{
				StartTime: t.Format("15:04"),
				EndTime:   endTime.Format("15:04"),
			})
		}
	}
	bookingRows.Close()

	// Load time blockers
	blockers, err := GetTimeBlockersInRange(r.Context(), start, end)
	if err != nil {
		log.Printf("Failed to load time blockers: %v", err)
	}
	// Convert blockers to map by date for easier lookup

	blockerMap := make(map[string][]TimeSlot)

	for _, blocker := range blockers {

		dateStr := blocker.StartTime.Format("2006-01-02")

		endTime := blocker.StartTime.Add(time.Duration(blocker.DurationMinutes) * time.Minute)

		blockerMap[dateStr] = append(blockerMap[dateStr], TimeSlot{

			StartTime: blocker.StartTime.Format("15:04"),

			EndTime: endTime.Format("15:04"),
		})

	}

	// Check if user is admin
	isAdmin := false
	if userRole, ok := r.Context().Value(mw.UserRoleKey).(string); ok {
		isAdmin = userRole == "admin"
	}

	// Generate available slots per day
	var results []DayAvailableHours
	for d := start; !d.After(end); d = d.AddDate(0, 0, 1) {
		weekday := int(d.Weekday())
		if weekday == 0 {
			weekday = 6
		} else {
			weekday -= 1
		}

		// Calculate the Monday of this week
		daysSinceMonday := int(d.Weekday()) - 1
		if daysSinceMonday < 0 {
			daysSinceMonday = 6 // Sunday
		}
		weekStart := d.AddDate(0, 0, -daysSinceMonday)
		weekStart = time.Date(weekStart.Year(), weekStart.Month(), weekStart.Day(), 0, 0, 0, 0, ukLocation)

		var applied *ExceptionalHours
		weekStartStr := weekStart.Format("2006-01-02")
		for _, a := range apps {
			appWeekStartStr := a.WeekStart.Format("2006-01-02")
			if appWeekStartStr == weekStartStr {
				if dayHours, ok := exHoursMap[a.GroupID][weekday]; ok {
					applied = &dayHours
				}
				break
			}
		}

		var day DayAvailableHours
		day.Date = d.Format("2006-01-02")
		day.Weekday = weekday

		var baseStart, baseEnd string
		var isOpen bool
		if applied != nil {
			baseStart = applied.StartTime
			baseEnd = applied.EndTime
			isOpen = applied.IsOpen
			day.Source = "exceptional"
		} else if def, ok := defaultMap[weekday]; ok {
			baseStart = def.StartTime
			baseEnd = def.EndTime
			isOpen = def.IsOpen
			day.Source = "default"
		} else {
			baseStart = "00:00"
			baseEnd = "00:00"
			isOpen = false
			day.Source = "default"
		}

		day.IsOpen = isOpen
		if isOpen {
			slots := []TimeSlot{{StartTime: baseStart, EndTime: baseEnd}}
			if booked, ok := bookings[day.Date]; ok {
				slots = subtractTimeSlots(slots, booked)
			}
			day.Slots = slots
			// Handle time blockers
			if !isAdmin {
				// Regular users: subtract blockers from available slots
				if dayBlockers, ok := blockerMap[day.Date]; ok {
					day.Slots = subtractTimeSlots(day.Slots, dayBlockers)
				}

				// Late night lock: after 22:00, block next morning 00:00-11:00 for non-admin users
				now := time.Now()
				if !isAdmin && now.Hour() >= 22 {
					// Check if this is tomorrow's date
					tomorrow := now.AddDate(0, 0, 1)
					tomorrowStr := tomorrow.Format("2006-01-02")
					if day.Date == tomorrowStr {
						// Add a fake blocker for 00:00-11:00
						lateNightBlock := TimeSlot{
							StartTime: "00:00",
							EndTime:   "11:00",
						}
						day.Slots = subtractTimeSlots(day.Slots, []TimeSlot{lateNightBlock})
					}
				}
			} else {
				// Admins: keep blockers visible for warning display
				if dayBlockers, ok := blockerMap[day.Date]; ok {
					day.Blockers = dayBlockers
				}
			}
		} else {
			day.Slots = []TimeSlot{}
		}

		results = append(results, day)
	}

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(results)
}

// subtractTimeSlots removes gaps from available slots
// Returns the remaining available time slots after removing the gaps
func subtractTimeSlots(available []TimeSlot, gaps []TimeSlot) []TimeSlot {
	if len(gaps) == 0 {
		return available
	}

	result := []TimeSlot{}

	for _, slot := range available {
		current := []TimeSlot{slot}

		// Apply each gap
		for _, gap := range gaps {
			var temp []TimeSlot
			for _, s := range current {
				// Check if gap overlaps with this slot
				if gap.EndTime <= s.StartTime || gap.StartTime >= s.EndTime {
					// No overlap, keep the slot as is
					temp = append(temp, s)
				} else {
					// Overlap exists, split the slot
					if s.StartTime < gap.StartTime {
						// Keep the part before the gap
						temp = append(temp, TimeSlot{
							StartTime: s.StartTime,
							EndTime:   gap.StartTime,
						})
					}
					if gap.EndTime < s.EndTime {
						// Keep the part after the gap
						temp = append(temp, TimeSlot{
							StartTime: gap.EndTime,
							EndTime:   s.EndTime,
						})
					}
				}
			}
			current = temp
		}

		result = append(result, current...)
	}

	return result
}
