import React, { useState } from "react";
import Box from "@mui/material/Box";
import Stepper from "@mui/material/Stepper";
import Step from "@mui/material/Step";
import StepLabel from "@mui/material/StepLabel";
import Typography from "@mui/material/Typography";
import Button from "@mui/material/Button";
import CircularProgress from "@mui/material/CircularProgress";
import { useGetAllWorkOrderHistoryQuery } from "../../../Api/attoDeskApi";

export default function HorizontalLinearStepper() {
  const {
    data: workOrderHistoryData,
    isLoading: workOrderHistoryIsLoading,
    isError: workOrderHistoryError,
  } = useGetAllWorkOrderHistoryQuery({ id: "15" });

  // State to manage which steps' details are expanded
  const [expandedSteps, setExpandedSteps] = useState<number[]>([]);

  // Memoized work order data for generating steps
  const timeLineSteps = React.useMemo(() => {
    if (
      workOrderHistoryData &&
      Array.isArray(workOrderHistoryData.data) &&
      workOrderHistoryData.data.length > 0
    ) {
      return workOrderHistoryData.data.map((order, index) => {
        const label =
          index === 0
            ? 'Work order created' // First step
            : order.isInvoice
            ? `Work order covered as invoice ${order.invoiceNo}`
            : 'Work order edited'; // Subsequent steps

        return {
          label: label,
          description: `
            Status: ${order.quoteWorkOrderStatus === 2 ? 'Completed' : 'Pending'}
            Subtotal: ${order.quoteWorkOrderSubTotal}
            Grand Total: ${order.quoteWorkOrderSaleGrandTotal}`,
        };
      });
    }
    return [];
  }, [workOrderHistoryData]);

  // Toggle the description visibility for each step
  const toggleStepDetails = (index: number) => {
    if (expandedSteps.includes(index)) {
      setExpandedSteps(expandedSteps.filter((stepIndex) => stepIndex !== index));
    } else {
      setExpandedSteps([...expandedSteps, index]);
    }
  };

  return (
    <Box sx={{ maxWidth: 600 }}>
      {workOrderHistoryIsLoading ? (
        <CircularProgress />
      ) : workOrderHistoryError ? (
        <Typography color="error">Error fetching work order history</Typography>
      ) : (
        <>
          <Stepper orientation="vertical" activeStep={timeLineSteps.length}>
            {timeLineSteps.map((step, index) => (
              <Step key={step.label} completed>
                <StepLabel>
                  <Box display="flex" justifyContent="space-between" alignItems="center">
                    {step.label}
                    <Button
                      variant="outlined"
                      size="small"
                      onClick={() => toggleStepDetails(index)}
                      sx={{ ml: 2 }}
                    >
                      {expandedSteps.includes(index) ? "Hide Details" : "Show Details"}
                    </Button>
                  </Box>
                </StepLabel>
                {/* Show description if the step is expanded */}
                {expandedSteps.includes(index) && (
                  <Box sx={{ ml: 4, mt: 1 }}>
                    <Typography>{step.description}</Typography>
                  </Box>
                )}
              </Step>
            ))}
            {/* Last step + 1 with loading spinner */}
            <Step>
              <StepLabel>
                <Typography>Converting Work Order to Invoice...</Typography>
              </StepLabel>
              <Box sx={{ display: "flex", justifyContent: "center", py: 2 }}>
                <CircularProgress />
              </Box>
            </Step>
          </Stepper>
        </>
      )}
    </Box>
  );
}
