import { cn } from "@/utils/class-merge";
import { CalendarDaysIcon, ListBulletIcon, UserIcon } from "@heroicons/react/24/solid";
import { FunctionComponent, h } from "preact";
import { useLocation } from "preact-iso";
import { tv } from "tailwind-variants";
import classes from "./menu.module.scss";
import { useEffect, useState } from "preact/hooks";
import apiClient from "@/services/api";
import { useAppContext } from "@/providers/AuthProvider";

interface UserProfile {
  username: string;
  email: string;
  status: string;
  avatar_url: string | null;
  telegram_notifications: boolean;
  telegram_chat_id: string;
}

interface UserSettings {
  profile: UserProfile;
}

interface MenuItemProps {
  title: string;
  link: string;
  icon: h.JSX.Element;
}

const MenuItem: FunctionComponent<MenuItemProps> = ({ title, link, icon }: MenuItemProps) => {
  const { route, path } = useLocation();
  const active = path === link;
  const menuItemClasses = tv({
    base: classes.menu_item,
    variants: {
      activity: {
        active: "bg-gray-200",
        inactive: "bg-white",
      },
    },
    defaultVariants: {
      activity: "inactive",
    },
  });
  return (
    <div class={menuItemClasses({ activity: active ? "active" : "inactive" })} onClick={() => route(link, true)}>
      {icon}
      <div class="hidden md:block">{title}</div>
    </div>
  );
};

const Avatar: FunctionComponent = () => {
  const [status, setStatus] = useState("");
  const [username, setUsername] = useState("");
  const { route, path } = useLocation();
  const { isLoggedIn } = useAppContext();

  useEffect(() => {
    const fetchUserData = async () => {
      try {
        const response = await apiClient<UserSettings>("/api/settings/view_settings/", { method: "GET" }, isLoggedIn);
        setUsername(response.profile.username);
        setStatus(response.profile.status);
      } catch (error) {
        console.error("Failed to fetch user data:", error);
      }
    };

    if (isLoggedIn.value) {
      fetchUserData();
    }
  }, [isLoggedIn.value]);

  return (
    <button
      onClick={() => route("/profile/settings")}
      class={cn("hidden h-32 w-full cursor-pointer overflow-hidden opacity-100 transition-[height,opacity] md:block", {
        "h-0 opacity-0": path === "/profile/settings",
      })}
    >
      <div
        class={cn(
          "h-full flex-row items-center justify-around rounded-[3rem] bg-[linear-gradient(180.00deg,rgba(249,134,143,0.5)_3.053%,rgb(228,242,252)_96.183%)] px-5 py-5 md:flex"
        )}
      >
        <div class="my-5 aspect-square h-full rounded-full bg-white"></div>
        <div class="flex flex-col items-center justify-center">
          <p class="text-3xl font-semibold">{username}</p>
          <div class="rounded-[1rem] bg-white px-5 leading-5 font-light italic">{status}</div>
        </div>
      </div>
    </button>
  );
};

interface MenuItems {
  title: string;
  link: string;
  icon: h.JSX.Element;
}

const Menu: FunctionComponent = () => {
  //TODO: Move links to enum
  const menu_items: MenuItems[] = [
    {
      title: "Задачи",
      link: "/profile/tasks",
      icon: <ListBulletIcon class="size-10" />,
    },
    {
      title: "Календарь",
      link: "/profile/calendar",
      icon: <CalendarDaysIcon class="size-10" />,
    },
    {
      title: "Профиль",
      link: "/profile/settings",
      icon: <UserIcon class="size-10" />,
    },
  ];
  return (
    <div id={classes.container}>
      <Avatar />
      <div class={classes.menu_container}>
        {menu_items.map(({ title, link, icon }) => (
          <MenuItem title={title} link={link} icon={icon} />
        ))}
      </div>
    </div>
  );
};

export default Menu;
