"use client";
import Image from "next/image";
import style from "./header.module.css";
import MenuIcon from "@mui/icons-material/Menu";
import NotificationIcon from "@mui/icons-material/NotificationsNone";
import Badge from "@mui/material/Badge";
import { useUserMenuStore } from "@store/UserMenu.Store";
import { HEADER_MODES, HEADER_WIDGETS, useHeaderStore } from "@store/Header.Store";
import { useEffect, useState } from "react";
import useWindowSize from "@hooks/WindowSize";
import Textbox from "../Textbox/Textbox";
import { useNavigation } from "@core/app/hooks/goto";
import { usePathname } from "next/navigation";
import { NO_CATEGORY } from "@core/Models/Categories.type";
import { IconButton } from "@mui/material";
import { useSessionStore } from "@core/Store/Sesion.Store";
import { blurElementsOnLoad } from "@core/helpers/blur";

//import { useSessionStore, useSessionTokenStore } from "@core/Store/Sesion.Store";

export default function Header(): React.ReactElement {
    const menuState = useUserMenuStore();
    const headerState = useHeaderStore();
    const SessionInfo = useSessionStore();
    //const SessionToken = useSessionTokenStore();
    const [showNotificationIcon, setShowNotificationIcon] = useState(false);
    const [windowWidth, windowHeight] = useWindowSize();
    const [filterText, setFilterText] = useState("");
    const [publicFilterText, setPublicFilterText] = useState("");
    const { goTo } = useNavigation();
    const pathName = usePathname();

    useEffect(() => {
        blurElementsOnLoad();
        headerState.setActiveWidget(HEADER_WIDGETS.PUBLIC_FIND);
    }, [SessionInfo.userId]);

    useEffect(() => {
        if (!SessionInfo.loged) {
            setShowNotificationIcon(false);
            return;
        }

        setShowNotificationIcon(true);
    }, [SessionInfo.loged]);

    // useEffect(() => {
    //     console.log("notificationsCount ha cambiado:", headerState.notificationsCount);
    // }, [headerState.notificationsCount]);

    useEffect(() => {
        if (windowWidth < 600) {
            headerState.setState(HEADER_MODES.SMALL);
        } else {
            headerState.setState(HEADER_MODES.LARGE);
        }
    }, [windowWidth, windowHeight]);

    useEffect(() => {
        if (headerState.activeWidget === HEADER_WIDGETS.FIND) {
            const txtObjectFilter = document.getElementById("txtObjectFilter");
            if (txtObjectFilter) {
                txtObjectFilter.focus();
            }
        } else if (headerState.activeWidget === HEADER_WIDGETS.PUBLIC_FIND) {
            const txtPublicFilter = document.getElementById("txtPublicFilter");
            if (txtPublicFilter) {
                txtPublicFilter.focus();
            }
        }
    }, [headerState.activeWidget]);

    useEffect(() => {
        setFilterText(headerState.findText);
    }, [headerState.findText]);

    useEffect(() => {
        setPublicFilterText(headerState.publicFindText);
    }, [headerState.publicFindText]);

    const toggleMenu = () => {
        menuState.setVisible(!menuState.visible);
    };

    const goHome = () => {
        headerState.setActiveWidget(HEADER_WIDGETS.PUBLIC_FIND);
        goTo("/");
    };

    const HeaderLogo = () => {
        let logo = (
            <Image
                className={style.logoText}
                src="/tx-logo-text.svg"
                alt="TurnosXpress logo"
                width={183}
                height={25}
                priority
                onClick={goHome}
            />
        );

        if (headerState.state === HEADER_MODES.SMALL) {
            logo = (
                <Image
                    className={style.logoText}
                    src="/tx-logo-short.svg"
                    alt="TurnosXpress logo"
                    width={32}
                    height={25}
                    priority
                    onClick={goHome}
                />
            );
        }

        return logo;
    };

    const publicSearch = () => {
        if (pathName === "/landing/find") {
            headerState.setPublicFindTrigger(true);
        } else {
            headerState.setPublicFindTrigger(true);
            goTo("/landing/find");
        }
    };

    return (
        <>
            <div className={style.header}>
                <HeaderLogo />
                {headerState.activeWidget === HEADER_WIDGETS.FIND && (
                    <div style={{ marginLeft: "30px", marginRight: "30px", width: "100%" }}>
                        <Textbox
                            name="txtObjectFilter"
                            type="text"
                            value={filterText}
                            placeholder=""
                            width="100%"
                            variant="transparent"
                            icon="search"
                            onChange={(
                                e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>
                            ) => {
                                headerState.setFindText(e.target.value);
                                setFilterText(e.target.value);
                            }}
                        />
                    </div>
                )}
                {headerState.activeWidget === HEADER_WIDGETS.PUBLIC_FIND && (
                    <div
                        style={{
                            marginLeft: "30px",
                            width: "100%",
                            display: "flex",
                            justifyContent: "center",
                            alignItems: "center",
                        }}
                    >
                        <Textbox
                            name="txtPublicFilter"
                            type="text"
                            value={publicFilterText}
                            placeholder="Buscar servicios..."
                            width="80%"
                            style={{ maxWidth: "500px" }}
                            variant="search"
                            icon="search"
                            onChange={(
                                e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>
                            ) => {
                                setPublicFilterText(e.target.value);
                                headerState.setPublicFindText(e.target.value);
                            }}
                            onKeyUp={(
                                e: React.KeyboardEvent<HTMLInputElement | HTMLTextAreaElement>
                            ) => {
                                if (e.key === "Enter") {
                                    //Si no estoy en la pagina de busqueda paso a NO_CATEGORY.
                                    if (pathName !== "/landing/find") {
                                        headerState.setPublicFindCategoryId(NO_CATEGORY);
                                        //console.log("busco desde fuera");
                                    } else {
                                        //console.log("busco desde find");
                                    }
                                    //en caso de estar en la pagina de busqueda respeto la categoria seleccionada.
                                    publicSearch();
                                }
                            }}
                        />
                    </div>
                )}
                {headerState.activeWidget === HEADER_WIDGETS.NONE && (
                    <div style={{ width: "100%" }}>&nbsp;</div>
                )}

                {showNotificationIcon && (
                    <IconButton
                        sx={{ marginRight: "20px" }}
                        onClick={() => goTo("/user/profile/notifications")}
                    >
                        <Badge
                            color="warning"
                            variant={"standard"}
                            badgeContent={headerState.notificationsCount}
                        >
                            <NotificationIcon sx={{ color: "white" }} />
                        </Badge>
                    </IconButton>
                )}

                <MenuIcon sx={{ color: "white" }} onClick={toggleMenu} className={style.menuIcon} />
            </div>
        </>
    );
}
