import { useCallback, useEffect, useState } from "react";
import PageContainer from "./PageContainer";
import {
  Tooltip,
  Chip,
  Typography,
  Grid2,
} from "@mui/material";
import { pond } from "protobuf-ts/pond";
import { useMineAPI } from "hooks";
import AddMine from "ventilation/AddMine";
import { LibraryAdd } from "@mui/icons-material";
import ResponsiveTable, { Column } from "common/ResponsiveTable";
import { useNavigate } from "react-router-dom";
import { or } from "utils";
import { useGlobalState } from "providers";
import { cloneDeep } from "lodash";

interface MineRow {
  mine: pond.Mine;
}

const mineColumns: Column<MineRow>[] = [
  {
    title: "Name",
    cellStyle: { margin: 1 },
    render: row => {
      let key = row.mine.settings?.key ? row.mine.settings?.key : "No Key found";
      let name = row.mine.settings?.name ? row.mine.settings?.name : "Mine";
      return (
        <Tooltip title={"ID: " + key}>
          <Chip variant="outlined" label={name} />
        </Tooltip>
      );
    }
  }
];

export default function Mines() {
  const mineAPI = useMineAPI();
  const navigate = useNavigate();
  const [isLoading, setIsLoading] = useState<boolean>(false);
  const [mineTableData, setMineTableData] = useState<MineRow[]>([]);
  const [minesTotal, setMinesTotal] = useState<number>(0);
  const [page, setPage] = useState(0);
  const [pageSize, setPageSize] = useState(10);
  const [mineDialog, setMineDialog] = useState(false);
  const [searchValue, setSearchValue] = useState("");
  const [{as}] = useGlobalState();

  const load = useCallback(() => {
    setIsLoading(true);
    mineAPI
      .listMines(pageSize, pageSize * page, "desc", undefined, searchValue, false, as)
      .then(resp => {
        let mineData: MineRow[] = [];
        resp.data.mines.forEach(mine => {
          mineData.push({
            mine: mine
          });
        });
        setMineTableData(mineData);
        setMinesTotal(resp.data.total);
      })
      .finally(() => {
        setIsLoading(false);
      });
  }, [pageSize, page, mineAPI, setIsLoading, searchValue, as]);

  useEffect(() => {
    load();
  }, [load]);

  const handleRowsPerPageChange = (event: any) => {
    const newRowsPerPage = parseInt(event.target.value, 10); // Get selected value
    setPageSize(newRowsPerPage);
    setPage(0)
  }

  const renderTitle = () => {
    return (
      <Grid2 container direction={"row"} spacing={1} alignContent={"center"}>
        <Typography variant="h5">
           Mines
        </Typography>
        <LibraryAdd color="primary" onClick={() => setMineDialog(true)} />
      </Grid2>
    )
  }

  const onRowClick = (data: MineRow) => {
    navigate(or(data.mine.settings?.key, ""))
  }

  const closeCallback = () => {
    setMineDialog(false);
  };

  return (
    <PageContainer padding={0}>
      <ResponsiveTable<MineRow>
        title={renderTitle}
        rows={mineTableData}
        columns={mineColumns}
        total={minesTotal}
        page={page}
        pageSize={pageSize}
        setSearchText={setSearchValue}
        setPage={setPage}
        handleRowsPerPageChange={handleRowsPerPageChange}
        hideKeys
        isLoading={isLoading}
        onRowClick={onRowClick}
        loadMore={()=>{
          let current = cloneDeep(mineTableData)
          setIsLoading(true);
          mineAPI
            .listMines(pageSize, current.length, "desc", undefined, searchValue, false, as)
            .then(resp => {
              let newMines: MineRow[] = [];
              resp.data.mines.forEach(mine => {
                newMines.push({
                  mine: mine
                });
              });
              setMineTableData(current.concat(newMines));
            })
            .finally(() => {
              setIsLoading(false);
            });
        }}
      />
      <AddMine open={mineDialog} closeCallback={closeCallback} refreshCallback={load} />
    </PageContainer>
  );
}
