import { type FC, type ReactNode, Suspense, useMemo } from 'react';

import CardHeader from '@material-hu/mui/CardHeader';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

import HuSkeleton from '@material-hu/components/design-system/Skeleton';
import HuTooltip from '@material-hu/components/design-system/Tooltip';

import { MAX_NAME_LENGTH } from 'src/constants/posts';
import { ApprovalStatus } from 'src/types/groups';
import { StreamStatus } from 'src/types/stream';
import { type User } from 'src/types/user';
import { getCorrectLiveDescription } from 'src/utils/feed';
import { useLokaliseTranslation as useTranslation } from 'src/utils/i18n';
import { lazyRetry } from 'src/utils/lazyRetry';
import { truncateText } from 'src/utils/text';
import { getFullName } from 'src/utils/userUtils';

import TimeDistance from 'src/components/time/TimeDistance';
import { UserNameLink } from 'src/components/UserNameLink';
import ProfilePicture, {
  type ProfilePictureProps,
} from 'src/components/user/ProfilePicture';

import { PostBreadcrumb } from './PostBreadcrumb';

const KeyUpdateSubheader = lazyRetry(
  () => import('src/pages/dashboard/feed/components/KeyUpdateSubheader'),
);

/** Minimal user type required for PostCardHeader */
export type PostCardHeaderUser = Pick<
  User,
  'id' | 'firstName' | 'lastName' | 'profilePicture'
>;

export type PostCardHeaderProps = {
  user: PostCardHeaderUser;
  publicationDatetime: string;
  updatedAt?: string;
  createdAt: string;
  approvalStatus?: ApprovalStatus;
  isKeyUpdate?: boolean;
  isExternal?: boolean;
  openProfileInNewTab?: boolean;
  hideKeyUpdateHeader?: boolean;
  abbreviateDate?: boolean;

  // Stream info
  stream?: {
    status: StreamStatus;
  };
  isGroupPost?: boolean;

  // Breadcrumb (for groups context)
  breadcrumb?: {
    title: string;
    link: string;
    showMultiCompanyIcon?: boolean;
  };

  // Action slot (PostAction component)
  action?: ReactNode;

  /** Disable profile link (e.g., for deleted users) */
  disableProfileLink?: boolean;
};

export const PostCardHeader: FC<PostCardHeaderProps> = ({
  user,
  publicationDatetime,
  updatedAt,
  createdAt,
  approvalStatus,
  isKeyUpdate = false,
  isExternal = false,
  openProfileInNewTab = false,
  stream,
  isGroupPost = false,
  breadcrumb,
  action,
  disableProfileLink = false,
  hideKeyUpdateHeader = false,
  abbreviateDate,
}) => {
  const { t } = useTranslation(['web_only']);

  // Memoize the time distance date
  const timeDistanceDate = useMemo(
    () =>
      approvalStatus === ApprovalStatus.PENDING
        ? new Date(updatedAt || createdAt)
        : new Date(publicationDatetime),
    [approvalStatus, publicationDatetime, updatedAt, createdAt],
  );

  const userMemo = useMemo(
    () => ({ user, sx: { width: '40px', height: '40px' } }),
    [user],
  );

  const fullName = getFullName(user);
  const showTooltip = fullName.length >= MAX_NAME_LENGTH;

  const profilePictureProps = useMemo<ProfilePictureProps>(() => {
    const props = {
      id: user.id,
      user: userMemo.user,
      sx: userMemo.sx,
    };
    if (disableProfileLink || isExternal) {
      return {
        ...props,
        withLink: false,
      };
    }
    return {
      ...props,
      withLink: true,
      openInNewTab: openProfileInNewTab,
    };
  }, [user, userMemo, isExternal]);

  return (
    <CardHeader
      sx={{
        '& .MuiCardHeader-avatar': {
          mr: 1,
        },
      }}
      avatar={<ProfilePicture {...profilePictureProps} />}
      disableTypography
      title={
        <Stack
          sx={{
            flexDirection: 'row',
            alignItems: 'center',
            overflow: 'hidden',
            flexWrap: 'wrap',
          }}
        >
          <HuTooltip
            title={fullName}
            disableTooltip={!showTooltip}
          >
            <UserNameLink
              user={{ ...user, isExternal }}
              openInNewTab={openProfileInNewTab}
              displayName={truncateText(fullName, MAX_NAME_LENGTH)}
              disableLink={disableProfileLink}
            />
          </HuTooltip>
          {stream && (
            <Typography
              variant="globalS"
              color={theme => theme.palette.new.text.neutral.lighter}
              sx={{ mx: 0.5, display: 'inline', verticalAlign: 'middle' }}
            >
              {getCorrectLiveDescription(
                t,
                !isGroupPost,
                stream.status === StreamStatus.LIVE,
              )}
            </Typography>
          )}
          {breadcrumb && (
            <PostBreadcrumb
              showChevron={!stream}
              title={breadcrumb.title}
              link={breadcrumb.link}
              showMultiCompanyIcon={breadcrumb.showMultiCompanyIcon}
            />
          )}
        </Stack>
      }
      subheader={
        <Stack
          sx={{
            flexDirection: 'row',
            alignItems: 'center',
            gap: 1,
            overflow: 'hidden',
          }}
        >
          <TimeDistance
            date={timeDistanceDate}
            showIcon={false}
            typographySx={{
              fontSize: '14px',
              fontWeight: '400',
              whiteSpace: 'nowrap',
              textOverflow: 'ellipsis',
              overflow: 'hidden',
            }}
            showFullDate={!abbreviateDate ? undefined : false}
          />
          {isKeyUpdate && !hideKeyUpdateHeader && (
            <Suspense
              fallback={
                <HuSkeleton
                  variant="text"
                  width={80}
                  height={20}
                />
              }
            >
              <KeyUpdateSubheader />
            </Suspense>
          )}
        </Stack>
      }
      action={action}
    />
  );
};

export default PostCardHeader;
