import { useEffect } from "react";
import { useLocation } from "wouter";
import { useQuery } from "@tanstack/react-query";
import { User } from "@shared/schema";

export function useRoutineBlocker() {
    const [, setLocation] = useLocation();
    const { data: user } = useQuery<User>({ queryKey: ["/api/user"] });
    const { data: settings } = useQuery<Record<string, string>>({ queryKey: ["/api/admin/settings"] });

    useEffect(() => {
        if (!user || !settings) return;

        const checkRoutine = () => {
            const now = new Date();
            const currentHours = now.getHours();
            const currentMinutes = now.getMinutes();
            const currentTimeVal = currentHours * 60 + currentMinutes;

            // Helper to parse "HH:MM" to minutes
            const parseTime = (t: string) => {
                const [h, m] = t.split(':').map(Number);
                return h * 60 + (m || 0);
            };

            // Helper to check if date is today
            const isToday = (dateStr?: Date | string | null) => {
                if (!dateStr) return false;
                const d = new Date(dateStr);
                return d.getDate() === now.getDate() &&
                    d.getMonth() === now.getMonth() &&
                    d.getFullYear() === now.getFullYear();
            };

            // Evening Routine Check
            const eveningEnabled = settings.evening_routine_enabled !== "false";
            const eveningStartTime = parseTime(settings.evening_routine_time || "22:00"); // 22:00 default

            // If it is Evening time (>= start time), we primarily check Evening Routine.
            if (eveningEnabled) {
                if (currentTimeVal >= eveningStartTime) {
                    // It is evening. Block if evening not done.
                    // We do NOT block for Morning routine anymore if it's evening time (user missed it).
                    if (!isToday(user.lastEveningRoutine)) {
                        return '/focus/routine/evening';
                    }
                    // If evening done, we don't block for morning either.
                    return null;
                }
            }

            // Morning Routine Check (Only if < evening start time or evening disabled)
            const morningEnabled = settings.morning_routine_enabled !== "false";
            if (morningEnabled) {
                const morningStartTime = parseTime(settings.morning_routine_time || "09:00");

                // Block if it's morning time (>= start) AND < evening start (if evening enabled).
                // FIX: Add a hard cutoff (e.g. 13:00 / 1 PM) so morning routine doesn't haunt users all day.
                const HARD_MORNING_CUTOFF = 13 * 60;

                const cutoffTime = eveningEnabled
                    ? Math.min(eveningStartTime, HARD_MORNING_CUTOFF)
                    : HARD_MORNING_CUTOFF;

                if (currentTimeVal >= morningStartTime && currentTimeVal < cutoffTime && !isToday(user.lastMorningRoutine)) {
                    return '/focus/routine/morning';
                }
            }

            return null;
        };

        const target = checkRoutine();
        if (target) {
            // Only redirect if not already there
            if (!window.location.pathname.includes(target)) {
                setLocation(target);
            }
        }

    }, [user, settings, setLocation]);

    // Return a boolean telling if blocking is active, so App can hide Sidebar
    const isMorningBlocked = () => {
        if (!user || !settings) return false;

        const now = new Date();
        const currentTimeVal = now.getHours() * 60 + now.getMinutes();

        const eveningEnabled = settings.evening_routine_enabled !== "false";
        // Safe parse
        const [eh, em] = (settings.evening_routine_time || "22:00").split(':').map(Number);
        const eveningStartVal = (eh || 0) * 60 + (em || 0);

        const morningEnabled = settings.morning_routine_enabled !== "false";
        if (!morningEnabled) return false;

        const [mh, mm] = (settings.morning_routine_time || "09:00").split(':').map(Number);
        const startVal = (mh || 0) * 60 + (mm || 0);

        const HARD_MORNING_CUTOFF = 13 * 60; // 13:00

        // Cutoff: Min of (End of day OR Evening Start) AND Hard Cutoff
        const baseCutoff = eveningEnabled ? eveningStartVal : 24 * 60;
        const cutoffVal = Math.min(baseCutoff, HARD_MORNING_CUTOFF);

        if (currentTimeVal >= startVal && currentTimeVal < cutoffVal && !isSameDay(user.lastMorningRoutine, now)) return true;

        return false;
    };

    const isEveningBlocked = () => {
        if (!user || !settings) return false;

        const now = new Date();
        const currentTimeVal = now.getHours() * 60 + now.getMinutes();

        const eveningEnabled = settings.evening_routine_enabled !== "false";
        if (!eveningEnabled) return false;

        const rawTime = settings.evening_routine_time || "22:00";
        const [eh, em] = rawTime.split(':').map(Number);
        const startVal = (eh || 0) * 60 + (em || 0);

        if (currentTimeVal >= startVal && !isSameDay(user.lastEveningRoutine, now)) return true;

        return false;
    };

    return isMorningBlocked() || isEveningBlocked();
}

function isSameDay(d1: any, d2: Date) {
    if (!d1) return false;
    const d = new Date(d1);
    return d.getDate() === d2.getDate() && d.getMonth() === d2.getMonth() && d.getFullYear() === d2.getFullYear();
}
