import * as React from "react";
import { styled } from "@mui/material/styles";
import Box from "@mui/material/Box";
import Card from "@mui/material/Card";
import CardActions from "@mui/material/CardActions";
import CardContent from "@mui/material/CardContent";
import Button from "@mui/material/Button";
import Typography from "@mui/material/Typography";
import Stack from "@mui/material/Stack";
import NorthEastIcon from "@mui/icons-material/NorthEast";
import LoadingButton from "@mui/lab/LoadingButton";
import Skeleton from "@mui/material/Skeleton";

import CodeBlock from "@/components/CodeBlock";
import SQLStatus from "@/components/Status/SQLStatus";
import SQLExecutionPlanDialog from "@/components/Dialog/SQLExecutionPlanDialog";
import SQLResultTable from "@/components/Table/SQLResultTable";
import ExplainTable from "@/components/Table/ExplainTable";
import TableSchemaButton from "@/components/Button/TableSchemaButton";

import type {
  SQLFieldsType,
  SQLResultRowType,
} from "@/components/CodeBlock/SQLDiff";

export const StyledCard = styled(Card)(({ theme }) => ({
  minWidth: 275,
  backgroundColor: "#F6F8FC",
  "--ds--code--bg-color": "#F6F8FC",
  height: "100%",
  "&.MuiPaper-root": {
    display: "flex",
    flexDirection: "column",
    height: "100%",
    justifyContent: "space-between",
  },
}));

export interface SQLCardProps {
  sql: string;
  onClick?: () => void;
  loading?: boolean;
  disabled?: boolean;
  disableRun?: boolean;
  showLineNumbers?: boolean;
  wrapLongLines?: boolean;
  errorMsg?: string;
  mode?: "default" | "light";
}

export default function SQLCard(props: SQLCardProps) {
  const {
    sql,
    onClick,
    loading,
    disabled,
    disableRun,
    showLineNumbers,
    wrapLongLines,
    errorMsg,
    mode = "default",
  } = props;

  return (
    <StyledCard
      variant="outlined"
      sx={{
        ...(mode === "light" && {
          backgroundColor: "#fff",
        }),
      }}
    >
      <CardContent>
        {/* <Typography
          sx={{ fontSize: 12 }}
          color="text.secondary"
          mb={0}
          component="div"
        >
          SQL
        </Typography> */}
        <CodeBlock
          language="sql"
          text={sql}
          showLineNumbers={!!showLineNumbers}
          wrapLongLines={!!wrapLongLines}
          transparentBackground
          boxSxProps={{
            ...(mode === "light" && {
              backgroundColor: "#fff",
            }),
          }}
          CustomContent={TableSchemaButton}
        />
        {errorMsg && (
          <Typography variant="body2" color="error" component="div">
            {errorMsg}
          </Typography>
        )}
      </CardContent>
      {!disableRun && (
        <CardActions
          sx={{
            justifyContent: "flex-end",
          }}
        >
          <LoadingButton
            size="small"
            variant="contained"
            onClick={onClick}
            loading={loading}
            disabled={disabled}
          >
            Run
          </LoadingButton>
        </CardActions>
      )}
    </StyledCard>
  );
}

export function SQLStatusCard(props: {
  status: ({
    status: "success" | "error" | "loading";
    label: string;
    content: string | JSX.Element;
    tip?: string | null;
    hidden?: boolean;
  } | null)[];
  data: { [x: string]: string }[];
  content?: string | JSX.Element;
  mode?: "default" | "light";
}) {
  const { data, status, content, mode = "default" } = props;

  return (
    <StyledCard
      variant="outlined"
      sx={{
        ...(mode === "light" && {
          backgroundColor: "#fff",
        }),
      }}
    >
      <CardContent>
        <Stack
          direction="column"
          justifyContent="center"
          alignItems="flex-start"
          spacing={1}
          sx={{
            overflowX: "auto",
          }}
        >
          {status.map(
            (item, index) =>
              item &&
              !item.hidden && (
                <SQLStatus
                  key={index}
                  status={item.status}
                  label={item.label}
                  content={item.content}
                  tip={item.tip}
                />
              )
          )}
        </Stack>
        {content && (
          <Box
            sx={{
              fontSize: 12,
              pt: (theme) => theme.spacing(1),
            }}
          >
            {content}
          </Box>
        )}
      </CardContent>
      <CardActions>
        <SQLExecutionPlanDialog data={data} />
      </CardActions>
    </StyledCard>
  );
}

export function LoadingCard(props: { mode?: "default" | "light" }) {
  const { mode = "default" } = props;

  return (
    <StyledCard
      variant="outlined"
      sx={{
        ...(mode === "light" && {
          backgroundColor: "#fff",
        }),
      }}
    >
      <CardContent>
        <Typography variant="h5" component="div">
          <Skeleton animation="wave" />
        </Typography>
      </CardContent>
    </StyledCard>
  );
}

export interface SQLResultPreviewCardTableProps {
  fields: SQLFieldsType[];
  rows: SQLResultRowType[];
  type?: "table";
  mode?: "default" | "light";
}

export interface SQLExecutionPlanCardCodeProps {
  text: string;
  language?: any;
  type: "code";
  mode?: "default" | "light";
}

export function SQLResultPreviewCard(
  props: SQLResultPreviewCardTableProps | SQLExecutionPlanCardCodeProps
) {
  const { mode = "default" } = props;

  return (
    <StyledCard
      variant="outlined"
      sx={{
        ...(mode === "light" && {
          backgroundColor: "#fff",
        }),
      }}
    >
      <CardContent>
        <Typography
          sx={{ fontSize: 12 }}
          color="text.secondary"
          mb={0}
          component="div"
        >
          Output
        </Typography>

        {(!props.type || props?.type === "table") && (
          <SQLResultTable fields={props.fields} rows={props.rows} />
        )}
        {props.type === "code" && (
          <CodeBlock
            showLineNumbers={false}
            language={props.language}
            text={props.text}
            transparentBackground
          />
        )}
      </CardContent>
    </StyledCard>
  );
}

export function SQLExecutionPlanCard(props: {
  data: { [x: string]: string }[];
  mode?: "default" | "light";
}) {
  const { data, mode = "default" } = props;

  return (
    <StyledCard
      variant="outlined"
      sx={{
        ...(mode === "light" && {
          backgroundColor: "#fff",
        }),
      }}
    >
      <CardContent>
        <Typography
          sx={{ fontSize: 12 }}
          color="text.secondary"
          mb={0}
          component="div"
        >
          Execution Plan
        </Typography>
        <ExplainTable
          data={data}
          TableSx={{
            maxHeight: 300,
          }}
        />
      </CardContent>
    </StyledCard>
  );
}
