"use client";

import ConfigureWindow from "@/app/[language]/site/components/ConfigureWindow";
import SiteWindow from "@/app/[language]/site/components/SiteWindow";
import SiteYellsView from "@/app/[language]/site/components/SiteYellsView";
import wsAPI from "@/app/[language]/site/lib/wsAPI";
import Loading from "@/app/[language]/site/loading";

import { useSiteStore } from "@/state/Stores";
import { observer } from "mobx-react-lite";
import { useTranslations } from "next-intl";
import { useEffect, useMemo } from "react";
import Tab from "react-bootstrap/Tab";
import Tabs from "react-bootstrap/Tabs";
import { Item, Menu, useContextMenu } from "react-contexify";
import Swal from "sweetalert2";
import { useIsPath } from "taehui-lib/fe-utilities";

const EventPB = require("@/Event_pb");

export default observer(() => {
  const {
    targetSiteID,
    siteViews,
    siteAvatarID,
    getSiteView,
    isLoading,
    setTargetSiteID,
  } = useSiteStore();

  const t = useTranslations();

  const { show: viewSiteNameInput } = useContextMenu({
    id: "siteName",
  });

  const isPath = useIsPath();

  useEffect(() => {
    if (isPath("/site")) {
      getSiteView(targetSiteID)?.siteYellsViewMove();
    }
  }, [getSiteView, isPath, targetSiteID]);

  useEffect(() => {
    window.Notification?.requestPermission();
  }, []);

  const isSiteHand = useMemo(
    () => getSiteView(targetSiteID)?.siteHand === siteAvatarID,
    [getSiteView, siteAvatarID, targetSiteID],
  );

  if (isLoading) {
    return <Loading />;
  }

  return (
    <>
      <Tabs
        id="tabsView"
        activeKey={targetSiteID}
        onSelect={(eventKey) => {
          setTargetSiteID(eventKey ?? "");
        }}
        onContextMenu={(event) => {
          event.preventDefault();
          viewSiteNameInput({ event });
        }}
      >
        {siteViews.map((siteView) => (
          <Tab
            key={siteView.siteID}
            eventKey={siteView.siteID}
            title={
              siteView.isNew ? `💬 ${siteView.siteName}` : siteView.siteName
            }
          >
            <SiteYellsView siteView={siteView} />
          </Tab>
        ))}
      </Tabs>

      <Menu id="siteName">
        <Item
          disabled={!isSiteHand}
          onClick={async () => {
            const { isConfirmed, value } = await Swal.fire({
              title: t("setSiteNameText"),
              input: "text",
            });
            if (isConfirmed) {
              wsAPI.send({
                eventID: EventPB.Event.EventID.SET_SITE_NAME,
                text: JSON.stringify({
                  siteID: targetSiteID,
                  siteName: value,
                }),
              });
            }
          }}
        >
          {t("setSiteName")}
        </Item>
      </Menu>

      <ConfigureWindow />
      <SiteWindow />
    </>
  );
});
