import Timeline from "@mui/lab/Timeline";
import TimelineDot from "@mui/lab/TimelineDot";
import Typography from "@mui/material/Typography";
import CardHeader from "@mui/material/CardHeader";
import Card, { CardProps } from "@mui/material/Card";
import TimelineContent from "@mui/lab/TimelineContent";
import TimelineSeparator from "@mui/lab/TimelineSeparator";
import TimelineConnector from "@mui/lab/TimelineConnector";
import TimelineItem, { timelineItemClasses } from "@mui/lab/TimelineItem";

import { fDateTime } from "@/utils/format-time";

// ----------------------------------------------------------------------

type ItemProps = {
  id: string;
  title: string;
  time: Date;
  type: string;
  details?: string;
};

interface Props extends CardProps {
  title?: string;
  subheader?: string;
  list: ItemProps[];
}

export default function TaskHistory({
  title,
  subheader,
  list,
  ...other
}: Props) {
  return (
    <Card {...other}>
      <CardHeader title={title} subheader={subheader} />

      <Timeline
        sx={{
          m: 0,
          p: 3,
          [`& .${timelineItemClasses.root}:before`]: {
            flex: 0,
            padding: 0,
          },
        }}
      >
        {list.map((item, index) => (
          <OrderItem
            key={item.id}
            item={item}
            lastTimeline={index === list.length - 1}
          />
        ))}
      </Timeline>
    </Card>
  );
}

// ----------------------------------------------------------------------

type OrderItemProps = {
  item: ItemProps;
  lastTimeline: boolean;
};

function OrderItem({ item, lastTimeline }: OrderItemProps) {
  const { type, title, time, details } = item; // Ensure `details` is destructured
  return (
    <TimelineItem>
      <TimelineSeparator>
        <TimelineDot
          color={
            (type === "order1" && "primary") ||
            (type === "order2" && "success") ||
            (type === "order3" && "info") ||
            (type === "order4" && "warning") ||
            "error"
          }
        />
        {lastTimeline ? null : <TimelineConnector />}
      </TimelineSeparator>

      <TimelineContent>
        <Typography variant="subtitle2">{title}</Typography>
        <Typography variant="caption" sx={{ color: "text.disabled" }}>
          {fDateTime(time)}
        </Typography>
        {details && ( // Render details if available
          <Typography variant="body2" sx={{ mt: 1 }}>
            {details}
          </Typography>
        )}
      </TimelineContent>
    </TimelineItem>
  );
}
