import React from 'react';

import { Typography } from '@mui/material';
import {
  Timeline,
  TimelineItem,
  TimelineSeparator,
  TimelineConnector,
  TimelineContent,
  TimelineDot,
  timelineItemClasses,
} from '@mui/lab';

import { palette } from '../../helpers';
import { ColorVariant } from '@/types';
import styled from 'styled-components';

export interface TimeLineData {
  date: string;
  description?: string;
  children?: React.ReactNode;
}

interface TimeLineProps {
  data: TimeLineData[];
  theme?: ColorVariant;
  color?: string;
}

const colorMap: Record<ColorVariant, string> = {
  inherit: palette.inherit,
  primary: '#DB6619',
  secondary: palette.secondary,
  error: palette.error,
  warning: palette.warning,
  info: palette.info,
  success: palette.success,
};

export const TimeLine: React.FC<TimeLineProps> = ({ data, theme = 'primary', color }) => {
  const _mainColor = color || colorMap[theme];

  const NormaTimeLine = styled(Timeline)`
    .${timelineItemClasses.root} {
      padding: 0;
      &:before {
        flex: 0;
        padding: 0;
      }
    }

    .MuiTimelineDot-root {
      &:last-child {
        &:before {
          content: '';
          width: 70%;
          height: 70%;
          background: ${_mainColor};
          position: absolute;
          border-radius: 50%;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%);
        }
      }
    }
  `;

  const _getDotStyle = (last: boolean) => {
    const style = {
      background: 'none',
      boxShadow: 'none',
      padding: '6px',
      margin: '0',
      border: `3px solid ${_mainColor}`,
    };

    const lastStyle = {
      padding: '8px',
      position: 'relative',
      left: '-2px',
    };

    return last ? { ...style, ...lastStyle } : style;
  };

  return (
    <NormaTimeLine sx={{ padding: '0' }}>
      {data.map((item, key) => {
        const last = key !== data.length - 1;
        return (
          <TimelineItem key={key} sx={{ minHeight: 'auto' }}>
            <TimelineSeparator>
              <TimelineDot sx={_getDotStyle(!last)} />
              {last && <TimelineConnector sx={{ bgcolor: _mainColor, width: '5px' }} />}
            </TimelineSeparator>
            <TimelineContent sx={{ py: 0, pl: 2, pb: '35px' }}>
              <Typography sx={{ m: 'auto 0' }} className="TimelineContent__Date" variant="body1">
                {item.date}
              </Typography>
              {item.description && (
                <Typography sx={{ m: 'auto 0' }} className="TimelineContent__Description" variant="body2">
                  {item.description}
                </Typography>
              )}
              {item.children}
            </TimelineContent>
          </TimelineItem>
        );
      })}
    </NormaTimeLine>
  );
};
