import React, { Component, Profiler } from "react";
import Box from "@mui/material/Box";
import Container from "@mui/material/Container";
import Button from "@mui/material/Button";
import Typography from "@mui/material/Typography";
import Collapse from "@mui/material/Collapse";
import { Link } from "react-router-dom";
import HomeIcon from "@mui/icons-material/Home";
import FiberNewIcon from '@mui/icons-material/FiberNew';
import LocalShippingIcon from "@mui/icons-material/LocalShipping";
import SettingsIcon from "@mui/icons-material/Settings";
import MenuIcon from "@mui/icons-material/Menu";
import CloseIcon from "@mui/icons-material/Close";
import { withI18n } from "../../i18n/withTranslation.js";

class CategoryList extends Component {
  constructor(props) {
    super(props);
    //const { i18n } = props;
    const categories = window.categoryService.getSync(209);

    this.state = {
      categories: categories && categories.children && categories.children.length > 0 ? categories.children : [],
      mobileMenuOpen: false,
      activeCategoryId: null // Will be set properly after categories are loaded
    };
    this.productCategoryCheckInterval = null;
  }

  componentDidMount() {
    console.log("CategoryList componentDidMount - Debug info:");
    console.log("  languageContext:", this.props.languageContext);
    console.log("  i18n.language:", this.props.i18n?.language);
    console.log("  sessionStorage i18nextLng:", typeof sessionStorage !== 'undefined' ? sessionStorage.getItem('i18nextLng') : 'N/A');
    console.log("  localStorage i18nextLng:", typeof localStorage !== 'undefined' ? localStorage.getItem('i18nextLng') : 'N/A');

    const currentLanguage = this.props.languageContext?.currentLanguage || this.props.i18n.language;

    // ALWAYS reload categories to ensure correct language
    console.log("CategoryList componentDidMount: ALWAYS RELOADING categories for language", currentLanguage);
    this.setState({ categories: [] }); // Clear any cached categories
    window.categoryService.get(209, currentLanguage).then((response) => {
      console.log("categoryService.get response for language '" + currentLanguage + "':", response);
      if (response.children && response.children.length > 0) {
        console.log("Setting categories with", response.children.length, "items");
        console.log("First category name:", response.children[0]?.name);
        this.setState({
          categories: response.children,
          activeCategoryId: this.setLevel1CategoryId(this.props.activeCategoryId)
        });
      }
    });
  }

  componentDidUpdate(prevProps) {
    console.log("componentDidUpdate", prevProps.languageContext?.currentLanguage, this.props.languageContext?.currentLanguage);
    if (prevProps.languageContext?.currentLanguage !== this.props.languageContext?.currentLanguage) {
      this.setState({
        categories: [],
        activeCategoryId: null
      }, () => {
        window.categoryService.get(209, this.props.languageContext?.currentLanguage || this.props.i18n.language).then((response) => {
          console.log("response", response);
          if (response.children && response.children.length > 0) {
            this.setState({
              categories: response.children,
              activeCategoryId: this.setLevel1CategoryId(this.props.activeCategoryId)
            });
          }
        });
      });
    }
    if (prevProps.activeCategoryId !== this.props.activeCategoryId) {
      this.setLevel1CategoryId(this.props.activeCategoryId);
    }
  }


  setLevel1CategoryId = (input) => {
    if (input) {
      const language = this.props.languageContext?.currentLanguage || this.props.i18n.language;
      const categoryTreeCache = window.categoryService.getSync(209, language);

      if (categoryTreeCache && categoryTreeCache.children) {
        let level1CategoryId = null;

        // Check if input is already a numeric level 1 category ID
        const inputAsNumber = parseInt(input);
        if (!isNaN(inputAsNumber)) {
          // Check if this is already a level 1 category ID
          const level1Category = categoryTreeCache.children.find(cat => cat.id === inputAsNumber);
          if (level1Category) {
            console.log("Input is already a level 1 category ID:", inputAsNumber);
            level1CategoryId = inputAsNumber;
          } else {
            // It's a category ID, find its level 1 parent
            const findLevel1FromId = (categories, targetId) => {
              for (const category of categories) {
                if (category.id === targetId) {
                  return category.parentId === 209 ? category.id : findLevel1FromId(categoryTreeCache.children, category.parentId);
                }
                if (category.children && category.children.length > 0) {
                  const result = findLevel1FromId(category.children, targetId);
                  if (result) return result;
                }
              }
              return null;
            };
            level1CategoryId = findLevel1FromId(categoryTreeCache.children, inputAsNumber);
          }
        } else {
          // It's an SEO name, find the level 1 category
          const findLevel1FromSeoName = (categories, targetSeoName, level1Id = null) => {
            for (const category of categories) {
              const currentLevel1Id = level1Id || category.id;

              if (category.seoName === targetSeoName) {
                return currentLevel1Id;
              }

              if (category.children && category.children.length > 0) {
                const result = findLevel1FromSeoName(category.children, targetSeoName, currentLevel1Id);
                if (result) return result;
              }
            }
            return null;
          };
          level1CategoryId = findLevel1FromSeoName(categoryTreeCache.children, input);
        }

        this.setState({
          activeCategoryId: level1CategoryId
        });
        return;
      }
    }
    this.setState({ activeCategoryId: null });
  }



  handleMobileMenuToggle = () => {
    this.setState(prevState => ({
      mobileMenuOpen: !prevState.mobileMenuOpen
    }));
  };

  handleMobileCategoryClick = () => {
    // Close the mobile menu when a category is selected
    this.setState({
      mobileMenuOpen: false
    });
  };

  componentWillUnmount() {
    if (this.productCategoryCheckInterval) {
      clearInterval(this.productCategoryCheckInterval);
      this.productCategoryCheckInterval = null;
    }
  }

  /**
   * Which nav item should appear active: home, konfigurator, neu, bald, a level-1 category id, or null.
   * neu/bald are not in the category tree as seoNames, so pathname / explicit props must drive them.
   * Home vs Konfigurator both had categoryId null from the app; pathname disambiguates.
   */
  getNavHighlightKey() {
    const pathname = this.props.pathname || "";
    if (pathname === "/") return "home";
    if (pathname === "/Konfigurator" || pathname.startsWith("/Konfigurator/")) return "konfigurator";
    if (pathname === "/Kategorie/neu" || this.props.activeCategoryId === "neu") return "neu";
    if (pathname === "/Kategorie/bald" || this.props.activeCategoryId === "bald") return "bald";
    return this.state.activeCategoryId;
  }

  render() {
    const { categories, mobileMenuOpen } = this.state;
    const navKey = this.getNavHighlightKey();

    const renderCategoryRow = (categories, isMobile = false) => (
      <Box
        sx={{
          display: "flex",
          justifyContent: "flex-start",
          alignItems: "center",
          flexWrap: "wrap",
          overflowX: "visible",
          flexDirection: isMobile ? "column" : "row",
          py: 0.5, // Add vertical padding to prevent border clipping
        }}
      >
        <Button
          component={Link}
          to="/"
          color="inherit"
          size="small"
          aria-label="Zur Startseite"
          onClick={isMobile ? this.handleMobileCategoryClick : undefined}
          sx={{
            fontSize: "0.75rem",
            textTransform: "none",
            whiteSpace: "nowrap",
            opacity: 0.9,
            mx: isMobile ? 0 : 0.5,
            my: 0.25,
            minWidth: isMobile ? "100%" : "auto",
            borderRadius: 1,
            justifyContent: isMobile ? "flex-start" : "center",
            transition: "all 0.2s ease",
            textShadow: "0 1px 2px rgba(0,0,0,0.3)",
            position: "relative",
            ...(navKey === "home" && {
              bgcolor: "#fff",
              textShadow: "none",
              opacity: 1,
            }),
            "&:hover": {
              opacity: 1,
              bgcolor: "#fff",
              textShadow: "none",
              "& .MuiSvgIcon-root": {
                color: "#2e7d32 !important",
              },
              "& .bold-text": {
                color: "#2e7d32 !important",
              },
              "& .thin-text": {
                color: "transparent !important",
              },
            },
          }}
        >
          <HomeIcon sx={{
            fontSize: "1rem",
            mr: isMobile ? 1 : 0,
            color: navKey === "home" ? "#2e7d32" : "inherit"
          }} />
          {isMobile && (
            <Box sx={{ position: "relative", display: "inline-block" }}>
              {/* Bold text (always rendered to set width) */}
              <Box
                className="bold-text"
                sx={{
                  fontWeight: "bold",
                  color: navKey === "home" ? "#2e7d32" : "transparent",
                  position: "relative",
                  zIndex: 2,
                }}
              >
                {this.props.t ? this.props.t('navigation.home') : 'Startseite'}
              </Box>
              {/* Thin text (positioned on top) */}
              <Box
                className="thin-text"
                sx={{
                  fontWeight: "400",
                  color: navKey === "home" ? "transparent" : "inherit",
                  position: "absolute",
                  top: 0,
                  left: 0,
                  zIndex: 1,
                }}
              >
                {this.props.t ? this.props.t('navigation.home') : 'Startseite'}
              </Box>
            </Box>
          )}
        </Button>

        <Button
          component={Link}
          to="/Kategorie/neu"
          color="inherit"
          size="small"
          aria-label="Neuheiten"
          onClick={isMobile ? this.handleMobileCategoryClick : undefined}
          sx={{
            fontSize: "0.75rem",
            textTransform: "none",
            whiteSpace: "nowrap",
            opacity: 0.9,
            mx: isMobile ? 0 : 0.5,
            my: 0.25,
            minWidth: isMobile ? "100%" : "auto",
            borderRadius: 1,
            justifyContent: isMobile ? "flex-start" : "center",
            transition: "all 0.2s ease",
            textShadow: "0 1px 2px rgba(0,0,0,0.3)",
            position: "relative",
            ...(navKey === "neu" && {
              bgcolor: "#fff",
              textShadow: "none",
              opacity: 1,
            }),
            "&:hover": {
              opacity: 1,
              bgcolor: "#fff",
              textShadow: "none",
              "& .MuiSvgIcon-root": {
                color: "#2e7d32 !important",
              },
              "& .bold-text": {
                color: "#2e7d32 !important",
              },
              "& .thin-text": {
                color: "transparent !important",
              },
            },
          }}
        >
          <FiberNewIcon sx={{
            fontSize: "1rem",
            mr: isMobile ? 1 : 0,
            color: navKey === "neu" ? "#2e7d32" : "inherit"
          }} />
          {isMobile && (
            <Box sx={{ position: "relative", display: "inline-block" }}>
              {/* Bold text (always rendered to set width) */}
              <Box
                className="bold-text"
                sx={{
                  fontWeight: "bold",
                  color: navKey === "neu" ? "#2e7d32" : "transparent",
                  position: "relative",
                  zIndex: 2,
                }}
              >
                {this.props.t ? this.props.t('navigation.new') : 'Neuheiten'}
              </Box>
              {/* Thin text (positioned on top) */}
              <Box
                className="thin-text"
                sx={{
                  fontWeight: "400",
                  color: navKey === "neu" ? "transparent" : "inherit",
                  position: "absolute",
                  top: 0,
                  left: 0,
                  zIndex: 1,
                }}
              >
                {this.props.t ? this.props.t('navigation.new') : 'Neuheiten'}
              </Box>
            </Box>
          )}
        </Button>

        <Button
          component={Link}
          to="/Kategorie/bald"
          color="inherit"
          size="small"
          aria-label={this.props.t ? this.props.t('navigation.soon') : 'Demnächst'}
          onClick={isMobile ? this.handleMobileCategoryClick : undefined}
          sx={{
            fontSize: "0.75rem",
            textTransform: "none",
            whiteSpace: "nowrap",
            opacity: 0.9,
            mx: isMobile ? 0 : 0.5,
            my: 0.25,
            minWidth: isMobile ? "100%" : "auto",
            borderRadius: 1,
            justifyContent: isMobile ? "flex-start" : "center",
            transition: "all 0.2s ease",
            textShadow: "0 1px 2px rgba(0,0,0,0.3)",
            position: "relative",
            ...(navKey === "bald" && {
              bgcolor: "#fff",
              textShadow: "none",
              opacity: 1,
            }),
            "&:hover": {
              opacity: 1,
              bgcolor: "#fff",
              textShadow: "none",
              "& .MuiSvgIcon-root": {
                color: "#2e7d32 !important",
              },
              "& .bold-text": {
                color: "#2e7d32 !important",
              },
              "& .thin-text": {
                color: "transparent !important",
              },
            },
          }}
        >
          <LocalShippingIcon sx={{
            fontSize: "1rem",
            mr: isMobile ? 1 : 0,
            color: navKey === "bald" ? "#2e7d32" : "inherit"
          }} />
          {isMobile && (
            <Box sx={{ position: "relative", display: "inline-block" }}>
              <Box
                className="bold-text"
                sx={{
                  fontWeight: "bold",
                  color: navKey === "bald" ? "#2e7d32" : "transparent",
                  position: "relative",
                  zIndex: 2,
                }}
              >
                {this.props.t ? this.props.t('navigation.soon') : 'Demnächst'}
              </Box>
              <Box
                className="thin-text"
                sx={{
                  fontWeight: "400",
                  color: navKey === "bald" ? "transparent" : "inherit",
                  position: "absolute",
                  top: 0,
                  left: 0,
                  zIndex: 1,
                }}
              >
                {this.props.t ? this.props.t('navigation.soon') : 'Demnächst'}
              </Box>
            </Box>
          )}
        </Button>


        {categories.length > 0 ? (
          <>
            {categories.map((category) => {

              return (
                <Button
                  key={category.id}
                  component={Link}
                  to={`/Kategorie/${category.seoName}`}
                  color="inherit"
                  size="small"
                  onClick={isMobile ? this.handleMobileCategoryClick : undefined}
                  sx={{
                    fontSize: "0.75rem",
                    textTransform: "none",
                    whiteSpace: "nowrap",
                    opacity: 0.9,
                    mx: isMobile ? 0 : 0.5,
                    my: 0.25,
                    minWidth: isMobile ? "100%" : "auto",
                    borderRadius: 1,
                    justifyContent: isMobile ? "flex-start" : "center",
                    transition: "all 0.2s ease",
                    textShadow: "0 1px 2px rgba(0,0,0,0.3)",
                    position: "relative",
                    ...(navKey === category.id && {
                      bgcolor: "#fff",
                      textShadow: "none",
                      opacity: 1,
                    }),
                    "&:hover": {
                      opacity: 1,
                      bgcolor: "#fff",
                      textShadow: "none",
                      "& .bold-text": {
                        color: "#2e7d32 !important",
                      },
                      "& .thin-text": {
                        color: "transparent !important",
                      },
                    },
                  }}
                >
                  <Box sx={{ position: "relative", display: "inline-block" }}>
                    {/* Bold text (always rendered to set width) */}
                    <Box
                      className="bold-text"
                      sx={{
                        fontWeight: "bold",
                        color: navKey === category.id ? "#2e7d32" : "transparent",
                        position: "relative",
                        zIndex: 2,
                      }}
                    >
                      {category.name}
                    </Box>
                    {/* Thin text (positioned on top) */}
                    <Box
                      className="thin-text"
                      sx={{
                        fontWeight: "400",
                        color: navKey === category.id ? "transparent" : "inherit",
                        position: "absolute",
                        top: 0,
                        left: 0,
                        zIndex: 1,
                      }}
                    >
                      {category.name}
                    </Box>
                  </Box>
                </Button>
              );
            })}
          </>
        ) : (!isMobile && (
          <Typography
            variant="caption"
            color="inherit"
            sx={{
              display: "inline-flex",
              alignItems: "center",
              height: "33px", // Match small button height
              px: 1,
              fontSize: "0.75rem",
              opacity: 0.9,
            }}
          >
            &nbsp;
          </Typography>
        )
        )}
        <Button
          component={Link}
          to="/Konfigurator"
          color="inherit"
          size="small"
          aria-label={this.props.t ? this.props.t('navigation.konfiguratorAria') : 'Zum Konfigurator'}
          onClick={isMobile ? this.handleMobileCategoryClick : undefined}
          sx={{
            fontSize: "0.75rem",
            textTransform: "none",
            whiteSpace: "nowrap",
            opacity: 0.9,
            mx: isMobile ? 0 : 0.5,
            my: 0.25,
            minWidth: isMobile ? "100%" : "auto",
            borderRadius: 1,
            justifyContent: isMobile ? "flex-start" : "center",
            transition: "all 0.2s ease",
            textShadow: "0 1px 2px rgba(0,0,0,0.3)",
            position: "relative",
            ...(navKey === "konfigurator" && {
              bgcolor: "#fff",
              textShadow: "none",
              opacity: 1,
            }),
            "&:hover": {
              opacity: 1,
              bgcolor: "#fff",
              textShadow: "none",
              "& .MuiSvgIcon-root": {
                color: "#2e7d32 !important",
              },
              "& .bold-text": {
                color: "#2e7d32 !important",
              },
              "& .thin-text": {
                color: "transparent !important",
              },
            },
          }}
        >
          <SettingsIcon sx={{
            fontSize: "1rem",
            mr: isMobile ? 1 : 0,
            color: navKey === "konfigurator" ? "#2e7d32" : "inherit"
          }} />
          {isMobile && (
            <Box sx={{ position: "relative", display: "inline-block" }}>
              {/* Bold text (always rendered to set width) */}
              <Box
                className="bold-text"
                sx={{
                  fontWeight: "bold",
                  color: navKey === "konfigurator" ? "#2e7d32" : "transparent",
                  position: "relative",
                  zIndex: 2,
                }}
              >
                {this.props.t ? this.props.t('sections.konfigurator') : 'Konfigurator'}
              </Box>
              {/* Thin text (positioned on top) */}
              <Box
                className="thin-text"
                sx={{
                  fontWeight: "400",
                  color: navKey === "konfigurator" ? "transparent" : "inherit",
                  position: "absolute",
                  top: 0,
                  left: 0,
                  zIndex: 1,
                }}
              >
                {this.props.t ? this.props.t('sections.konfigurator') : 'Konfigurator'}
              </Box>
            </Box>
          )}
        </Button>

      </Box>
    );

    const onRenderCallback = (id, phase, actualDuration) => {
      if (actualDuration > 50) {
        console.warn(
          `CategoryList render took ${actualDuration}ms in ${phase} phase`
        );
      }
    };

    return (
      <Profiler id="CategoryList" onRender={onRenderCallback}>
        {/* Desktop Menu - Hidden on xs, shown on sm and up */}
        <Box
          sx={{
            width: "100%",
            bgcolor: "primary.dark",
            display: { xs: "none", sm: "block" },
          }}
        >
          <Container maxWidth="lg" sx={{ px: 2 }}>
            {renderCategoryRow(categories, false)}
          </Container>
        </Box>

        {/* Mobile Menu - Shown only on xs screens */}
        <Box
          sx={{
            width: "100%",
            bgcolor: "primary.dark",
            display: { xs: "block", sm: "none" },
          }}
        >
          <Container maxWidth="lg" sx={{ px: 2 }}>
            {/* Toggle Button */}
            <Box
              sx={{
                display: "flex",
                justifyContent: "space-between",
                alignItems: "center",
                py: 1,
                cursor: "pointer",
                "&:hover": {
                  bgcolor: "rgba(255,255,255,0.1)"
                }
              }}
              onClick={this.handleMobileMenuToggle}
              role="button"
              tabIndex={0}
              aria-label={this.props.t ?
                (mobileMenuOpen ? this.props.t('navigation.categoriesClose') : this.props.t('navigation.categoriesOpen')) :
                (mobileMenuOpen ? "Kategorien schließen" : "Kategorien öffnen")
              }
              onKeyDown={(e) => {
                if (e.key === 'Enter' || e.key === ' ') {
                  e.preventDefault();
                  this.handleMobileMenuToggle();
                }
              }}
            >
              <Typography variant="subtitle2" color="inherit" sx={{
                fontWeight: "bold",
                textShadow: "0 1px 2px rgba(0,0,0,0.3)"
              }}>
                {this.props.t ? this.props.t('navigation.categories') : 'Kategorien'}
              </Typography>
              <Box sx={{ display: "flex", alignItems: "center" }}>
                {mobileMenuOpen ? <CloseIcon /> : <MenuIcon />}
              </Box>
            </Box>

            {/* Collapsible Menu Content */}
            <Collapse in={mobileMenuOpen}>
              <Box sx={{ pb: 2 }}>
                {/* Level 1 Categories - Only level shown in mobile menu */}
                {renderCategoryRow(categories, true)}
              </Box>
            </Collapse>
          </Container>
        </Box>
      </Profiler>
    );
  }
}

export default withI18n()(CategoryList);
