import { Children, type ComponentType, type ReactNode } from 'react';

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

import HuAvatar from '@material-hu/components/design-system/Avatar';
import HuCardContainer from '@material-hu/components/design-system/CardContainer';
import HuTitle from '@material-hu/components/design-system/Title';

import useHuGoTheme from 'src/hooks/useHuGoTheme';
import { getFullName, getInitials } from 'src/utils/userUtils';

type ReviewHeaderCardUser = {
  firstName?: string | null;
  lastName?: string | null;
  fullName?: string | null;
  profilePicture?: string | null;
};

type ReviewHeaderCardProps = {
  user?: ReviewHeaderCardUser;
  subtitle?: string;
  rightSlot?: ReactNode;
  children?: ReactNode;
  footer?: ReviewHeaderCardFooter;
};

type ReviewHeaderCardFooterAction = {
  title: string;
  onClick: (...args: unknown[]) => void;
  variant?: string;
  endIcon?: ReactNode;
  disabled?: boolean;
  size?: string;
};

type ReviewHeaderCardFooter = {
  action1: ReviewHeaderCardFooterAction;
  text?: string;
};

const SafeHuCardContainer = HuCardContainer as unknown as ComponentType<{
  fullWidth?: boolean;
  padding?: 0 | 16 | 24;
  footer?: ReviewHeaderCardFooter;
  sx?: { boxSizing: string };
  children?: ReactNode;
}>;

const ReviewHeaderCard = ({
  user,
  subtitle,
  rightSlot,
  children,
  footer,
}: ReviewHeaderCardProps) => {
  const HuGoThemeProvider = useHuGoTheme();
  const userFullName = getFullName({
    firstName: user?.firstName ?? undefined,
    lastName: user?.lastName ?? undefined,
  });
  const hasFooterContent = Children.toArray(children).length > 0;

  return (
    <HuGoThemeProvider>
      <SafeHuCardContainer
        fullWidth
        padding={24}
        footer={footer}
        sx={{ boxSizing: 'border-box' }}
      >
        <Stack sx={{ gap: 2 }}>
          <Stack
            sx={{
              flexDirection: 'row',
              alignItems: 'center',
              justifyContent: 'space-between',
              flexWrap: 'wrap',
              gap: 2,
            }}
          >
            <Stack
              sx={{
                flexDirection: 'row',
                alignItems: 'center',
                gap: 2,
                minWidth: 0,
                flex: 1,
              }}
            >
              <HuAvatar
                size="large"
                src={user?.profilePicture ?? undefined}
                text={getInitials(userFullName)}
                alt=""
                sx={{ flexShrink: 0 }}
              />
              <HuTitle
                title={userFullName}
                description={subtitle}
                variant="L"
                sx={{ minWidth: 0 }}
              />
            </Stack>
            {rightSlot}
          </Stack>

          {hasFooterContent && <Stack sx={{ gap: 2 }}>{children}</Stack>}
        </Stack>
      </SafeHuCardContainer>
    </HuGoThemeProvider>
  );
};

export default ReviewHeaderCard;
