import { useEffect, useRef, useState } from "react";
import { Box, useTheme, useMediaQuery } from "@mui/material";
import { DataGrid } from "@mui/x-data-grid";

import { scrollBlock } from "@root/utils/scrollBlock";

import forwardIcon from "@root/assets/icons/forward.svg";

import type { ChangeEvent } from "react";
import type { GridColDef } from "@mui/x-data-grid";

const COLUMNS: GridColDef[] = [
  {
    field: "date",
    headerName: "Дата",
    minWidth: 130,
    maxWidth: 200,
    flex: 1,
    sortable: false,
  },
  {
    field: "time",
    headerName: "Время",
    minWidth: 90,
    maxWidth: 180,
    flex: 1,
    sortable: false,
  },
  {
    field: "product",
    headerName: "Товар",
    minWidth: 200,
    maxWidth: 280,
    flex: 1,
    sortable: false,
  },
  {
    field: "amount",
    headerName: "Кол-во",
    minWidth: 70,
    maxWidth: 70,
    flex: 1,
    sortable: false,
  },
];

const ROWS = [
  {
    id: "row_1",
    date: "19.02.2023",
    time: "17:01",
    product: "Шаблонизатор",
    amount: "1 шт.",
  },
  {
    id: "row_2",
    date: "28.02.2023",
    time: "10:43",
    product: "Шаблонизатор",
    amount: "1 шт.",
  },
  {
    id: "row_3",
    date: "04.03.2023",
    time: "21:09",
    product: "Сокращатель ссылок",
    amount: "2 шт.",
  },
];

export const PurchaseTab = () => {
  const [canScrollToRight, setCanScrollToRight] = useState<boolean>(true);
  const [canScrollToLeft, setCanScrollToLeft] = useState<boolean>(false);
  const theme = useTheme();
  const smallScreen = useMediaQuery(theme.breakpoints.down(830));
  const gridContainer = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const handleScroll = (nativeEvent: unknown) => {
      const { target } = nativeEvent as ChangeEvent<HTMLDivElement>;

      if (target.scrollLeft > 0) {
        setCanScrollToLeft(true);
      } else {
        setCanScrollToLeft(false);
      }

      if (target.clientWidth + target.scrollLeft >= target.scrollWidth - 1) {
        setCanScrollToRight(false);
      } else {
        setCanScrollToRight(true);
      }
    };

    const addScrollEvent = () => {
      const grid = gridContainer.current?.querySelector(
        ".MuiDataGrid-virtualScroller"
      );

      if (grid) {
        grid.addEventListener("scroll", handleScroll);

        return;
      }

      setTimeout(addScrollEvent, 100);
    };

    addScrollEvent();

    return () => {
      const grid = gridContainer.current?.querySelector(
        ".MuiDataGrid-virtualScroller"
      );

      grid?.removeEventListener("scroll", handleScroll);
    };
  }, []);

  const scrollDataGrid = (toStart = false) => {
    const grid = gridContainer.current?.querySelector(
      ".MuiDataGrid-virtualScroller"
    );

    if (grid) {
      scrollBlock(grid, { left: toStart ? 0 : grid.scrollWidth });
    }
  };

  return (
    <Box
      ref={gridContainer}
      sx={{
        height: "100%",
        padding: "0 25px",
        "&:before": {
          content: '""',
          height: "50px",
          width: "100%",
          position: "absolute",
          left: "0",
          top: "0",
          background: "#F2F3F7",
        },
      }}
    >
      <DataGrid
        rows={ROWS}
        columns={COLUMNS}
        pageSize={5}
        rowsPerPageOptions={[5]}
        hideFooter
        disableColumnMenu
        disableSelectionOnClick
        rowHeight={50}
        headerHeight={50}
        experimentalFeatures={{ newEditingApi: true }}
        sx={{
          borderRadius: "0",
          border: "none",
          "& .MuiDataGrid-columnHeaders": {
            background: "#F2F3F7",
            borderBottom: "none",
          },
          "& .MuiDataGrid-main .MuiDataGrid-columnHeader": {
            outline: "none",
          },
          "& .MuiDataGrid-columnHeaderTitle": {
            fontWeight: "bold",
            userSelect: "none",
          },
          "& .MuiDataGrid-virtualScrollerRenderZone": {
            width: "100%",
          },
          "& .MuiDataGrid-iconSeparator": { display: "none" },
          "& .MuiDataGrid-main .MuiDataGrid-cell": {
            outline: "none",
            border: "none",
            justifyContent: "flex-start",
          },
          "& .MuiDataGrid-row": {
            width: "100%",
            "&:hover": {
              background: "#F2F3F7",
            },
          },
        }}
      />
      {smallScreen && (
        <Box
          sx={{
            position: "absolute",
            right: "15px",
            bottom: "50px",
            display: "flex",
            columnGap: "5px",
          }}
        >
          {canScrollToLeft && (
            <Box
              sx={{
                display: "flex",
                justifyContent: "center",
                alignItems: "center",
                width: "30px",
                height: "30px",
                borderRadius: "8px",
                border: "1px solid #7E2AEA",
                background: "rgba(126, 42, 234, 0.07)",
              }}
              onClick={() => scrollDataGrid(true)}
            >
              <img
                src={forwardIcon}
                alt="forward"
                style={{ transform: "rotate(180deg)" }}
              />
            </Box>
          )}
          {canScrollToRight && (
            <Box
              sx={{
                display: "flex",
                justifyContent: "center",
                alignItems: "center",
                width: "30px",
                height: "30px",
                borderRadius: "8px",
                border: "1px solid #7E2AEA",
                background: "rgba(126, 42, 234, 0.07)",
              }}
              onClick={() => scrollDataGrid(false)}
            >
              <img src={forwardIcon} alt="forward" />
            </Box>
          )}
        </Box>
      )}
    </Box>
  );
};
