/* eslint-disable jsx-a11y/anchor-is-valid */
import { useState } from "react";
import { Button, Link, Input, Table, Sheet, Typography, Box } from "@mui/joy";
import CustomAlert from "~/components/CustomAlert";
import EditCategoryForm from "./EditCategoryForm";
import * as Icon from "react-feather";
import { api } from "~/utils/api";

function descendingComparator<T>(a: T, b: T, orderBy: keyof T) {
  if (b[orderBy] < a[orderBy]) {
    return -1;
  }
  if (b[orderBy] > a[orderBy]) {
    return 1;
  }
  return 0;
}

type Order = "asc" | "desc";

function getComparator<Key extends keyof any>(
  order: Order,
  orderBy: Key
): (
  a: { [key in Key]: number | string },
  b: { [key in Key]: number | string }
) => number {
  return order === "desc"
    ? (a, b) => descendingComparator(a, b, orderBy)
    : (a, b) => -descendingComparator(a, b, orderBy);
}

function stableSort<T>(
  array: readonly T[],
  comparator: (a: T, b: T) => number
) {
  const stabilizedThis = array.map((el, index) => [el, index] as [T, number]);
  stabilizedThis.sort((a, b) => {
    const order = comparator(a[0], b[0]);
    if (order !== 0) {
      return order;
    }
    return a[1] - b[1];
  });
  return stabilizedThis.map((el) => el[0]);
}

export default function CategoryTable({ categoriesQuery }) {
  const [editOpen, setEditOpen] = useState(false);
  const [order, setOrder] = useState<Order>("desc");
  const [category, setCategory] = useState({});

  const [customAlert, setAlert] = useState({
    open: false,
    type: "success",
    text: "",
    duration: 6000,
  });

  const createAlert = (settings) => {
    setAlert({ ...settings, open: true });
  };

  const deleteCategoryMutation = api.category.deleteCategory.useMutation({
    onSuccess: (data) => {
      createAlert({
        type: "success",
        text: "Categoria excluida com sucesso!",
        duration: 6000,
      });
    },
    onError: (error) => {
      createAlert({
        type: "error",
        text: error.message,
        duration: 6000,
      });
    },
    onSettled: () => categoriesQuery.refetch(),
  });

  const deleteCategory = (category_id) => {
    if (confirm("Você tem certeza que quer excluir a categoria?")) {
      deleteCategoryMutation.mutate({
        category_id,
      });
    }
  };

  return (
    <>
      <EditCategoryForm
        open={editOpen}
        setOpen={setEditOpen}
        categoriesQuery={categoriesQuery}
        category={category}
      />
      <CustomAlert customAlert={customAlert} setAlert={setAlert} />
      <Sheet
        className='OrderTableContainer'
        variant='outlined'
        sx={{
          width: "100%",
          borderRadius: "md",
          flex: 1,
          overflow: "auto",
          minHeight: 0,
        }}
      >
        <Table
          aria-labelledby='tableTitle'
          stickyHeader
          hoverRow
          sx={{
            "--TableCell-headBackground": (theme) =>
              theme.vars.palette.background.level1,
            "--Table-headerUnderlineThickness": "1px",
            "--TableRow-hoverBackground": (theme) =>
              theme.vars.palette.background.level1,
          }}
        >
          <thead>
            <tr>
              <th style={{ width: 80, padding: 12 }}>
                <Link
                  underline='none'
                  color='primary'
                  component='button'
                  onClick={() => setOrder(order === "asc" ? "desc" : "asc")}
                  fontWeight='lg'
                  endDecorator={<Icon.ArrowDown />}
                  sx={{
                    "& svg": {
                      transition: "0.2s",
                      transform:
                        order === "desc" ? "rotate(0deg)" : "rotate(180deg)",
                    },
                  }}
                >
                  #
                </Link>
              </th>
              <th style={{ width: 200, padding: 12 }}>Nome</th>
              <th style={{ padding: 12 }}>Descrição</th>
              <th style={{ width: 120, padding: 12 }}>Editar</th>
              <th style={{ width: 80, padding: 12 }}>Excluir</th>
            </tr>
          </thead>
          <tbody>
            {categoriesQuery.isSuccess &&
              stableSort(
                categoriesQuery.data.categories,
                getComparator(order, "id")
              ).map((category) => (
                <tr key={category.id}>
                  <td>
                    <Typography fontWeight='md'>{category.id}</Typography>
                  </td>
                  <td>{category.name}</td>
                  <td>{category.description}</td>
                  <td>
                    <Button
                      variant='outlined'
                      color='neutral'
                      startDecorator={<Icon.Edit />}
                      onClick={() => {
                        setCategory(category);
                        setEditOpen(true);
                      }}
                    >
                      Editar
                    </Button>
                  </td>
                  <td>
                    <Box justifyContent='center'>
                      <Button
                        variant='solid'
                        color='danger'
                        onClick={() => {
                          deleteCategory(category.id);
                        }}
                      >
                        <Icon.Trash size={18} />
                      </Button>
                    </Box>
                  </td>
                </tr>
              ))}
          </tbody>
        </Table>
      </Sheet>
      {/* <Box
        className='Pagination-mobile'
        sx={{ display: { xs: "flex", md: "none" }, alignItems: "center" }}
      >
        <IconButton
          aria-label='previous page'
          variant='outlined'
          color='neutral'
          size='sm'
        >
          <Icon.ArrowLeft />
        </IconButton>
        <Typography level='body2' mx='auto'>
          Page 1 of 10
        </Typography>
        <IconButton
          aria-label='next page'
          variant='outlined'
          color='neutral'
          size='sm'
        >
          <Icon.ArrowRight />
        </IconButton>
      </Box>
      <Box
        className='Pagination-laptopUp'
        sx={{
          pt: 4,
          gap: 1,
          [`& .${iconButtonClasses.root}`]: { borderRadius: "50%" },
          display: {
            xs: "none",
            md: "flex",
          },
        }}
      >
        <Button
          size='sm'
          variant='plain'
          color='neutral'
          startDecorator={<Icon.ArrowLeft />}
        >
          Previous
        </Button>

        <Box sx={{ flex: 1 }} />
        {["1", "2", "3", "…", "8", "9", "10"].map((page) => (
          <IconButton
            key={page}
            size='sm'
            variant={Number(page) ? "outlined" : "plain"}
            color='neutral'
          >
            {page}
          </IconButton>
        ))}
        <Box sx={{ flex: 1 }} />

        <Button
          size='sm'
          variant='plain'
          color='neutral'
          endDecorator={<Icon.ArrowRight />}
        >
          Next
        </Button>
      </Box> */}
    </>
  );
}
