import { Gate } from "models/Gate";
import { Box, Card, IconButton, List, ListItem, ListItemText, Theme, Typography } from "@mui/material";
import React, { useCallback, useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { useMobile } from "hooks";
//import MaterialTable from "material-table";
//import { getTableIcons } from "common/ResponsiveTable";
import { Terminal } from "models/Terminal";
import { makeStyles } from "@mui/styles";
import ResponsiveTable, { Column } from "common/ResponsiveTable";
import AddGateFab from "./AddGateFab";
import GateSettings from "./GateSettings";
import { useGateAPI, useGlobalState } from "providers";
import { Settings } from "@mui/icons-material";
import { cloneDeep } from "lodash";

interface Props {
  //gates: Gate[];
  terminals: Terminal[];
  currentTerminal?: string; //the key of the terminal for the currently selected tab
  useMobile: boolean;
  //duplicateGate: (gate: Gate) => void;
}

const useStyles = makeStyles((theme: Theme) => ({
    gridListTile: {
      minHeight: "184px",
      height: "auto !important",
      width: "184px",
      padding: 2
    },
    hidden: {
      visibility: "hidden"
    },
    gateCard: {
      marginBottom: 10,
      paddingLeft: 15
    }
  }));

export default function GateList(props: Props) {
  const {terminals, currentTerminal } = props;
  const [{as}] = useGlobalState();
  // const history = useHistory();
  const navigate = useNavigate();
  const isMobile = useMobile();
  const classes = useStyles();
  const [gateDialog, setGateDialog] = useState(false);
  const [tablePage, setTablePage] = useState(0)
  const [pageSize, setPageSize] = useState(10)
  const [total, setTotal] = useState(0)
  const [terminalMap, setTerminalMap] = useState<Map<string, string>>(new Map<string, string>());
  const gateAPI = useGateAPI();
  const [gates, setGates] = useState<Gate[]>([])
  const [selectedGate, setSelectedGate] = useState<Gate | undefined>()
  const [search, setSearch] = useState("")

  const goToGate = (gate: Gate) => {
    let path = "/terminals/" + gate.key;
    navigate(path, { state: gate })
  };

  useEffect(() => {
    let map = new Map<string, string>();
    terminals.forEach(t => {
      map.set(t.key, t.name);
    });
    setTerminalMap(map);
  }, [terminals]);

  const loadGates = useCallback(() => {
    let keys = undefined
    let types = undefined
    if(currentTerminal) {
      keys = [currentTerminal]
      types = ["terminal"]
    }
    gateAPI.listGates(pageSize, pageSize * tablePage, "asc", "name", search, undefined, keys, types, undefined, undefined, as).then(resp => {
      setGates(resp.data.gates.map(gate => Gate.create(gate)))
      setTotal(resp.data.total)
    })
  },[currentTerminal, search, pageSize, tablePage, as])

  useEffect(() => {
    loadGates()
  },[loadGates])

  const handleChange = (event: any) => {
    setPageSize(event.target.value);
  };

  const desktopCols = (): Column<Gate>[] => {
    return [
      {
        title: "Gate",
        render: gate => (
          <Box padding={2}>
            <Typography>
              {gate.name}
            </Typography>
          </Box>
        )
      },
      {
        title: "Terminal",
        render: gate => (
          <Box padding={2}>
            <Typography>
            {terminalMap.get(gate.terminal())}
            </Typography>
          </Box>
        )
      },
      {
        title: "Duct Type",
        render: gate => (
          <Box padding={2}>
            <Typography>
            {gate.settings.ductName}
            </Typography>
          </Box>
        )
      },
      {
        title: "Duct Size(mm)",
        render: gate => (
          <Box padding={2}>
            <Typography>
            {gate.ductDiameter()}
            </Typography>
          </Box>
        )
      },
      {
        title: "Duct Length(m)",
        render: gate => (
          <Box padding={2}>
            <Typography>
            {gate.settings.ductLength}
            </Typography>
          </Box>
        )
      },
      {
        title: "PCA Unit",
        render: gate => (
          <Box padding={2}>
            <Typography>
            {gate.settings.pcaType}
            </Typography>
          </Box>
        )
      },
    ]
  }
  const mobileCols = (): Column<Gate>[] => {
    return [{
      title: "",
      render: gate => {
        return (
          <Box padding={2} display="flex" flexDirection="row" justifyContent="space-between">
            <Typography margin="auto" marginLeft={0} fontWeight={650} fontSize={20}>
              {gate.name}
            </Typography>
            <IconButton onClick={(event) => {
              event.stopPropagation()
              setSelectedGate(gate)
              setGateDialog(true)
            }}>
              <Settings />
            </IconButton>
          </Box>
        )
      }
    }]
  }

  const gutter = (gate: Gate) => {
    return(
      <Box>
        <Box padding={2} display="flex" flexDirection="row" justifyContent="space-between">
          <Typography>Terminal:</Typography>
          <Typography>{terminalMap.get(gate.terminal()) ?? "None"}</Typography>
        </Box>
        <Box padding={2} display="flex" flexDirection="row" justifyContent="space-between">
          <Typography>Duct Type:</Typography>
          <Typography>{gate.ductName() !== "" ? gate.ductName() : "None"}</Typography>
        </Box>
        <Box padding={2} display="flex" flexDirection="row" justifyContent="space-between">
          <Typography>Duct Size(mm):</Typography>
          <Typography>{gate.ductDiameter()}</Typography>
        </Box>
        <Box padding={2} display="flex" flexDirection="row" justifyContent="space-between">
          <Typography>DuctLength(m):</Typography>
          <Typography>{gate.ductLength()}</Typography>
        </Box>
        <Box padding={2} display="flex" flexDirection="row" justifyContent="space-between">
          <Typography>PCA Unit:</Typography>
          <Typography>{gate.settings.pcaType !== "" ? gate.settings.pcaType : "None"}</Typography>
        </Box>
      </Box>
      // <Typography variant="body2" color="textSecondary" sx={{ padding: 1 }}>

      // </Typography>
    )
  }

  const gateTable = () => {
    return (
      <ResponsiveTable<Gate>
        page={tablePage}
        pageSize={pageSize}
        columns={isMobile || props.useMobile ? mobileCols() : desktopCols()}
        handleRowsPerPageChange={handleChange}
        renderGutter={isMobile || props.useMobile ? gutter : undefined}
        gutterPadding={0}
        rows={gates}
        setPage={(page) => {setTablePage(page)}}
        total={total}
        onRowClick={(gate) => {goToGate(gate)}}
        hideKeys={isMobile || props.useMobile}
        setSearchText={(search) => setSearch(search)}
        loadMore={()=>{
          let current = cloneDeep(gates)
          let keys = undefined
          let types = undefined
          if(currentTerminal) {
            keys = [currentTerminal]
            types = ["terminal"]
          }
          gateAPI.listGates(pageSize, current.length , "asc", "name", search, undefined, keys, types, undefined, undefined, as).then(resp => {
            let newGates = resp.data.gates.map(gate => Gate.create(gate))
            setGates(current.concat(newGates))
          })
        }}
      />
    )
  };

  return <Box>
      <GateSettings
        open={gateDialog}
        gate={selectedGate}
        close={newGate => {
          if (newGate) {
            gates.push(newGate)
          }
          setGateDialog(false);
        }}
        terminals={terminals}
      />
      <AddGateFab
        onClick={() => {
          setGateDialog(true);
        }}
        pulse={gates.length < 1}
      />
      {gateTable()}
  </Box>
}
