import {
  Button,
  DialogActions,
  DialogContent,
  DialogTitle,
  MenuItem,
  TextField
} from "@mui/material";
import ResponsiveDialog from "common/ResponsiveDialog";
import { Option } from "common/SearchSelect";
import { Field, HarvestPlan, Task } from "models";
import moment from "moment";
import { pond } from "protobuf-ts/pond";
import { useFieldAPI, useGlobalState, useHarvestPlanAPI, useTaskAPI } from "providers";
import { useCallback, useEffect, useState } from "react";

interface Props {
  open: boolean;
  close: () => void;
  fields?: Field[];
  plan: HarvestPlan;
}

export default function DuplicateHarvestPlan(props: Props) {
  const { open, close, fields, plan } = props;
  const [{as}] = useGlobalState();
  const [newFieldIndex, setNewFieldIndex] = useState(0);
  const [planTasks, setPlanTasks] = useState<Task[]>([]);
  const [title, setTitle] = useState("");
  const harvestPlanAPI = useHarvestPlanAPI();
  const taskAPI = useTaskAPI();
  const [ready, setReady] = useState(false);
  const [fieldOptions, setFieldOptions] = useState<Field[]>([])
  const fieldAPI = useFieldAPI();

  const loadTasks = useCallback(() => {
    taskAPI.listTasks(50, 0, "asc", "start", plan.key(), undefined).then(resp => {
      if(resp.data.tasks){
        setPlanTasks(resp.data.tasks.map(t => Task.any(t)));
      }
      setReady(true);
    });
  }, [taskAPI, plan]);

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

  useEffect(()=>{
    if(fields){
      //if fields were passed in use those
      setFieldOptions(fields)
    }else{
      //otherwise load them
      fieldAPI.listFields(50, 0, "asc", "fieldName").then(resp => {
        setFieldOptions(resp.data.fields.map(f => Field.create(f)))
      }).catch(err => {
        
      })
    }
  },[fields])

  //this should load the fields here

  const duplicate = () => {
    let planSettings = HarvestPlan.clone(plan).settings;
    planSettings.field = fieldOptions[newFieldIndex].key();
    planSettings.createDate = moment.now();
    if (title !== "") {
      planSettings.title = title;
    }
    harvestPlanAPI.addHarvestPlan(planSettings, as).then(resp => {
      let tasks = planTasks;
      tasks.forEach(task => {
        task.settings.objectKey = resp.data.harvestPlan;
        taskAPI.addTask(task.settings, as);
      });
    });
    close();
  };
  return (
    <ResponsiveDialog open={open} onClose={close}>
      <DialogTitle>Duplicate Crop Plan</DialogTitle>
      <DialogContent>
        <TextField
          margin="normal"
          fullWidth
          select
          label="Field"
          value={newFieldIndex}
          onChange={e => setNewFieldIndex(+e.target.value)}
          color="primary">
          {fieldOptions.map((option, i) => (
            <MenuItem key={option.key()} value={i}>
              {option.fieldName()}
            </MenuItem>
          ))}
        </TextField>
        <TextField
          fullWidth
          margin="normal"
          type="text"
          label="Title"
          value={title}
          helperText={"Leave blank to use the same title*"}
          onChange={e => setTitle(e.target.value)}
        />
      </DialogContent>
      <DialogActions>
        <Button
          onClick={close}
          variant="contained"
          style={{ color: "black", backgroundColor: "red" }}>
          Cancel
        </Button>
        <Button
          onClick={duplicate}
          variant="contained"
          color="primary"
          disabled={
            !ready ||
            (fieldOptions[newFieldIndex] &&
              !fieldOptions[newFieldIndex].permissions.includes(pond.Permission.PERMISSION_WRITE))
          }>
          Duplicate
        </Button>
      </DialogActions>
    </ResponsiveDialog>
  );
}
