import { Box, Button, Checkbox, DialogActions, DialogContent, DialogTitle, FormControl, FormControlLabel, FormGroup, FormLabel, Grid2, Stack, Switch, TextField } from "@mui/material";
import ResponsiveDialog from "common/ResponsiveDialog";
import { cloneDeep } from "lodash";
import { pond } from "protobuf-ts/pond";
import { useFieldAPI, useSnackbar } from "providers";
import React, { useEffect, useState } from "react";
import TeamSearch from "teams/TeamSearch";

interface Props {
  open: boolean
  close: () => void
}

export default function ShareAllFields(props: Props) {
  const {open, close} = props
  const [teamShare, setTeamShare] = useState(false)
  const fieldAPI = useFieldAPI();
  const { openSnack } = useSnackbar()
  const [team, setTeam] = useState<string>("")
  const [user, setUser] = useState<string>("")
  const [sharedPermissions, setSharedPermissions] = useState<pond.Permission[]>([
    pond.Permission.PERMISSION_READ
  ])

  const share = () => {
    if(teamShare){
      //if sharing to team use shareAllByKey
      fieldAPI.shareAllByKey(team, sharedPermissions)
      .then(resp => {
        openSnack("Shared all fields to team")
      }).catch(err => {
        openSnack("There was a problem sharing the fields")
      })
    }else{
      //if sharing to user use shareAll
      fieldAPI.shareAll(user, sharedPermissions)
      .then(resp => {
        openSnack("Shared all fields to user")
      }).catch(err => {
        openSnack("There was a problem sharing the fields")
      })
    }

  }

  const target = () => {
    // toggle for whether sharing to user or team
    return (
      <React.Fragment>
        <Grid2 container alignItems="center">
          <Grid2>User</Grid2>
            <Grid2>
              <Switch
                color="default"
                value={teamShare}
                checked={teamShare}
                onChange={(_, checked) => {
                  setTeamShare(checked)
                }}
                name="storage"
              />
            </Grid2>
          <Grid2>Team</Grid2>
        </Grid2>
        {teamShare ? 
        <Box>
          <TeamSearch label="Team" setTeamCallback={(teamKey) => {setTeam(teamKey)}}/>
        </Box> :
        <Box>
          <TextField 
            label="User Email" 
            fullWidth
            value={user}
            onChange={(e) => {
              setUser(e.target.value)
            }}
          />  
        </Box>}
      </React.Fragment>
    )
    // if sharing to user have a text field
  }

  const changePermissions = (checked: boolean, permission: pond.Permission) => {
    let currentPerms = cloneDeep(sharedPermissions)
    if(checked){
      //if the permissions does not include the permission add it
      if(!sharedPermissions.includes(permission)) currentPerms.push(permission)
    }else{
      //if the permissions includes the permission remove it
      if(sharedPermissions.includes(permission)) currentPerms.splice(currentPerms.indexOf(permission), 1)
    }
    setSharedPermissions(currentPerms)
  }

  const permissions = () => {
    // the checkboxes of permissions
    return (
      <React.Fragment>
        <FormControl sx={{marginTop: 2}} component="fieldset" fullWidth variant="outlined">
          <FormLabel component="legend">Permissions</FormLabel>
          <FormGroup>
            <FormControlLabel
              control={
                <Checkbox
                disabled={sharedPermissions.includes(pond.Permission.PERMISSION_READ)}
                checked={sharedPermissions.includes(pond.Permission.PERMISSION_READ)}
                onChange={(_, checked) => {changePermissions(checked, pond.Permission.PERMISSION_READ)}}
                value={pond.Permission.PERMISSION_READ as pond.Permission}
                />
              }
              label="View"
              labelPlacement="end"
              />
            <FormControlLabel
              control={
                <Checkbox
                checked={sharedPermissions.includes(pond.Permission.PERMISSION_WRITE)}
                onChange={(_, checked) => {changePermissions(checked, pond.Permission.PERMISSION_WRITE)}}
                value={pond.Permission.PERMISSION_WRITE as pond.Permission}
                />
              }
              label="Edit"
              labelPlacement="end"
            />
            <FormControlLabel
              control={
                <Checkbox
                checked={sharedPermissions.includes(pond.Permission.PERMISSION_SHARE)}
                onChange={(_, checked) => {changePermissions(checked, pond.Permission.PERMISSION_SHARE)}}
                value={pond.Permission.PERMISSION_SHARE as pond.Permission}
                />
              }
              label="Share"
              labelPlacement="end"
            />
            <FormControlLabel
              control={
                <Checkbox
                checked={sharedPermissions.includes(pond.Permission.PERMISSION_USERS)}
                onChange={(_, checked) => {changePermissions(checked, pond.Permission.PERMISSION_USERS)}}
                value={pond.Permission.PERMISSION_USERS as pond.Permission}
                />
              }
              label="Users"
              labelPlacement="end"
            />
            <FormControlLabel
              control={
                <Checkbox
                checked={sharedPermissions.includes(pond.Permission.PERMISSION_FILE_MANAGEMENT)}
                onChange={(_, checked) => {changePermissions(checked, pond.Permission.PERMISSION_FILE_MANAGEMENT)}}
                value={pond.Permission.PERMISSION_FILE_MANAGEMENT as pond.Permission}
                />
              }
              label="Files"
              labelPlacement="end"
            />
            {/* billing */}
            <FormControlLabel
              control={
                <Checkbox
                checked={sharedPermissions.includes(pond.Permission.PERMISSION_BILLING)}
                onChange={(_, checked) => {changePermissions(checked, pond.Permission.PERMISSION_BILLING)}}
                value={pond.Permission.PERMISSION_BILLING as pond.Permission}
                />
              }
              label="Billing"
              labelPlacement="end"
            />
          </FormGroup>
        </FormControl>
      </React.Fragment>
    )
  }

  const actions = () => {
    //the buttons to shaare or cancel
    return (
      <React.Fragment>
        <Button onClick={close}>Close</Button>
        <Button onClick={share} variant="contained" color="primary">Share</Button>
      </React.Fragment>
    )
  }

  return (
    <ResponsiveDialog open={open} onClose={close}>
      <DialogTitle>Share All Fields</DialogTitle>
      <DialogContent>
        <Box minWidth={300}>
          {target()}
          {permissions()}
        </Box>
      </DialogContent>
      <DialogActions>
        {actions()}
      </DialogActions>
    </ResponsiveDialog>
  )
}