import { isNil, isNull } from 'lodash-es';
import Divider from '@material-hu/mui/Divider';
import Paper from '@material-hu/mui/Paper';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

import { type Nullable } from '../types';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { formatValue, getFavorabilityCountText } from '../utils';

import FavorabilityChart from './FavorabilityChart';
import FavorabilityIndexSkeleton from './FavorabilityIndexSkeleton';

type FavorabilityIndexProps = {
  metadata: Array<{ transKey: string; count?: number }>;
  score?: Nullable<number>;
  promoters?: Nullable<number>;
  neutrals?: Nullable<number>;
  detractors?: Nullable<number>;
  isLoading?: boolean;
  passedThreshold: boolean;
};

const FavorabilityIndex = ({
  score,
  promoters,
  neutrals,
  detractors,
  isLoading,
  metadata,
  passedThreshold,
}: FavorabilityIndexProps) => {
  const { t } = useLokaliseTranslation('people_experience');

  if (isLoading) {
    return <FavorabilityIndexSkeleton />;
  }

  return (
    <Paper
      component={Stack}
      sx={{
        alignItems: 'center',
        flexDirection: 'row',
        gap: 2,
        p: 2,
        borderRadius: 2,
      }}
      elevation={2}
    >
      <Stack>
        <Typography
          variant="h3"
          align="center"
        >
          {isNull(score) || score === undefined || !passedThreshold
            ? '--'
            : formatValue(score)}
        </Typography>
        <Typography
          variant="overline"
          sx={theme => ({ color: theme.palette.new.text.neutral.lighter })}
        >
          {t('SCORE')}
        </Typography>
      </Stack>
      <Divider
        orientation="vertical"
        flexItem
      />
      <Stack
        sx={{
          gap: 1,
          flex: '1 1 0',
          minWidth: 0,
          justifyContent: 'space-between',
        }}
      >
        <Typography
          variant="overline"
          sx={theme => ({ color: theme.palette.new.text.neutral.lighter })}
        >
          {t('GENERAL_ANSWERS')}
        </Typography>
        <FavorabilityChart
          positives={promoters ?? 0}
          neutrals={neutrals ?? 0}
          negatives={detractors ?? 0}
          variant="large"
        />
        <Typography
          variant="body2"
          sx={theme => ({ color: theme.palette.new.text.neutral.lighter })}
        >
          {metadata
            .map(item =>
              getFavorabilityCountText({
                t,
                translationKey: item.transKey,
                hasPassedThreshold: Boolean(
                  !isNil(item.count) && passedThreshold,
                ),
                count: item.count ?? 0,
              }),
            )
            .join(' | ')}
        </Typography>
      </Stack>
    </Paper>
  );
};

export default FavorabilityIndex;
