import { Trans } from 'react-i18next';
import { useNavigate } from 'react-router-dom';

import { filter, isArray, map } from 'lodash-es';
import {
  IconBrandFacebook,
  IconBrandInstagram,
  IconBrandLinkedin,
  IconBrandWhatsapp,
  IconBrandX,
  type TablerIcon,
} from '@material-hu/icons/tabler';
import Stack from '@material-hu/mui/Stack';
import { useTheme } from '@material-hu/mui/styles';
import Typography from '@material-hu/mui/Typography';

import ProfileListFieldRow from '@material-hu/components/composed-components/profile/ProfileListFieldRow';
import ProfileListUsersRow from '@material-hu/components/composed-components/profile/ProfileListUsersRow';
import ProfileSingleFieldRow from '@material-hu/components/composed-components/profile/ProfileSingleFieldRow';
import Avatar from '@material-hu/components/design-system/Avatar';
import Button from '@material-hu/components/design-system/Buttons/Button';
import ListItem from '@material-hu/components/design-system/List/components/ListItem';

import { PROFILE_DATA_CONSTANTS } from 'src/constants/instance';
import { useRequiredAuth } from 'src/contexts/JWTContext';
import useFormatDate from 'src/hooks/useFormatDate';
import usePermissions from 'src/hooks/usePermissions';
import { type UserProfile } from 'src/types/user';
import { insertIf } from 'src/utils/arrays';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { UserPermissions } from 'src/utils/permissions';
import { getFullName, getInitials } from 'src/utils/userUtils';

import { profileRoutes } from '../routes';
import { useWhatsappLink } from '../utils';

const SocialMediaButton = ({
  url,
  Icon,
}: {
  url: string;
  Icon: TablerIcon;
}) => {
  return (
    <Button
      key={url}
      href={url}
      target="_blank"
      rel="noopener noreferrer"
      sx={{ minWidth: 0 }}
    >
      <Icon
        height={24}
        width={24}
      />
    </Button>
  );
};

const useSocialNetworks = (user: UserProfile) => {
  const {
    instance: { allowSocialNetworks },
  } = useRequiredAuth();
  const { t } = useLokaliseTranslation('users');
  const whatsappLink = useWhatsappLink(user);

  const linkedin =
    allowSocialNetworks.allowLinkedin && user.socialNetworks?.linkedIn;
  const instagram =
    allowSocialNetworks.allowInstagram && user.socialNetworks?.instagram;
  const x = allowSocialNetworks.allowTwitter && user.socialNetworks?.twitter;
  const facebook =
    allowSocialNetworks.allowFacebook && user.socialNetworks?.facebook;
  const whatsapp =
    allowSocialNetworks.allowWhatsApp &&
    user.socialNetworks?.allowWhatsApp &&
    user.phoneNumber;

  const socialNetworksButtons = [
    ...insertIf(
      !!linkedin,
      <SocialMediaButton
        key="linkedin"
        url={linkedin as string}
        Icon={IconBrandLinkedin}
      />,
    ),
    ...insertIf(
      !!instagram,
      <SocialMediaButton
        key="instagram"
        url={instagram as string}
        Icon={IconBrandInstagram}
      />,
    ),
    ...insertIf(
      !!x,
      <SocialMediaButton
        key="x"
        url={x as string}
        Icon={IconBrandX}
      />,
    ),
    ...insertIf(
      !!facebook,
      <SocialMediaButton
        key="facebook"
        url={facebook as string}
        Icon={IconBrandFacebook}
      />,
    ),
    ...insertIf(
      !!whatsapp,
      <SocialMediaButton
        key="whatsapp"
        url={whatsappLink}
        Icon={IconBrandWhatsapp}
      />,
    ),
  ];

  return (
    socialNetworksButtons.length > 0 && (
      <Stack>
        <Typography
          variant="globalXXS"
          sx={{
            color: ({ palette }) => palette.new.text.neutral.lighter,
          }}
        >
          {t('profile_categories.social')}
        </Typography>
        <Stack sx={{ flexDirection: 'row', gap: 0.5, alignItems: 'center' }}>
          {socialNetworksButtons}
        </Stack>
      </Stack>
    )
  );
};

const useGetCustomFieldContent = () => {
  const { formatDate } = useFormatDate();
  const { t } = useLokaliseTranslation('profile');
  const navigate = useNavigate();
  const theme = useTheme();

  const getContent = (field: { type: string; name: string; value: any }) => {
    const texts = {
      items_associated_to_field: t('items_associated_to_field', {
        field: field.name,
      }),
      no_items_found: t('no_items_found'),
      back: t('general:back'),
      items_total: (
        <Trans
          i18nKey="profile:items_total"
          values={{ count: field.value?.length ?? 0 }}
          components={{ b: <strong /> }}
        />
      ),
    };
    switch (field.type) {
      case PROFILE_DATA_CONSTANTS.STRING:
        return (
          <ProfileSingleFieldRow
            field={field}
            texts={texts}
          />
        );
      case PROFILE_DATA_CONSTANTS.NUMBER:
      case PROFILE_DATA_CONSTANTS.OPTION:
        return <ListItem text={{ title: field.value, copetin: field.name }} />;
      case PROFILE_DATA_CONSTANTS.DATE:
        return (
          <ListItem
            text={{ title: formatDate(field.value), copetin: field.name }}
          />
        );
      case PROFILE_DATA_CONSTANTS.NUMBER_LIST:
      case PROFILE_DATA_CONSTANTS.STRING_LIST:
      case PROFILE_DATA_CONSTANTS.MULTIPLE_OPTION:
        return (
          <ProfileListFieldRow
            field={field}
            texts={texts}
          />
        );
      case PROFILE_DATA_CONSTANTS.USER:
        return (
          <ListItem
            text={{
              title: getFullName(field.value),
              copetin: field.name,
              withEllipsis: true,
              overflow: 'tooltip',
            }}
            sideContent={
              <Avatar
                src={field.value.profilePicture}
                text={getInitials(getFullName(field.value))}
              />
            }
            slotProps={{
              container: {
                sx: {
                  width: 'fit-content',
                },
              },
              title: {
                slotProps: {
                  title: {
                    onClick: () =>
                      navigate(profileRoutes.profile(field.value.id)),
                    sx: {
                      '.MuiTypography-globalS': {
                        wordBreak: 'break-all',
                        cursor: 'pointer',
                        '&:hover': {
                          color: () =>
                            theme.palette.new.action.button.text.tertiary
                              .default as string,
                          textDecoration: 'underline',
                        },
                      },
                    },
                  },
                },
              },
            }}
          />
        );
      case PROFILE_DATA_CONSTANTS.USER_LIST: {
        const userTexts = {
          collaborator_count: t('general:collaborator_count', {
            count: field.value.length,
          }),
          back: t('general:back'),
          no_items_found: t('general:no_collaborators_found'),
          items_total: (
            <Trans
              i18nKey="profile:count_total_users"
              values={{ count: field.value.length }}
              components={{ b: <strong /> }}
            />
          ),
          drawer_title: t('users_associated_to_field', { field: field.name }),
        };
        return (
          <ProfileListUsersRow
            field={{
              ...field,
              value: field.value.map((user: UserProfile) => ({
                ...user,
                name: getFullName(user),
              })),
            }}
            texts={userTexts}
          />
        );
      }
      default:
        return field.type;
    }
  };
  return getContent;
};

export const useInfoData = (user: UserProfile) => {
  const { user: currentUser } = useRequiredAuth();
  const { t } = useLokaliseTranslation(['profile', 'users']);
  const socialNetworksContent = useSocialNetworks(user);
  const { hasAll: canViewTimeTracking } = usePermissions([
    UserPermissions.VIEW_TIME_TRACKING,
  ]);
  const showKioskPin = canViewTimeTracking && user.id === currentUser.id;

  const getCustomFieldContent = useGetCustomFieldContent();

  const bossData = user.bosses?.[0];

  const hiringDate =
    !!user.hiringDate &&
    getCustomFieldContent({
      type: PROFILE_DATA_CONSTANTS.DATE,
      name: t('fields.HIRING_DATE'),
      value: user.hiringDate,
    });

  const boss =
    !!bossData &&
    getCustomFieldContent({
      type: PROFILE_DATA_CONSTANTS.USER,
      name: t('general:boss'),
      value: bossData,
    });

  const approver =
    !!user.reviewer &&
    getCustomFieldContent({
      type: PROFILE_DATA_CONSTANTS.USER,
      name: t('users:reviewer'),
      value: user.reviewer,
    });

  const kioskPin = getCustomFieldContent({
    type: PROFILE_DATA_CONSTANTS.STRING,
    name: t('kiosk_pin'),
    value: user.timeTrackingUserSettings?.kioskPin || '-',
  });

  const profileDataWithoutEmptyArrays = filter(
    user.profileData,
    value => !isArray(value.value) || value.value.length > 0,
  );

  const infoData = [
    ...insertIf(!!hiringDate, hiringDate),
    ...insertIf(!!boss, boss),
    ...insertIf(!!approver, approver),
    ...insertIf(!!socialNetworksContent, socialNetworksContent),
    ...insertIf(showKioskPin, kioskPin),
    ...map(profileDataWithoutEmptyArrays, getCustomFieldContent),
  ];
  return infoData;
};

export const useSegmentationData = (user: UserProfile) => {
  const getCustomFieldContent = useGetCustomFieldContent();
  return user.segmentations.map(segmentation =>
    getCustomFieldContent({
      type: PROFILE_DATA_CONSTANTS.STRING_LIST,
      name: segmentation.name,
      value: segmentation.items?.map(item => item.name),
    }),
  );
};
