import { type ReactNode } from 'react';

import Stack from '@material-hu/mui/Stack';
import { type SxProps, type Theme } from '@material-hu/mui/styles';

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

export type RequestOfferActionItem = {
  label: string;
  onClick: () => void;
  variant: 'primary' | 'secondary';
  disabled?: boolean;
  fullWidth?: boolean;
  size?: 'large' | 'medium' | 'small';
  startIcon?: ReactNode;
  endIcon?: ReactNode;
  sx?: SxProps<Theme>;
};

export type RequestOfferActionsProps = {
  layout: 'column' | 'row';
  justifyContent?: 'flex-end' | 'flex-start' | 'space-between';
  gap?: number;
  actions: RequestOfferActionItem[];
  sx?: SxProps<Theme>;
};

function getRowLayoutButtonSx(
  isRow: boolean,
  actionCount: number,
): SxProps<Theme> | undefined {
  if (!isRow) {
    return undefined;
  }
  if (actionCount === 1) {
    return {
      width: { xs: '100%', sm: 'auto' },
      alignSelf: { xs: 'stretch', sm: 'auto' },
    };
  }
  if (actionCount === 2) {
    return {
      flex: { xs: '1 1 0', sm: '0 1 auto' },
      minWidth: { xs: 0 },
    };
  }
  return undefined;
}

export const RequestOfferActions = ({
  layout,
  justifyContent = 'flex-end',
  gap,
  actions,
  sx,
}: RequestOfferActionsProps) => {
  const resolvedGap = gap ?? (layout === 'column' ? 2.5 : 1.5);
  const actionCount = actions.length;
  const isRow = layout === 'row';

  return (
    <Stack
      sx={{
        width: '100%',
        flexDirection: layout === 'column' ? 'column' : 'row',
        alignItems:
          layout === 'row' ? { xs: 'stretch', sm: 'center' } : 'stretch',
        justifyContent: layout === 'row' ? justifyContent : undefined,
        flexWrap: layout === 'row' ? 'wrap' : undefined,
        gap: resolvedGap,
        ...sx,
      }}
    >
      {actions.map(action => {
        const rowMobileSx = getRowLayoutButtonSx(isRow, actionCount);
        const mergedSx: SxProps<Theme> | undefined =
          rowMobileSx && action.sx
            ? ([rowMobileSx, action.sx] as SxProps<Theme>)
            : (rowMobileSx ?? action.sx);

        return (
          <Button
            key={action.label}
            type="button"
            variant={action.variant}
            fullWidth={action.fullWidth ?? layout === 'column'}
            disabled={action.disabled}
            onClick={action.onClick}
            size={action.size ?? 'large'}
            startIcon={action.startIcon}
            endIcon={action.endIcon}
            sx={mergedSx}
          >
            {action.label}
          </Button>
        );
      })}
    </Stack>
  );
};
