import moment, { Moment } from "moment-timezone";
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";
import { StepIcon } from "@/components/stepIcon";

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

    waiting?: boolean;
    declined?: boolean;
}

const now = moment();

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

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

    return <StepperStep { ...rest } completed={ completed }>
        <StepLabel error={ declined } StepIconComponent={ StepIcon } StepIconProps={{ ...props, waiting } as any}>
            { label }
            <Box>
                { state && <Typography variant="subtitle2" display="inline">{ state }</Typography> }
                { notBefore &&
                    <Typography variant="subtitle2" color="textSecondary" display="inline">
                        { t('not-before', { date: notBefore }) }
                    </Typography> }
                { until && <>
                    <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>
}
