import moment, { Moment } from "moment";
import { Box, Step as StepperStep, StepContent, StepLabel, StepProps as StepperStepProps, Typography } from "@material-ui/core";
import { useTranslation } from "react-i18next";
import React, { ReactChild, useMemo } from "react";

type StepProps = StepperStepProps & {
    until?: Moment;
    completedOn?: Moment;
    label: string;
    state?: ReactChild | null;

    /** this roughly translates into completed */
    accepted?: boolean;

    /** this roughly translates into error */
    declined?: boolean;
    sent?: boolean;
}

const now = moment();

export const Step = ({ until, label, completedOn, children, accepted = false, declined = false, completed = false, state = null, ...props }: StepProps) => {
    const { t } = useTranslation();

    const isLate = useMemo(() => until?.isBefore(completedOn || now), [completedOn, until]);
    const left = useMemo(() => moment.duration(now.diff(until)), [until]);

    return <StepperStep { ...props } completed={ completed }>
        <StepLabel error={ declined }>
            { label }
            { until && <Box>
                { state && <>
                    <Typography variant="subtitle2" display="inline">{ state }</Typography>
                    <Typography variant="subtitle2" display="inline" color="textSecondary"> • </Typography>
                </> }
                <Typography variant="subtitle2" color="textSecondary" display="inline">
                    { t('until', { date: until }) }
                    { isLate && <Typography color="error" display="inline"
                                            variant="body2"> - { t('late', { by: moment.duration(now.diff(until)) }) }</Typography> }
                    { !isLate && !completed && <Typography display="inline" variant="body2"> - { t('left', { left: left }) }</Typography> }
                </Typography>
            </Box> }
        </StepLabel>
        { children && <StepContent>{ children }</StepContent> }
    </StepperStep>
}
