import { forwardRef } from 'react';
import { useTranslation } from 'react-i18next';
import { Link as RouterLink } from 'react-router-dom';

import { type SxProps } from '@material-hu/mui';
import Link from '@material-hu/mui/Link';
import Stack from '@material-hu/mui/Stack';
import { useTheme } from '@material-hu/mui/styles';
import Typography from '@material-hu/mui/Typography';

import Pills from '@material-hu/components/design-system/Pills';

import { profileRoutes } from 'src/pages/dashboard/profile/routes';
import { type User } from 'src/types/user';
import { getFullName } from 'src/utils/userUtils';

import ProfilePicture from './user/ProfilePicture';

type UserNameLinkProps = {
  user: Pick<User, 'id' | 'firstName' | 'lastName' | 'profilePicture'> & {
    isExternal?: boolean;
  };
  openInNewTab?: boolean;
  displayName?: string;
  showProfilePicture?: boolean;
  /** Disable the profile link (renders as plain text) */
  disableLink?: boolean;
  /** Truncate long names with ellipsis (use in constrained layouts, e.g. tables) */
  truncate?: boolean;
  sx?: SxProps;
};
export const UserNameLink = forwardRef<HTMLDivElement, UserNameLinkProps>(
  (
    {
      user,
      showProfilePicture = false,
      openInNewTab = false,
      displayName = getFullName(user),
      disableLink = false,
      sx = {},
      truncate = false,
      ...other
    },
    ref,
  ) => {
    const { t } = useTranslation('group');
    const theme = useTheme();
    const openInNewTabProps = openInNewTab
      ? {
          target: '_blank' as const,
          rel: 'noopener noreferrer' as const,
        }
      : ({} as const);

    const truncateSx = truncate
      ? {
          overflow: 'hidden',
          textOverflow: 'ellipsis',
          whiteSpace: 'nowrap' as const,
        }
      : {};

    const Container = ({ children }: { children: React.ReactNode }) =>
      user.isExternal || disableLink ? (
        <Typography
          variant="globalS"
          sx={{ fontWeight: 'semiBold', ...truncateSx, ...sx }}
        >
          {children}
        </Typography>
      ) : (
        <Link
          color="textPrimary"
          component={RouterLink}
          to={profileRoutes.profile(user.id)}
          variant="globalS"
          sx={{
            color: theme.palette.new.text.neutral.default,
            textDecoration: 'none',
            fontWeight: 'semiBold',
            transition: 'color 0.2s',
            '&:hover': {
              color: theme.palette.new.text.neutral.brand,
              textDecoration: 'underline',
            },
            ...truncateSx,
            ...sx,
          }}
          {...openInNewTabProps}
        >
          {children}
        </Link>
      );

    return (
      <Stack
        ref={ref}
        direction="row"
        alignItems="center"
        gap={1}
        sx={truncate ? { minWidth: 0, overflow: 'hidden' } : undefined}
        {...other}
      >
        {showProfilePicture && (
          <ProfilePicture
            id={user.id}
            user={user}
            {...(user.isExternal
              ? { withLink: false }
              : { withLink: true, openInNewTab: openInNewTab })}
            sx={{ mr: 1 }}
          />
        )}
        <Container>{displayName}</Container>
        {user.isExternal && (
          <Pills
            label={t('group:external')}
            type="neutral"
            size="small"
            hasIcon={false}
          />
        )}
      </Stack>
    );
  },
);

UserNameLink.displayName = 'UserNameLink';
