import * as React from "react";
import Box, { BoxProps } from "@mui/material/Box";
import ReactEcharts from "echarts-for-react";
import Switch from "@mui/material/Switch";
import Grid from "@mui/material/Unstable_Grid2"; // Grid version 2
import Card, { CardProps } from "@mui/material/Card";
import CardContent from "@mui/material/CardContent";
import Typography from "@mui/material/Typography";
import { styled } from "@mui/material/styles";
import CircularProgress, {
  circularProgressClasses,
  CircularProgressProps,
} from "@mui/material/CircularProgress";
import LinearProgress, {
  linearProgressClasses,
} from "@mui/material/LinearProgress";
import IconButton from "@mui/material/IconButton";
import PlayCircleIcon from "@mui/icons-material/PlayCircle";
import StopCircleIcon from "@mui/icons-material/StopCircle";
import PauseCircleIcon from "@mui/icons-material/PauseCircle";
import ReplayCircleFilledIcon from "@mui/icons-material/ReplayCircleFilled";
import WarningIcon from "@mui/icons-material/Warning";
import Button, { ButtonProps } from "@mui/material/Button";
import Collapse from "@mui/material/Collapse";
import Grow from "@mui/material/Grow";
import Stack from "@mui/material/Stack";
import CheckIcon from "@mui/icons-material/Check";
import type { SvgIconProps } from "@mui/material/SvgIcon";

import { cards as cardsCfg } from "@/components/Sections/Scalable/_config";
import { config as navCfg } from "@/components/Layout2/_config";
import SQL from "@/components/Sections/RealTimeAnalytics/SQL";
import ContentTemplate from "@/components/Sections/Common/ContentTemplate";
import ARTComparisonChart from "@/components/Sections/Scalable/ARTComparisonChart";
import ARTSwitchCard from "@/components/Sections/Scalable/ARTSwitchCard";
import {
  SteadilyGrowingIcon,
  SpikyWorkloadIcon,
  AnalyticalWorkloadIcon,
  SpikyWorkloadLine,
  NoCfgChangesRequiredIcon,
  SteadilyWorkloadLine,
  AnalyticalWorkloadLine,
  ClearIcon,
  APBucket,
} from "@/components/Sections/Scalable/Icons";
import { UnifiedCodeDiffHighlight } from "@/components/CodeBlock";
import {
  animationKeyframesProps,
  DefaultBucketAnimation,
  DangerBucketAnimation,
  ResourcePoolExtensionAnimation,
  ClickArrowAnimation,
} from "@/components/Sections/Scalable/Animation";
import CustomCollapse from "@/components/Transform/Collapse";
import YoutubePlayer from "@/components/Sections/Scalable/Player";

export default function EasyScaleContent() {
  const [selectedItemId, setSelectedItemId] =
    React.useState("steadily-growing");

  const handleChangeItem = (target: string) => () => {
    setSelectedItemId(target);
  };

  return (
    <Grid
      container
      spacing={2}
      xs={12}
      sx={{
        overflowX: "auto",
      }}
    >
      <Grid container xs={12} spacing={2} minWidth="800px">
        <Player
          key={selectedItemId}
          selected={selectedItemId}
          onChange={handleChangeItem}
        />
      </Grid>
    </Grid>
  );
}

const easyScaleItems: easyScaleItemType[] = [
  {
    id: "steadily-growing",
    title: "Steadily growing",
    Icon: SteadilyGrowingIcon,
    Chart: SteadilyWorkloadLine,
    mysql: {
      cfg: `spring: 
    datasource: 
      url: jdbc:mysql://localhost:4000/sharding_plan?username=root 
      driver-class-name: com.mysql.cj.jdbc.Driver`,
      modifiedCfg: `spring: 
    datasource: 
      url: jdbc:shardingsphere:classpath:shardingsphere-config.yml 
      driver-class-name: org.apache.shardingsphere.driver.ShardingSphereDriver
    
      mode: 
        type: Cluster 
        repository: 
          type: ZooKeeper
          props: 
            namespace: governance 
            server-lists: localhost:2181`,
      added: [3, 5, 6, 7, 8, 9, 10, 11, 12],
      conclusion: [
        "Manual data relocation",
        "Complex code & arch",
        "Higher cost(hardware & human resource)",
      ],
    },
    tidb: {
      cfg: `spring: 
    datasource: 
      url: jdbc:mysql://localhost:4000/tidb_plan 
      username: root 
      driver-class-name: com.mysql.cj.jdbc.Driver`,
      conclusion: [
        "A few clicks to scaling and zero down time",
        "Simple code & arch",
        "Lower maintenance cost",
      ],
    },
    frames: [
      {
        id: "load-threshold",
        steps: 80,
        disabled: true,
        alert: {
          title: "load threshold",
          status: "warning",
        },
        actions: ["mysql-add-node", "mysql-check-cfg"],
      },
    ],
  },
  {
    id: "spiky-workload",
    title: "Spiky workload",
    Icon: SpikyWorkloadIcon,
    Chart: SpikyWorkloadLine,
    mysql: {
      cfg: `spring: 
    datasource: 
      url: jdbc:mysql://localhost:4000/sharding_plan?username=root 
      driver-class-name: com.mysql.cj.jdbc.Driver`,
      modifiedCfg: `spring: 
    datasource: 
      url: jdbc:shardingsphere:classpath:shardingsphere-config.yml 
      driver-class-name: org.apache.shardingsphere.driver.ShardingSphereDriver
  
    mode: 
      type: Cluster 
      repository: 
        type: ZooKeeper
        props: 
          namespace: governance 
          server-lists: localhost:2181`,
      added: [3, 5, 6, 7, 8, 9, 10, 11, 12],
      conclusion: [
        "Manual data relocation",
        "Complex code & arch",
        "Higher cost(hardware & human resource)",
      ],
    },
    tidb: {
      cfg: `spring: 
    datasource: 
      url: jdbc:mysql://localhost:4000/tidb_plan 
      username: root 
      driver-class-name: com.mysql.cj.jdbc.Driver`,
      conclusion: [
        "Automatic data relocation and zero down time",
        "Simple code & arch",
        "Lower cost(pay as you go)",
      ],
    },
    frames: [
      {
        id: "approaching-peak-load",
        steps: 50,
        disabled: true,
        alert: {
          title: "Approaching peak load",
          status: "warning",
        },
        actions: ["mysql-add-node", "mysql-check-cfg"],
      },
      {
        id: "load-reduction",
        steps: 57,
        alert: {
          title: "Load reduction",
          status: "info",
        },
      },
    ],
  },
  {
    id: "analytical-workload",
    title: "Analytical workload",
    Icon: AnalyticalWorkloadIcon,
    Chart: AnalyticalWorkloadLine,
    mysql: {
      cfg: `spring: 
    datasource: 
      url: jdbc:mysql://localhost:4000/sharding_plan?username=root 
      driver-class-name: com.mysql.cj.jdbc.Driver`,
      conclusion: ["Unavailable service"],
    },
    tidb: {
      cfg: `spring: 
    datasource: 
      url: jdbc:mysql://localhost:4000/tidb_plan 
      username: root 
      driver-class-name: com.mysql.cj.jdbc.Driver`,
      conclusion: ["Analytic nodes auto scaling", "Zero down time"],
    },
    frames: [
      {
        id: "sudden-peak-load",
        steps: 30,
        disabled: true,
        alert: {
          title: "Sudden peak load",
          status: "warning",
        },
        actions: ["mysql-check-node-overload"],
      },
      {
        id: "load-reduction",
        steps: 40,
        alert: {
          title: "Load reduction",
          status: "info",
        },
      },
    ],
  },
];

export type easyScaleItemType = {
  id: string;
  title: string;
  Icon: (props: SvgIconProps) => JSX.Element;
  Chart: (props: SvgIconProps) => JSX.Element;
  mysql: {
    cfg: string;
    modifiedCfg?: string;
    added?: number[];
    conclusion: string[];
  };
  tidb: {
    cfg: string;
    conclusion: string[];
  };
  frames: {
    id: string;
    steps: number;
    disabled?: boolean;
    alert?: {
      title: string;
      status: "info" | "warning";
    };
    actions?: string[];
  }[];
};

const Player = (props: {
  selected: string;
  onChange: (id: string) => () => void;
}) => {
  const { selected, onChange } = props;

  const [isPlaying, setIsPlaying] = React.useState(false);
  const [progress, setProgress] = React.useState(0);
  const [frameCount, setFrameCount] = React.useState(0);
  const [completedActions, setCompletedActions] = React.useState<string[]>([]);
  const [playTimes, setPlayTimes] = React.useState(0);

  const selectedItemMemo = React.useMemo(() => {
    return easyScaleItems.find(
      (i) => i.id === selected
    ) as (typeof easyScaleItems)[1];
  }, [selected]);
  const currentFrameMemo = React.useMemo(() => {
    if (frameCount + 1 > selectedItemMemo.frames.length) return;
    const currentFrame = selectedItemMemo.frames
      .slice(0, frameCount + 1)
      ?.pop();
    process.env.NODE_ENV === "development" &&
      console.log("currentFrameMemo", currentFrame);
    return currentFrame;
  }, [frameCount, selectedItemMemo.frames]);
  const isActionsCompleted = React.useMemo(() => {
    if (!currentFrameMemo?.actions || currentFrameMemo.actions.length === 0)
      return true;
    return (
      currentFrameMemo?.actions?.every((a) => completedActions.includes(a)) ??
      false
    );
  }, [completedActions, currentFrameMemo?.actions]);
  const isReachedCurrentFrame = React.useMemo(() => {
    if (!currentFrameMemo?.steps) return false;
    return currentFrameMemo?.steps <= progress;
  }, [currentFrameMemo?.steps, progress]);

  const handlePlay = () => {
    if (isReachedCurrentFrame) {
      setFrameCount((prev) => prev + 1);
    }
    setIsPlaying(true);

    if (selectedItemMemo.id === "spiky-workload") {
      if (progress === selectedItemMemo.frames[0].steps) {
        process.env.NODE_ENV === "development" &&
          console.log("CustomCollapseOpen");
        typeof window !== "undefined" &&
          window.dispatchEvent(new Event("CustomCollapseClose"));
      }
    }
    if (selectedItemMemo.id === "steadily-growing") {
      if (progress === selectedItemMemo.frames[0].steps) {
        process.env.NODE_ENV === "development" &&
          console.log("CustomCollapseClose");
        typeof window !== "undefined" &&
          window.dispatchEvent(new Event("CustomCollapseOpen"));
      }
    }
  };

  const handlePause = () => {
    setIsPlaying(false);
  };

  const handleReplay = () => {
    setProgress(0);
    setFrameCount(0);
    setCompletedActions([]);
    setPlayTimes((prev) => prev + 1);
    setIsPlaying(true);
  };

  React.useEffect(() => {
    if (isPlaying) {
      const timer = setInterval(() => {
        setProgress((prev) => {
          if (prev === 100) {
            setIsPlaying(false);
            return 100;
          }
          return prev + 1;
        });
      }, 100);

      return () => clearInterval(timer);
    }
  }, [isPlaying]);

  React.useEffect(() => {
    process.env.NODE_ENV === "development" && console.log("progress", progress);
    // console.log("frameCount", frameCount);

    if (frameCount + 1 > selectedItemMemo.frames.length) return;

    const currentFrame = selectedItemMemo.frames
      .slice(0, frameCount + 1)
      ?.pop();

    if (!currentFrame) return;

    if (currentFrame.steps <= progress) {
      handlePause();
    }
  }, [progress, selectedItemMemo.frames, frameCount]);

  return (
    <>
      <Grid
        container
        spacing={2}
        xs={12}
        position="relative"
        sx={{
          "@keyframes button-blink": {
            "0%": {
              opacity: 1,
            },
            "50%": {
              opacity: 0.5,
            },
            "100%": {
              opacity: 1,
            },
          },
        }}
      >
        {easyScaleItems.map((item) => {
          const isSelected = selected === item.id;
          return (
            <Grid key={item.id} xs={isSelected ? 6 : 3}>
              <Card
                variant="outlined"
                onClick={isSelected ? undefined : onChange(item.id)}
                sx={{
                  cursor: isSelected ? "default" : "pointer",
                  position: "relative",
                  padding: "10px",
                  height: "100%",
                  display: "flex",
                  "&:hover": {
                    boxShadow: (theme) =>
                      isSelected
                        ? undefined
                        : `0 0 0 1px ${theme.palette.primary.main}`,
                  },
                  ...(isSelected && {
                    boxShadow: (theme) => `0 0 0 1px rgba(38, 38, 63, 0.5)`,
                    overflow: "visible",
                  }),
                }}
              >
                {!isSelected && (
                  <Box
                    width="100%"
                    display="flex"
                    alignItems="center"
                    justifyContent="space-around"
                    minHeight={32}
                  >
                    <Typography
                      component="div"
                      fontSize={12}
                      fontWeight={600}
                      color="text.light"
                    >
                      {item.title}
                    </Typography>
                    <item.Icon
                      sx={{
                        width: "120px",
                        height: "auto",
                        color: (theme) => theme.palette.background.paper,
                      }}
                    />
                  </Box>
                )}
                {isSelected && (
                  <>
                    <Box
                      component="div"
                      height="2px"
                      width="fit-content"
                      overflow="hidden"
                      fontSize={12}
                      fontWeight={600}
                      display="block"
                      position="absolute"
                      top="-2px"
                      left="10px"
                      px="6px"
                      sx={{
                        background: (theme) => theme.palette.background.paper,
                        userSelect: "none",
                      }}
                    >
                      {item.title}
                    </Box>
                    <Typography
                      component="label"
                      fontSize={12}
                      fontWeight={600}
                      position="absolute"
                      top="-10px"
                      left="16px"
                    >
                      {item.title}
                    </Typography>
                    <Box
                      width="100%"
                      display="flex"
                      alignItems="center"
                      justifyContent="space-between"
                      minHeight={64}
                      color="#000"
                      gap={2}
                    >
                      <IconButton
                        color="inherit"
                        aria-label={`play/${
                          isPlaying
                            ? "pause"
                            : progress === 100
                            ? "Replay"
                            : "play"
                        }`}
                        disabled={
                          currentFrameMemo?.disabled
                            ? isReachedCurrentFrame
                              ? !isActionsCompleted
                              : false
                            : false
                        }
                        onClick={
                          isPlaying
                            ? handlePause
                            : progress === 100
                            ? handleReplay
                            : handlePlay
                        }
                      >
                        {!isPlaying && progress !== 100 && (
                          <PlayCircleIcon sx={{ height: 38, width: 38 }} />
                        )}
                        {!isPlaying && progress === 100 && (
                          <ReplayCircleFilledIcon
                            sx={{ height: 38, width: 38 }}
                          />
                        )}
                        {isPlaying && (
                          <PauseCircleIcon sx={{ height: 38, width: 38 }} />
                        )}
                      </IconButton>
                      <Box width="100%" position="relative">
                        <BorderLinearProgress
                          variant="determinate"
                          value={progress}
                        />
                        <item.Chart
                          sx={{
                            position: "absolute",
                            width: "100%",
                            height: "100%",
                            color: "transparent",
                            py: "8px",
                            top: 0,
                          }}
                        />
                        {currentFrameMemo?.alert && isReachedCurrentFrame && (
                          <ProgressAlert
                            status={currentFrameMemo.alert.status}
                            content={currentFrameMemo.alert.title}
                            boxSx={{
                              position: "absolute",
                              top: "8px",
                              ...(progress < 75 && {
                                left: `${progress + 5}%`,
                              }),
                              ...(progress >= 75 && {
                                right: `${100 - progress + 5}%`,
                              }),
                              animation: "button-blink 2s infinite, shake 1s",
                            }}
                          />
                        )}
                      </Box>
                    </Box>
                  </>
                )}
              </Card>
            </Grid>
          );
        })}
        <Grid xs={6}>
          {selectedItemMemo.id !== "analytical-workload" && (
            <DBSectionForSpikyWorkloadMysql
              key={playTimes}
              title="MySQL RDS"
              fileContent={selectedItemMemo.mysql.cfg}
              newFileContent={selectedItemMemo.mysql.modifiedCfg}
              frames={selectedItemMemo.frames}
              ADDED={[3, 5, 6, 7, 8, 9, 10, 11, 12]}
              handleCompleteActions={(actions: string[]) => {
                setCompletedActions((prev) => [...prev, ...actions]);
              }}
              currentFrameIndex={frameCount}
              isReachedCurrentFrame={isReachedCurrentFrame}
              isPlaying={isPlaying}
              isStart={progress > 0}
              isCompleted={progress >= 100}
              conclusion={selectedItemMemo?.mysql?.conclusion}
            />
          )}
          {selectedItemMemo.id === "analytical-workload" && (
            <DBSectionForAnalyticalWorkloadMysql
              key={playTimes}
              title="MySQL RDS"
              fileContent={selectedItemMemo.mysql.cfg}
              frames={selectedItemMemo.frames}
              handleCompleteActions={(actions: string[]) => {
                setCompletedActions((prev) => [...prev, ...actions]);
              }}
              currentFrameIndex={frameCount}
              isReachedCurrentFrame={isReachedCurrentFrame}
              isPlaying={isPlaying}
              isStart={progress > 0}
              isCompleted={progress >= 100}
              conclusion={selectedItemMemo?.mysql?.conclusion}
            />
          )}
        </Grid>
        <Grid xs={6}>
          {selectedItemMemo.id === "spiky-workload" && (
            <DBSectionForSpikyWorkloadTidb
              key={playTimes}
              title="TiDB Cloud Starter"
              fileContent={selectedItemMemo.tidb.cfg}
              // newFileContent={selectedItemMemo.tidb.modifiedCfg}
              frames={selectedItemMemo.frames}
              // ADDED={[3, 5, 6, 7, 8, 9, 10, 11, 12]}
              handleCompleteActions={(actions: string[]) => {
                setCompletedActions((prev) => [...prev, ...actions]);
              }}
              currentFrameIndex={frameCount}
              isReachedCurrentFrame={isReachedCurrentFrame}
              isPlaying={isPlaying}
              isStart={progress > 0}
              isCompleted={progress >= 100}
              conclusion={selectedItemMemo?.tidb?.conclusion}
            />
          )}
          {selectedItemMemo.id === "steadily-growing" && (
            <DBSectionForSteadilyWorkloadTidb
              key={playTimes}
              title="TiDB Cloud Dedicated"
              fileContent={selectedItemMemo.tidb.cfg}
              frames={selectedItemMemo.frames}
              handleCompleteActions={(actions: string[]) => {
                setCompletedActions((prev) => [...prev, ...actions]);
              }}
              currentFrameIndex={frameCount}
              isReachedCurrentFrame={isReachedCurrentFrame}
              isPlaying={isPlaying}
              isStart={progress > 0}
              isCompleted={progress >= 100}
              conclusion={selectedItemMemo?.tidb?.conclusion}
            />
          )}
          {selectedItemMemo.id === "analytical-workload" && (
            <DBSectionForAnalyticalWorkloadTidb
              key={playTimes}
              title="TiDB Cloud Starter"
              fileContent={selectedItemMemo.tidb.cfg}
              frames={selectedItemMemo.frames}
              handleCompleteActions={(actions: string[]) => {
                setCompletedActions((prev) => [...prev, ...actions]);
              }}
              currentFrameIndex={frameCount}
              isReachedCurrentFrame={isReachedCurrentFrame}
              isPlaying={isPlaying}
              isStart={progress > 0}
              isCompleted={progress >= 100}
              conclusion={selectedItemMemo?.tidb?.conclusion}
            />
          )}
        </Grid>
        {progress >= 100 && (
          <Box
            sx={{
              position: "absolute",
              top: "160px",
              left: "calc(50% - 18px)",

              border: "1px solid #000",
            }}
          >
            <Typography component="div" variant="h5">
              VS
            </Typography>
          </Box>
        )}
      </Grid>
    </>
  );
};

export const BorderLinearProgress = styled(LinearProgress)(({ theme }) => ({
  height: 68,
  borderRadius: 5,
  [`&.${linearProgressClasses.colorPrimary}`]: {
    backgroundColor: "#F7FFF7",
  },
  [`& .${linearProgressClasses.bar}`]: {
    borderRadius: 5,
    backgroundColor: "#E6FFDA",
    borderRight: "1px dashed #09D698",
  },
}));

const ProgressAlert = (props: {
  status: "info" | "warning" | string;
  content: string | React.ReactNode;
  boxSx?: BoxProps["sx"];
}) => {
  const { status, content, boxSx } = props;

  return (
    <>
      <Box
        sx={{
          padding: "8px 16px",
          background: "#FFFFFF",
          border: "1px solid #EAEAEA",
          boxShadow: "inset 4px 4px 4px rgba(255, 138, 0, 0.1)",
          borderRadius: "6px",
          display: "flex",
          alignItems: "center",
          gap: "8px",
          userSelect: "none",
          ...boxSx,
        }}
      >
        {status === "warning" && (
          <WarningIcon fontSize="inherit" color="warning" />
        )}
        <Typography
          fontWeight={600}
          fontSize={12}
          lineHeight={1.25}
          component="div"
        >
          {content}
        </Typography>
      </Box>
    </>
  );
};

const NoticeCard = (props: {
  title: string;
  content: string | React.ReactNode;
  cardSx?: CardProps["sx"];
}) => {
  const { title, content, cardSx } = props;

  return (
    <Card
      variant="outlined"
      sx={{
        padding: 1,
        ...cardSx,
      }}
    >
      <Typography fontWeight={600} fontSize={20} lineHeight="24px" gutterBottom>
        {title}
      </Typography>
      <Typography variant="body2" color="text.secondary">
        {content}
      </Typography>
    </Card>
  );
};

const ConclusionContent = (props: {
  items: (string | React.ReactNode)[];
  boxSx?: BoxProps["sx"];
}) => {
  const { items, boxSx } = props;

  return (
    <Box sx={{ ...boxSx }}>
      {items.map((item, index) => {
        if (typeof item === "string") {
          return (
            <Typography variant="body1" component="div" key={index}>
              {`${index + 1}. `}
              {item}
            </Typography>
          );
        }
        return (
          <>
            {`${index + 1}. `}
            {item}
          </>
        );
      })}
    </Box>
  );
};

function DBSectionTemplate(props: {
  title: string;
  fileContent: string;
  ADDED?: number[];
  children?: React.ReactNode;
  cfgChildren?: React.ReactNode;
  conclusionContent?: React.ReactNode;
  codeMinHeight?: string;
  disableCollapse?: boolean;
  boxSx?: BoxProps["sx"];
  childrenBoxSx?: BoxProps["sx"];
}) {
  const {
    title,
    fileContent,
    ADDED,
    children,
    cfgChildren,
    conclusionContent,
    codeMinHeight,
    disableCollapse,
    boxSx,
    childrenBoxSx,
  } = props;

  return (
    <Box
      sx={{
        backgroundColor: "#F0F4F6",
        p: "16px 20px",
        display: "flex",
        flexDirection: "column",
        gap: "16px",
        ...boxSx,
      }}
    >
      <Typography
        component="div"
        fontWeight={700}
        fontSize={16}
        lineHeight={1.5}
      >
        {title}
      </Typography>
      {conclusionContent}
      <Box
        sx={{
          background: "#FFFFFF",
          border: "1px solid #EAEAEA",
          borderRadius: "6px",
        }}
        position="relative"
      >
        <Typography
          gutterBottom
          sx={{
            fontWeight: 600,
            fontSize: "12px",
            lineHeight: "15px",
            p: "8px",
          }}
        >
          Config file
        </Typography>
        {disableCollapse ? (
          <Box minHeight={codeMinHeight || "256px"}>
            <UnifiedCodeDiffHighlight
              language="yaml"
              text={fileContent}
              showLineNumbers
              wrapLines
              ADDED={ADDED}
            />
          </Box>
        ) : (
          <CustomCollapse collapsedSize={80} defaultCollapse>
            <Box minHeight={codeMinHeight || "256px"}>
              <UnifiedCodeDiffHighlight
                language="yaml"
                text={fileContent}
                showLineNumbers
                wrapLines
                ADDED={ADDED}
              />
            </Box>
          </CustomCollapse>
        )}
        {cfgChildren}
      </Box>
      <Box
        height={240}
        sx={{
          background: "#FFFFFF",
          border: "1px solid #EAEAEA",
          borderRadius: "6px",
          display: "flex",
          alignItems: "center",
          justifyContent: "center",

          ...animationKeyframesProps,
          ...(childrenBoxSx as any),
        }}
      >
        {children}
      </Box>
    </Box>
  );
}

const BlinkButtonSx = {
  outline: "1px dashed #0F8CFF",
  outlineOffset: "4px",
  transition: "outline-offset 200ms ease",
  "&:hover": {
    outlineOffset: "2px",
  },
  opacity: 0.8,
  animation: "button-blink 2s infinite",
};

function DBSectionForSpikyWorkloadMysql(props: {
  title: string;
  fileContent: string;
  newFileContent?: string;
  ADDED?: number[];
  frames: (typeof easyScaleItems)[1]["frames"][0][];
  handleCompleteActions: (actions: string[]) => void;
  currentFrameIndex?: number;
  isReachedCurrentFrame?: boolean;
  isPlaying?: boolean;
  isCompleted?: boolean;
  conclusion?: (string | React.ReactNode)[];
  isStart?: boolean;
}) {
  const {
    title,
    fileContent,
    newFileContent,
    ADDED,
    frames,
    handleCompleteActions,
    currentFrameIndex,
    isReachedCurrentFrame,
    isPlaying,
    isCompleted,
    conclusion,
    isStart,
  } = props;

  const [hasAddedBucket, setHasAddedBucket] = React.useState(false);
  const [hasCheckCfg, setHasCheckCfg] = React.useState(false);

  const currentFrame = frames[currentFrameIndex || 0];

  const CfgCheckButtonCallback = React.useCallback(() => {
    return (
      <Box
        sx={{
          position: "absolute",
          top: "8px",
          right: "8px",
        }}
      >
        <Box position="relative">
          <Button
            variant="contained"
            disabled={!hasAddedBucket || hasCheckCfg}
            endIcon={hasCheckCfg && <CheckIcon fontSize="inherit" />}
            onClick={() => {
              setHasCheckCfg(true);
              handleCompleteActions(["mysql-check-cfg"]);
            }}
            sx={{
              ...(!(!hasAddedBucket || hasCheckCfg) && BlinkButtonSx),
            }}
          >
            2. Modify configuration
          </Button>
          {!(!hasAddedBucket || hasCheckCfg) && <ClickArrowAnimation />}
        </Box>
      </Box>
    );
  }, [handleCompleteActions, hasAddedBucket, hasCheckCfg]);

  const KeepRunningWithCurCfgFlag = () => {
    return (
      <Box
        sx={{
          position: "absolute",
          top: "8px",
          right: "8px",
        }}
      >
        <Box position="relative">
          <Button variant="contained" disabled={true}>
            3. Keep running with current configuration
          </Button>
        </Box>
      </Box>
    );
  };

  return (
    <DBSectionTemplate
      title={title}
      fileContent={(hasCheckCfg ? newFileContent : fileContent) || fileContent}
      ADDED={hasCheckCfg ? ADDED : undefined}
      cfgChildren={
        (currentFrameIndex === 0 && isReachedCurrentFrame && (
          <CfgCheckButtonCallback />
        )) ||
        (currentFrameIndex && currentFrameIndex >= 1 && (
          <KeepRunningWithCurCfgFlag />
        )) ||
        null
      }
      conclusionContent={
        conclusion && isCompleted && <ConclusionContent items={conclusion} />
      }
      // boxSx={{
      //   "@keyframes button-blink": {
      //     "0%": {
      //       opacity: 0.8,
      //     },
      //     "50%": {
      //       opacity: 1,
      //     },
      //     "100%": {
      //       opacity: 0.8,
      //     },
      //   },
      // }}
    >
      {currentFrameIndex === 0 && !isReachedCurrentFrame && (
        <DefaultBucketAnimation />
      )}
      {currentFrameIndex === 0 && isReachedCurrentFrame && (
        <Box
          display="flex"
          alignItems="center"
          justifyContent="center"
          flexDirection="column"
          gap={2}
        >
          <Stack direction="row" spacing={2}>
            <Grow in={true}>
              <Box>
                {hasAddedBucket ? (
                  <DefaultBucketAnimation />
                ) : (
                  <DangerBucketAnimation />
                )}
              </Box>
            </Grow>
            {hasAddedBucket && (
              <Grow
                in={hasAddedBucket}
                style={{ transformOrigin: "0 0 0" }}
                {...(hasAddedBucket ? { timeout: 1000 } : {})}
              >
                <Box>
                  <DefaultBucketAnimation />
                </Box>
              </Grow>
            )}
          </Stack>

          <Box position="relative">
            <Button
              variant="contained"
              disabled={hasAddedBucket}
              endIcon={hasAddedBucket && <CheckIcon fontSize="inherit" />}
              onClick={() => {
                setHasAddedBucket(true);
                handleCompleteActions(["mysql-add-node"]);
              }}
              sx={{
                position: "relative",
                ...(!hasAddedBucket && BlinkButtonSx),
              }}
            >
              1. Click to add nodes
            </Button>
            {!hasAddedBucket && <ClickArrowAnimation />}
          </Box>
          <Typography variant="body2" color="text.secondary" textAlign="center">
            *Usually, it may cost more than one week. We accelerated the process
            here.
          </Typography>
        </Box>
      )}

      {!!currentFrameIndex && currentFrameIndex >= 1 && !isCompleted && (
        <Box
          display="flex"
          alignItems="center"
          justifyContent="space-around"
          width="100%"
        >
          <Stack direction="row" spacing={2}>
            <DefaultBucketAnimation />
            <DefaultBucketAnimation />
          </Stack>
          <NoticeCard
            title="😭 Higher Cost"
            content="In order to handle the growth data, keep running with high configuration"
            cardSx={{
              width: "240px",
            }}
          />
        </Box>
      )}

      {isCompleted && (
        <Box
          display="flex"
          alignItems="center"
          justifyContent="space-around"
          width="100%"
        >
          <Stack direction="row" spacing={2}>
            <DefaultBucketAnimation />
            <DefaultBucketAnimation play={false} />
            <DefaultBucketAnimation play={false} />
          </Stack>
        </Box>
      )}
    </DBSectionTemplate>
  );
}

function DBSectionForAnalyticalWorkloadMysql(props: {
  title: string;
  fileContent: string;
  frames: (typeof easyScaleItems)[2]["frames"][0][];
  handleCompleteActions: (actions: string[]) => void;
  currentFrameIndex?: number;
  isReachedCurrentFrame?: boolean;
  isPlaying?: boolean;
  isCompleted?: boolean;
  conclusion?: (string | React.ReactNode)[];
  isStart?: boolean;
}) {
  const {
    title,
    fileContent,
    frames,
    handleCompleteActions,
    currentFrameIndex,
    isReachedCurrentFrame,
    isPlaying,
    isCompleted,
    conclusion,
    isStart,
  } = props;

  const [hasCheckNode, setHasCheckNode] = React.useState(false);

  const handleCheckNode = React.useCallback(() => {
    setHasCheckNode(true);
    handleCompleteActions(["mysql-check-node-overload"]);
  }, [handleCompleteActions]);

  return (
    <DBSectionTemplate
      title={title}
      fileContent={fileContent}
      conclusionContent={
        conclusion &&
        isCompleted && (
          <ConclusionContent items={conclusion} boxSx={{ minHeight: "48px" }} />
        )
      }
      disableCollapse
      codeMinHeight="90px"
    >
      {currentFrameIndex === 0 && !isReachedCurrentFrame && (
        <DefaultBucketAnimation />
      )}
      {(!!(currentFrameIndex === 0 && isReachedCurrentFrame) ||
        !!(currentFrameIndex && currentFrameIndex > 0)) && (
        <Box
          display="flex"
          alignItems="center"
          justifyContent="center"
          flexDirection="column"
          gap={2}
        >
          <Box
            sx={{
              position: "relative",
              width: "100px",
              height: "100px",
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
            }}
          >
            <DangerBucketAnimation />
            {!(currentFrameIndex === 0 && isReachedCurrentFrame) && (
              <ClearIcon
                sx={{
                  position: "absolute",
                  top: "0",
                  left: "0",
                  color: "error.main",
                  width: "100px",
                  height: "100px",
                }}
              />
            )}
          </Box>
          <Box position="relative">
            <Button
              variant="contained"
              disabled={hasCheckNode}
              endIcon={hasCheckNode && <CheckIcon fontSize="inherit" />}
              onClick={handleCheckNode}
              sx={{
                ...(!hasCheckNode && BlinkButtonSx),
              }}
            >
              🚨 MySQL might be overload when run some analytical queries
            </Button>
            {!hasCheckNode && <ClickArrowAnimation />}
          </Box>
          {/* <Typography variant="body2" fontWeight="bold" textAlign="center">
            🚨 MySQL might be overload when run some analytical queries
          </Typography> */}
        </Box>
      )}
    </DBSectionTemplate>
  );
}

function DBSectionForSpikyWorkloadTidb(props: {
  title: string;
  fileContent: string;
  newFileContent?: string;
  ADDED?: number[];
  frames: (typeof easyScaleItems)[1]["frames"][0][];
  handleCompleteActions: (actions: string[]) => void;
  currentFrameIndex?: number;
  isReachedCurrentFrame?: boolean;
  isPlaying?: boolean;
  isCompleted?: boolean;
  conclusion?: (string | React.ReactNode)[];
  isStart?: boolean;
}) {
  const {
    title,
    fileContent,
    newFileContent,
    ADDED,
    frames,
    handleCompleteActions,
    currentFrameIndex,
    isReachedCurrentFrame,
    isPlaying,
    isCompleted,
    conclusion,
    isStart,
  } = props;

  const [hasAddedBucket, setHasAddedBucket] = React.useState(false);
  const [hasCheckCfg, setHasCheckCfg] = React.useState(false);

  const currentFrame = frames[currentFrameIndex || 0];

  const CfgFlagCallback = React.useCallback(() => {
    return (
      <NoCfgChangesRequiredIcon
        sx={{
          width: "158px",
          height: "138px",
          position: "absolute",
          top: "-25px",
          right: "-21px",
        }}
      />
    );
  }, []);

  return (
    <DBSectionTemplate
      title={title}
      fileContent={(hasCheckCfg ? newFileContent : fileContent) || fileContent}
      ADDED={hasCheckCfg ? ADDED : undefined}
      cfgChildren={
        (((currentFrameIndex === 0 && isReachedCurrentFrame) ||
          (!!currentFrameIndex && currentFrameIndex >= 0)) && (
          <CfgFlagCallback />
        )) ||
        null
      }
      conclusionContent={
        conclusion && isCompleted && <ConclusionContent items={conclusion} />
      }
      childrenBoxSx={{ flexDirection: "column", gap: 1 }}
    >
      {currentFrameIndex === 0 && !isReachedCurrentFrame && (
        <DefaultBucketAnimation />
      )}
      {currentFrameIndex === 0 && isReachedCurrentFrame && (
        <>
          <Box
            display="flex"
            alignItems="center"
            justifyContent="center"
            flexDirection="row"
            gap={11}
          >
            <DefaultBucketAnimation boxSx={{ height: "58px" }} />
            <ResourcePoolExtensionAnimation play />
          </Box>

          {!isCompleted && (
            <Typography
              variant="body2"
              fontWeight="bold"
              display="inline-flex"
              alignItems="center"
              gap={1}
            >
              <CircularProgress size={20} />
              Auto Scaling
            </Typography>
          )}
        </>
      )}

      {!!currentFrameIndex && currentFrameIndex === 1 && !isCompleted && (
        <Box
          display="flex"
          alignItems="center"
          justifyContent="space-around"
          width="100%"
        >
          <Box
            display="flex"
            flexDirection="column"
            alignItems="center"
            justifyContent="center"
          >
            <Stack direction="row" spacing={2}>
              <DefaultBucketAnimation />
              <DefaultBucketAnimation play={false} />
            </Stack>
            <ResourcePoolExtensionAnimation play={false} />
          </Box>
          <NoticeCard
            title="😊 Pay as you go"
            content="Auto scale in and keep the minimal cost"
            cardSx={{
              width: "240px",
            }}
          />
        </Box>
      )}

      {!!currentFrameIndex && currentFrameIndex > 1 && !isCompleted && (
        <>
          <Box
            display="flex"
            alignItems="center"
            justifyContent="center"
            flexDirection="row"
            gap={11}
          >
            <DefaultBucketAnimation boxSx={{ height: "58px" }} />
            <ResourcePoolExtensionAnimation play reverse />
          </Box>

          {!isCompleted && (
            <Typography
              variant="body2"
              fontWeight="bold"
              display="inline-flex"
              alignItems="center"
              gap={1}
            >
              <CircularProgress size={20} />
              Auto Scaling
            </Typography>
          )}
        </>
      )}

      {isCompleted && (
        <Box
          display="flex"
          alignItems="center"
          justifyContent="space-around"
          width="100%"
        >
          <Stack direction="row" spacing={2}>
            <DefaultBucketAnimation />
            <DefaultBucketAnimation play={false} />
            <DefaultBucketAnimation play={false} />
          </Stack>
        </Box>
      )}
    </DBSectionTemplate>
  );
}

function DBSectionForSteadilyWorkloadTidb(props: {
  title: string;
  fileContent: string;
  frames: (typeof easyScaleItems)[2]["frames"][0][];
  handleCompleteActions: (actions: string[]) => void;
  currentFrameIndex?: number;
  isReachedCurrentFrame?: boolean;
  isPlaying?: boolean;
  isCompleted?: boolean;
  conclusion?: (string | React.ReactNode)[];
  isStart?: boolean;
}) {
  const {
    title,
    fileContent,
    frames,
    handleCompleteActions,
    currentFrameIndex,
    isReachedCurrentFrame,
    isPlaying,
    isCompleted,
    conclusion,
    isStart,
  } = props;

  const CfgFlagCallback = React.useCallback(() => {
    return (
      <NoCfgChangesRequiredIcon
        sx={{
          width: "158px",
          height: "138px",
          position: "absolute",
          top: "-25px",
          right: "-21px",
        }}
      />
    );
  }, []);

  return (
    <DBSectionTemplate
      title={title}
      fileContent={fileContent}
      conclusionContent={
        conclusion && isCompleted && <ConclusionContent items={conclusion} />
      }
      cfgChildren={
        (((currentFrameIndex === 0 && isReachedCurrentFrame) ||
          (!!currentFrameIndex && currentFrameIndex >= 0)) && (
          <CfgFlagCallback />
        )) ||
        null
      }
    >
      {currentFrameIndex === 0 && !isReachedCurrentFrame && (
        <DefaultBucketAnimation />
      )}
      {((currentFrameIndex && currentFrameIndex > 0) ||
        isReachedCurrentFrame) && (
        <Box
          display="flex"
          alignItems="center"
          justifyContent="space-around"
          flexDirection="column"
          width="100%"
          gap={1}
        >
          {/* <iframe
            width="346"
            height="182"
            src="https://www.youtube.com/embed/wq2xLnSYlV0"
            title="YouTube video player"
            frameBorder="0"
            allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
            allowFullScreen
          ></iframe> */}
          <YoutubePlayer
            url="https://www.youtube.com/embed/wq2xLnSYlV0"
            controls
            boxSx={{
              backgroundImage: `url(/img/scale-out-with-a-few-clicks.png)`,
              backgroundSize: "cover",
            }}
          />
          {/* <DefaultBucketAnimation boxSx={{ height: "58px" }} /> */}
          <Typography color="text.secondary" variant="body2">
            Scale out with a few clicks!
          </Typography>
        </Box>
      )}
    </DBSectionTemplate>
  );
}

function DBSectionForAnalyticalWorkloadTidb(props: {
  title: string;
  fileContent: string;
  frames: (typeof easyScaleItems)[2]["frames"][0][];
  handleCompleteActions: (actions: string[]) => void;
  currentFrameIndex?: number;
  isReachedCurrentFrame?: boolean;
  isPlaying?: boolean;
  isCompleted?: boolean;
  conclusion?: (string | React.ReactNode)[];
  isStart?: boolean;
}) {
  const {
    title,
    fileContent,
    frames,
    handleCompleteActions,
    currentFrameIndex,
    isReachedCurrentFrame,
    isPlaying,
    isCompleted,
    conclusion,
    isStart,
  } = props;

  return (
    <DBSectionTemplate
      title={title}
      fileContent={fileContent}
      conclusionContent={
        conclusion && isCompleted && <ConclusionContent items={conclusion} />
      }
      disableCollapse
      codeMinHeight="auto"
      childrenBoxSx={{ flexDirection: "column", gap: 1 }}
    >
      {currentFrameIndex === 0 && !isReachedCurrentFrame && (
        <DefaultBucketAnimation />
      )}
      {((currentFrameIndex && currentFrameIndex > 0) ||
        isReachedCurrentFrame) && (
        <>
          <Box
            display="flex"
            alignItems="center"
            justifyContent="center"
            flexDirection="row"
            gap={11}
          >
            <Box
              sx={{
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
                flexDirection: "row",
                gap: 1.5,
              }}
            >
              <DefaultBucketAnimation boxSx={{ height: "58px" }} />
              {!!(currentFrameIndex === 1) && (
                <APBucket
                  sx={{ height: "58px", width: "auto", color: "transparent" }}
                />
              )}
            </Box>
            {!isCompleted && (
              <ResourcePoolExtensionAnimation
                isAP
                play
                reverse={
                  (currentFrameIndex === 1 && isReachedCurrentFrame) ||
                  currentFrameIndex === 2
                }
              />
            )}
          </Box>

          {!isCompleted && (
            <Typography
              variant="body2"
              fontWeight="bold"
              display="inline-flex"
              alignItems="center"
              gap={1}
            >
              <CircularProgress size={20} />
              Analytic nodes are auto scaling
            </Typography>
          )}
        </>
      )}
    </DBSectionTemplate>
  );
}
