import { CollaboratorProfile } from "models/talent/talent-profile-collaborator.model";
import { useMemo } from "react";
import {
  selectCollaborator,
  selectCollaboratorList,
  selectIsCollaborator,
  selectUserData,
} from "redux/User/selector";
import { ROLE, UserProfile } from "redux/User/types";
import { useTypedSelector } from "redux/rootReducer";
import {
  domainLink,
  profileAdminLink,
  profileLink,
} from "components/PreviewLayoutHeader/utils";

import {
  Avatar,
  AvatarSize,
  MenuItemGroupItem,
  MenuItemLink,
  MenuItemType,
  NavUser,
  useToast,
} from "@komi-app/creator-ui";

import {
  MdHelpOutline as HelpOutlineIcon,
  MdManageAccounts as ManageAccountsIcon,
  MdContentCopy as ContentCopyIcon,
  MdLogout as LogoutIcon,
  MdAddCircleOutline as AddCircleOutlineIcon,
  MdDashboardCustomize as DashboardCustomizeIcon,
} from "react-icons/md";
import { userHasRole } from "utils/user";

import config from "config";
import { getTrialDuration } from "utils/subscription";
import { DEFAULT_TRIAL_LENGTH_DAYS } from "constants/trial";
import { copyTextToClipboard } from "../utils/copyTextToClipboard";
import { FLAGS, useFeatureIsOn } from "@komi-app/flags-sdk";

export function fullname(user?: Record<string, any> | null) {
  return `${user?.firstName || ""} ${user?.lastName || ""}`.trim();
}

export function useNavUser(): NavUser | undefined {
  const collaborator = useTypedSelector(selectCollaborator);
  const user = useTypedSelector(selectUserData);
  const isCollaborator = useTypedSelector(selectIsCollaborator);
  const collaborationTalentProfiles = useTypedSelector(selectCollaboratorList);
  const isNavbarCopyUpdateEnabled = useFeatureIsOn(FLAGS.NAVBAR_COPY_UPDATE);
  const hideRequestProfile = useFeatureIsOn(
    FLAGS.FIX_SB_957_TALENT_REQUEST_POPUP
  );

  const isAdmin =
    userHasRole([user, collaborator], ROLE.Admin) ||
    userHasRole([user, collaborator], ROLE.Moderator) ||
    userHasRole([user, collaborator], ROLE.External);
  const isSelfSign = userHasRole([user, collaborator], ROLE.SelfSign);

  const trialDuration = getTrialDuration(DEFAULT_TRIAL_LENGTH_DAYS);

  const useEmailSignup = useFeatureIsOn(FLAGS.FEAT_SB_410_EMAIL_SIGNUP);
  const isNullNameFixEnabled = useFeatureIsOn(
    FLAGS.FIX_SB_666_DISPLAY_NULL_NAMES_CORRECTLY
  );
  const isNewHeaderOn = useFeatureIsOn(FLAGS.FEAT_SB_495_HEADER_ASPECT_RATIO);

  const { createToast } = useToast();

  const avatarSrc = useAvatarTransformedSrc();

  const logoutLink = useEmailSignup
    ? `${config.client.url}/signout`
    : `${config.client.url}?action=LOGOUT`;

  const UserInNav = useMemo(() => {
    let talentProfile: UserProfile | undefined;
    let connectedProfile: CollaboratorProfile[] | undefined;

    if (isCollaborator) {
      talentProfile = collaborator?.talentProfile;
      connectedProfile = collaborationTalentProfiles;
    }

    if (user) {
      talentProfile = user.talentProfile;
      connectedProfile = user.collaborationTalentProfiles;
    }

    // Since we're removing the request profile button for top talent
    // there won't be any items under the connected profiles header
    // this conditional hides the header if top talent has no connected profiles
    const shouldShowConnectedProfiles = hideRequestProfile
      ? isSelfSign || (connectedProfile && connectedProfile.length > 0)
      : true;

    let handle: string;

    if (isNullNameFixEnabled) {
      handle = fullname(user);
    } else {
      handle =
        `${user?.firstName} ${user?.lastName}`.trim() ||
        talentProfile?.user?.username ||
        (talentProfile as any)?.username;
    }

    const avatar =
      isNewHeaderOn && talentProfile?.avatar
        ? avatarSrc
        : talentProfile?.avatar;

    return {
      avatar,
      handle,
      email: user?.email,
      connected:
        connectedProfile && shouldShowConnectedProfiles
          ? [
              { name: "CONNECTED PROFILES", type: MenuItemType.LABEL },
              ...connectedProfile.map((item) => ({
                name: fullname(item?.talentProfile),
                icon: (
                  <Avatar
                    url={item?.talentProfile?.avatar as string}
                    username={item.talentProfile.user?.username}
                    size={AvatarSize.SM}
                  />
                ),
                type: MenuItemType.COMBO_LINK,
                url: profileAdminLink(item.talentProfile.user?.username),
                details: profileLink(item.talentProfile.user?.username, {
                  hideProtocol: true,
                }),
                native: true,
                action: {
                  type: MenuItemType.COMBO_ACTION,
                  icon: <ContentCopyIcon size={24} />,
                  onClick: () => {
                    copyTextToClipboard(
                      profileLink(item.talentProfile.user?.username)
                    );
                    createToast({
                      semantic: "success",
                      text: "The Komi link has been successfully copied to your clipboard. You can now paste it wherever you need.",
                      dismissible: true,
                      durationMs: 5000,
                    });
                  },
                },
              })),
            ]
          : [],
    };
  }, [user, collaborator, isNewHeaderOn, avatarSrc, hideRequestProfile]);

  const profiles: MenuItemGroupItem[] = UserInNav.handle // do not display if no current profile
    ? [
        {
          name: UserInNav.handle,
          details: UserInNav.email,
          icon: (
            <Avatar
              url={UserInNav.avatar as string}
              username={UserInNav.handle}
              size={AvatarSize.SM}
            />
          ),
          type: MenuItemType.PROFILE,
        },
      ]
    : [];

  profiles.push(...(UserInNav.connected as MenuItemLink[]));

  const controls: MenuItemGroupItem[] = useMemo(
    () =>
      isAdmin
        ? [
            {
              type: MenuItemType.LABEL,
              name: "Admin",
            },
            {
              type: MenuItemType.LINK,
              icon: <DashboardCustomizeIcon size={24} />,
              name: "Dashboard",
              url: config.admin.url,
              native: true,
            },
          ]
        : isSelfSign
          ? [
              {
                type: MenuItemType.LINK,
                icon: <AddCircleOutlineIcon size={24} />,
                name: "Create New Profile",
                details: `${trialDuration}-day trial available`,
                url: `${config.client.url}/create-profile`,
                native: true,
              },
            ]
          : hideRequestProfile
            ? []
            : [
                {
                  key: "request-profile",
                  type: MenuItemType.LINK,
                  icon: <AddCircleOutlineIcon size={24} />,
                  name: "Request Profile",
                },
              ],
    [user, collaborator, hideRequestProfile]
  );

  const settings: MenuItemGroupItem[] = [
    {
      name: "User",
      type: MenuItemType.LABEL,
    },
    {
      name: isNavbarCopyUpdateEnabled
        ? "Account Information"
        : "Account Settings",
      type: MenuItemType.LINK,
      icon: <ManageAccountsIcon size={24} />,
      url: `${domainLink()}/me`,
      native: true,
    },
    {
      name: "Help center",
      type: MenuItemType.LINK,
      icon: <HelpOutlineIcon size={24} />,
      url: "http://support.komi.io",
      external: true,
    },
    {
      name: "Logout",
      type: MenuItemType.LINK,
      icon: <LogoutIcon size={24} />,
      url: logoutLink,
      native: true,
    },
  ];

  // Support for account page as not linked to a profile
  const username = UserInNav.handle || fullname(user);

  if (user) {
    return {
      icon: (
        <Avatar
          url={UserInNav.avatar as string}
          username={username}
          size={AvatarSize.SM}
        />
      ),
      name: username,
      profiles,
      controls,
      settings,
    };
  }

  return undefined;
}

/**
 * Custom hook to get the avatar URL using ImageKit or Canvas.
 * This applies the transformations based on the query params.
 */
function useAvatarTransformedSrc() {
  const user = useTypedSelector(selectUserData);
  const collaborator = useTypedSelector(selectCollaborator);
  const isCollaborator = useTypedSelector(selectIsCollaborator);

  const talentProfile: UserProfile | undefined = isCollaborator
    ? collaborator?.talentProfile
    : user?.talentProfile;

  return talentProfile?.avatar;
}

export default useNavUser;
