import {
  Box,
  Button,
  Paper,
  Tab,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Tabs
} from "@mui/material";
import React, { useCallback, useEffect, useState } from "react";
import { useMobile, useSnackbar } from "hooks";
import { useGlobalState, useFieldAPI } from "providers";
//import HarvestTable from "harvestPlan/HarvestTable";
import { Field } from "models";
import GrainDescriber from "grain/GrainDescriber";
import { pond } from "protobuf-ts/pond";
import HarvestSettings from "harvestPlan/HarvestSettings";

interface TabPanelProps {
  children?: React.ReactNode;
  index: any;
  value: any;
}

function TabPanelMine(props: TabPanelProps) {
  const { children, value, index, ...other } = props;

  return (
    <div
      role="tabpanel"
      hidden={value !== index}
      aria-labelledby={`simple-tab-${index}`}
      style={{ height: "94%" }}
      {...other}>
      {value === index && <React.Fragment>{children}</React.Fragment>}
    </div>
  );
}

export default function FieldList() {
  const [{ as }] = useGlobalState();
  const isMobile = useMobile();
  const fieldAPI = useFieldAPI();
  const { openSnack } = useSnackbar();
  const [fields, setFields] = useState<Field[]>([]);
  const [value, setValue] = React.useState(0);
  const [openHarvestSettings, setOpenHarvestSettings] = useState(false);
  const [fieldForPlan, setFieldForPlan] = useState(Field.create());

  const handleChange = (event: React.ChangeEvent<{}>, newValue: number) => {
    setValue(newValue);
  };

  const loadFields = useCallback(() => {
    fieldAPI
      .listFields(500, 0, "asc", "fieldName", undefined, as)
      .then(resp => {
        setFields(resp.data.fields.map(f => Field.any(f)));
        // resp.data.fields.forEach(f => {
        //   if (f.settings) {
        //     fieldAPI.updateField(f.settings.key, f.settings);
        //   }
        // });
      })
      .catch(err => {
        openSnack("Failed to load Field Mapping");
      });
  }, [fieldAPI, as, openSnack]);

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

  const calcTotalAcres = () => {
    let totalAcres = 0;
    fields.forEach(field => {
      totalAcres += field.acres();
    });
    totalAcres = Math.round(totalAcres);
    return totalAcres;
  };

  const listFieldsInfo = fields.map((field, index) => (
    <TableRow key={index}>
      <TableCell>{field.fieldName()}</TableCell>
      <TableCell>{field.landLoc()}</TableCell>
      <TableCell>
        {field.crop() === pond.Grain.GRAIN_CUSTOM
          ? field.customType()
          : GrainDescriber(field.crop()).name}
      </TableCell>
      <TableCell>{field.calculateAcres()}</TableCell>
      <TableCell>
        {field.permissions.includes(pond.Permission.PERMISSION_WRITE) && (
          <Button
            variant="contained"
            color="primary"
            onClick={() => {
              setFieldForPlan(field);
              setOpenHarvestSettings(true);
            }}>
            New Crop Plan
          </Button>
        )}
      </TableCell>
    </TableRow>
  ));

  return (
    <Box>
      <Tabs
        value={value}
        onChange={handleChange}
        TabIndicatorProps={{ style: { background: "rgba(255,255,0,255)" } }}>
        <Tab label="Field Overview" />
        {/* {!isMobile && <Tab label="Current Harvest Plans" />}
        {!isMobile && <Tab label="Plan History" />} */}
      </Tabs>
      <TabPanelMine index={0} value={value}>
        <TableContainer component={Paper}>
          <Table style={{ minWidth: 1000 }}>
            <TableHead>
              <TableRow>
                <TableCell>Field Name</TableCell>
                <TableCell>Land Location</TableCell>
                <TableCell>Main Crop Type</TableCell>
                <TableCell>Acres ({calcTotalAcres()} Total)</TableCell>
                <TableCell>Create New Plan</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>{listFieldsInfo}</TableBody>
          </Table>
        </TableContainer>
      </TabPanelMine>
      {/* need to re-factor the harvest table file before restoring these functions */}
      {/* <TabPanelMine index={1} value={value}>
        <HarvestTable fields={fields} display="current" />
      </TabPanelMine>
      <TabPanelMine index={2} value={value}>
        <HarvestTable fields={fields} display="history" />
      </TabPanelMine> */}
      <HarvestSettings
        open={openHarvestSettings}
        close={() => setOpenHarvestSettings(false)}
        field={fieldForPlan}
      />
    </Box>
  );
}