import { ExpandMore } from "@mui/icons-material"
import { Accordion, AccordionDetails, AccordionSummary, Box, Theme, Typography } from "@mui/material"
import { makeStyles } from "@mui/styles"
import ResponsiveTable, { Column } from "common/ResponsiveTable"
import GrainDescriber from "grain/GrainDescriber"
import { cloneDeep } from "lodash"
import { Field, HarvestPlan } from "models"
import { useHarvestPlanAPI } from "providers"
import { useCallback, useEffect, useState } from "react"
import { getThemeType } from "theme"

interface Props {
  field: Field
  planSelected: (plan: HarvestPlan) => void
}

const useStyles = makeStyles((theme: Theme) => ({
    dark: {
      backgroundColor: getThemeType() === "light" ? "rgb(245, 245, 245)" : "rgb(50, 50, 50)",
      padding: 5
    },
    light: {
      backgroundColor: getThemeType() === "light" ? "rgb(235, 235, 235)" : "rgb(60, 60, 60)",
      padding: 5
    }
}));

export default function HarvestPlanTable(props: Props){
  const {field, planSelected} = props
  const harvestAPI = useHarvestPlanAPI()
  const [page, setPage] = useState(0)
  const [pageSize, setPageSize] = useState(10)
  const [loadedPlans, setLoadedPlans] = useState<HarvestPlan[]>([])
  const [total, setTotal] = useState(0)
  const classes = useStyles()
  
  useEffect(()=>{
    harvestAPI.listHarvestPlans(pageSize, page*pageSize, "desc", "harvestYear", field.key()).then(resp => {
      if(resp.data.harvestPlan){
        setLoadedPlans(resp.data.harvestPlan.map(hp => HarvestPlan.create(hp)))
      }
      setTotal(resp.data.total)
    })
  },[page, pageSize, field])

  const columns: Column<HarvestPlan>[] = [
    //these columns would be the ones on by default
    //field - hideable
    {
      title: "Field",
      hidden: field !== undefined,
      render: (row) => <Typography align="center">{row.field()}</Typography>
    },
    //title
    {
      title: "Plan",
      render: (row) => <Typography align="center">{row.settings.title}</Typography>
    },
    //year
    {
      title: "Year",
      render: (row) => <Typography align="center">{row.harvestYear()}</Typography>
    },
    //grain - crop_type
    {
      title: "Grain",
      render: (row) => <Typography align="center">{GrainDescriber(row.cropType()).name}</Typography>
    },
    //variant - grain_type
    {
      title: "Variant",
      render: (row) => <Typography align="center">{row.grainType()}</Typography>
    },
    //yield target
    {
      title: "Yield Target (bu)",
      render: (row) => <Typography align="right">{row.yieldTarget()}</Typography>
    },
    //actual yield
    {
      title: "Actual Yield (bu)",
      render: (row) => <Typography align="right">{row.actualYield()}</Typography>
    },
    //bushel price
    {
      title: "Bushel Price",
      render: (row) => <Typography align="right">{row.bushelPrice()}</Typography>
    },
    //material cost
    {
      title: "Material Cost",
      render: (row) => <Typography align="right">{row.totalMaterialCost()}</Typography>
    },
    //equipment cost
    {
      title: "Equipment Cost",
      render: (row) => <Typography align="right">{row.totalEquipmentCost()}</Typography>
    }
    //these columns could be optional (disabled by default but turned on later?)
    //pre-seed materials
    //pre-seed equpment
    //seed materials
    //seed equpment
    //post-seed materials
    //post-seed equpment
    //harvest materials
    //harvest equpment
    //fall materials
    //fall equpment
  ]

  return (
    <ResponsiveTable<HarvestPlan>
      columns={columns}
      title={"Harvest Plans"}
      resizeable
      page={page}
      onRowClick={(row) => {
        planSelected(row)
      }}
      pageSize={pageSize}
      rows={loadedPlans}
      total={total}
      handleRowsPerPageChange={(e)=>{
        setPageSize(e.target.value)
      }}
      setPage={(page)=>{
        setPage(page)
      }}
      loadMore={() => {
        harvestAPI.listHarvestPlans(pageSize, loadedPlans.length, "desc", "harvestYear", field.key()).then(resp => {
          let currentPlans = cloneDeep(loadedPlans)
          let newPlans: HarvestPlan[] = []
          if(resp.data.harvestPlan){
            newPlans = resp.data.harvestPlan.map(hp => HarvestPlan.create(hp))
          }
          setLoadedPlans(currentPlans.concat(newPlans))
        })
      }}
      renderMobile={(row, index) => {
        // since these are more about previous harvest plans i am only showing the final tallys rather than the breakdowns
        return (
          <Accordion>
            <AccordionSummary expandIcon={<ExpandMore />}>
              <Typography sx={{fontWeight: 650}}>
                {row.settings.title} - {row.harvestYear()}
              </Typography>
            </AccordionSummary>
            <AccordionDetails>
              {/* grain */}
              <Box className={classes.light} style={{ display: "flex", justifyContent: "space-between" }}>
                <Typography variant="subtitle1">Grain:</Typography>
                <Typography variant="subtitle1">{GrainDescriber(row.cropType()).name}</Typography>
              </Box>
              {/* variant */}
              <Box className={classes.dark} style={{ display: "flex", justifyContent: "space-between" }}>
                <Typography variant="subtitle1">Variant:</Typography>
                <Typography variant="subtitle1">{row.grainType()}</Typography>
              </Box>
              {/* yield target */}
              {/* <Box className={classes.dark} style={{ display: "flex", justifyContent: "space-between" }}>
                <Typography variant="subtitle1">Yield Target:</Typography>
                <Typography variant="subtitle1">{row.yieldTarget()}bu</Typography>
              </Box> */}
              {/* actual yield */}
              <Box className={classes.light} style={{ display: "flex", justifyContent: "space-between" }}>
                <Typography variant="subtitle1">Actual Yield:</Typography>
                <Typography variant="subtitle1">{row.actualYield()}bu</Typography>
              </Box>
              {/* bushel price */}
              <Box className={classes.dark} style={{ display: "flex", justifyContent: "space-between" }}>
                <Typography variant="subtitle1">Bushel Price:</Typography>
                <Typography variant="subtitle1">${row.bushelPrice()}</Typography>
              </Box>
              {/* material cost */}
              <Box className={classes.light} style={{ display: "flex", justifyContent: "space-between" }}>
                <Typography variant="subtitle1">Material Cost:</Typography>
                <Typography variant="subtitle1">${row.totalMaterialCost() * field.acres()}</Typography>
              </Box>
              {/* equipment cost */}
              <Box className={classes.dark} style={{ display: "flex", justifyContent: "space-between" }}>
                <Typography variant="subtitle1">Equipment Cost:</Typography>
                <Typography variant="subtitle1">${row.totalEquipmentCost() * field.acres()}</Typography>
              </Box>
              {/* pre-seed materials */}
              {/* pre-seed equpment */}
              {/* seed materials */}
              {/* seed equpment */}
              {/* post-seed materials */}
              {/* post-seed equpment */}
              {/* harvest materials */}
              {/* harvest equpment */}
              {/* fall materials */}
              {/* fall equpment */}
              {/* total cost */}
              <Box className={classes.light} style={{ display: "flex", justifyContent: "space-between" }}>
                <Typography variant="subtitle1">Total Cost:</Typography>
                <Typography variant="subtitle1">${(row.totalEquipmentCost() + row.totalMaterialCost()) * field.acres()}</Typography>
              </Box>
            </AccordionDetails>
          </Accordion>
        )
      }}
    />
  )
}