import React from "react";
import {
  AppBar,
  Toolbar,
  Typography,
  IconButton,
  Avatar,
  Box,
  useTheme,
  useMediaQuery,
  Tooltip,
  Button,
} from "@mui/material";
import { useSidebar } from "../components/sidebarContext";
import { useNavigate } from "react-router-dom";
import MenuIcon from "@mui/icons-material/Menu";
import NotificationsIcon from "@mui/icons-material/Notifications";
import themestyle from "../theme";
import logo from "../assets/logo-bg.png";
import {
  deepOrange,
  deepPurple,
  teal,
  indigo,
  pink,
  blue,
  green,
} from "@mui/material/colors";
import { TEXT ,PROFILE_TEXT} from "../const";
import { GET_CUSTOMER_ID } from "../graphql/query";
import { useQuery, useMutation } from "@apollo/client";
import { Link as RouterLink } from "react-router-dom";

const Header: React.FC<{ shouldHideSidebar: boolean }> = ({
  shouldHideSidebar,
}) => {
  const { toggleSidebar } = useSidebar();
  const navigate = useNavigate();
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down("sm"));

    const storedUser = JSON.parse(localStorage.getItem("user") || "{}");
    const id = storedUser?.id || "";
  
    const { loading, error, data, refetch } = useQuery(GET_CUSTOMER_ID, {
      variables: { id },
    });
  
    const customerData = data?.getCustomer || {};
  
    const displayName =
      customerData.username && customerData.username.toLowerCase() !== "unknown"
        ? customerData.username
        : PROFILE_TEXT.DEFAULT_NAME;
    const email = customerData.email || "";

  const getInitials = (name: string): string => {
    if (!name || name.toLowerCase() === "customer") return "C";
    const words = name.trim().split(/\s+/);
    if (words.length === 1) return words[0][0]?.toUpperCase() || "U";
    return (words[0][0] + (words[1]?.[0] || "")).toUpperCase();
  };

  const getAvatarColor = (name: string): string => {
    const colors = [
      deepOrange[500],
      deepPurple[500],
      teal[500],
      indigo[500],
      pink[500],
      blue[500],
      green[500],
    ];
    const hash = name
      .split("")
      .reduce((acc, char) => acc + char.charCodeAt(0), 0);
    return colors[hash % colors.length];
  };

  const initials = getInitials(displayName);
  const avatarColor = getAvatarColor(displayName);

  const renderTooltipContent = () => (
    <Box
      sx={{
        bgcolor: themestyle.colors.white,
        color: themestyle.colors.black,
        p: 2,
        borderRadius: "8px",
        boxShadow: "0px 4px 12px rgba(0, 0, 0, 0.2)",
        maxWidth: { xs: "250px", sm: "300px" },
      }}
    >
      <Typography
        variant="subtitle1"
        sx={{
          fontFamily: themestyle.fontFamily.lato,
          fontWeight: 500,
          mb: 1,
        }}
      >
        {TEXT.USERNAME}
        {displayName}
      </Typography>
      <Typography
        variant="body2"
        sx={{
          fontFamily: themestyle.fontFamily.lato,
          color: themestyle.colors.textSecondary,
          mb: 2,
        }}
      >
        {TEXT.EMAIL}
        {email}
      </Typography>
      <Button
        variant="contained"
        size="small"
        component={RouterLink}          
        to="/profile"
        sx={{
          bgcolor: themestyle.colors.secondary,
          color: "#fff",
          fontFamily: themestyle.fontFamily.lato,
          textTransform: "none",
          width: "100%",
          "&:hover": {
            bgcolor: themestyle.colors.secondaryDark,
          },
        }}
      >
        More Info
      </Button>
    </Box>
  );

  return (
    <AppBar
      position="fixed"
      sx={{
        backgroundColor: themestyle.colors.white,
        color: themestyle.colors.black,
        boxShadow: "0px 2px 4px rgba(0, 0, 0, 0.1)",
        zIndex: 1400,
      }}
    >
      <Toolbar sx={{ justifyContent: "space-between" }}>
        <Box sx={{ display: "flex", alignItems: "center"}}>
          {!shouldHideSidebar && (
            <IconButton
              edge="start"
              color="inherit"
              onClick={toggleSidebar}
              sx={{ mr: 2 }}
              aria-label="Toggle sidebar"
            >
              <MenuIcon />
            </IconButton>
          )}
          <img src={logo} alt="Intelliwealth Logo" style={{ height: "40px" }} />
        </Box>
        <Box sx={{ display: "flex", alignItems: "center" }}>
          {!isMobile && (
            <Typography
              sx={{
                fontFamily: themestyle.fontFamily.lato,
                fontSize: isMobile ? "12px" : "16px",
                fontWeight: 500,
                color: themestyle.colors.black,
                mr: isMobile ? 1 : 2,
                display: isMobile ? "inline" : "inline",
                overflow: "hidden",
                textOverflow: "ellipsis",
                whiteSpace: "nowrap",
                maxWidth: isMobile ? "80px" : "150px",
              }}
            >
              {displayName}
            </Typography>
          )}
          <IconButton
            color="inherit"
            sx={{ mr: isMobile ? 0.5 : 1 }}
            aria-label="Notifications"
          >
            <NotificationsIcon sx={{ color: themestyle.colors.secondary }} />
          </IconButton>
          <Tooltip
            title={renderTooltipContent()}
            placement="bottom-end"
            arrow
            componentsProps={{
              tooltip: {
                sx: {
                  pointerEvents: "auto",
                  bgcolor: "transparent",
                  padding: 0,
                  margin: 0,
                },
              },
              arrow: {
                sx: {
                  color: themestyle.colors.white,
                },
              },
            }}
          >
            <IconButton
              color="inherit"
              aria-label={`User profile for ${displayName}`}
            >
              <Avatar sx={{ bgcolor: avatarColor, color: "#fff" }}>
                {initials}
              </Avatar>
            </IconButton>
          </Tooltip>
        </Box>
      </Toolbar>
    </AppBar>
  );
};

export default Header;