import {
    Button,
    Checkbox,
    Dialog,
    DialogActions,
    DialogContent,
    DialogContentText,
    DialogTitle,
    FormControlLabel,
    FormGroup,
    TextField,
    Typography,
  } from "@mui/material";
  import LocalizationProvider from '@mui/lab/LocalizationProvider';
  import AdapterDateFns from '@mui/lab/AdapterDateFns';
  import DateTimePicker from '@mui/lab/DateTimePicker';
  import React, { useState } from "react";
  import { useAppSelector } from "../../redux/hooks";
  import { selectFavorites } from "../../redux/slices/favoritesSlice";
  import { selectTeam, selectUsers } from "../../redux/slices/usersSlice";
  import GroupSelect from "../sidebar/GroupSelect";
  import axios from "../../api/axios";
  import useAuth from "../../hooks/useAuth";
  import DetailedMeeting from "../../api-bodies/DetailedMeeting";
  import NewMeeting from "../../api-bodies/NewMeeting";
  
  interface Props {
    open: boolean;
    handleClose: () => void;
  }
  
  const CallScheduledMeetingDialog: React.FC<Props> = ({
    open,
    handleClose,
  }: Props) => {
  
    const [meetingStartDate, setMeetingStartDate] = React.useState<Date | null>(new Date());
    const [meetingTopic, setMeetingTopic] = useState<string>("");
    const [meetingDuration, setMeetingDuration] = useState<number>(60);
    const [group, setGroup] = useState<string>("Favorites");
    const [inputText, setInputText] = useState<string>("");
    const [checkedUuids, setCheckedUuids] = useState<string[]>([]);
    const [urlDialog, seturlDialog] = useState({ open: false, url: "" });
  
    const handleCheck = (uuid: string, checked: boolean) => {
      if (checked) {
        setCheckedUuids(checkedUuids.concat([uuid]));
      } else {
        setCheckedUuids(checkedUuids.filter((id) => id != uuid));
      }
    };
  
    const handleGroupChange = () => {
      setCheckedUuids([]);
    };

    const handleDateChange = (startDate: Date | null, keyboardInputValue?: string | undefined) => {
      setMeetingStartDate(startDate);
    };
    
  
    const favoritesUuids = useAppSelector(selectFavorites);
    const teamUuids = useAppSelector(selectTeam);
  
    const groupMembersUuids: string[] =
      group === "Favorites" ? favoritesUuids : teamUuids;
    const groupMembers = useAppSelector((state) =>
      selectUsers(state, groupMembersUuids)
    );
  
    const auth = useAuth();
  
    const handleCall = async(e: React.SyntheticEvent) => {
      const start = meetingStartDate ? meetingStartDate.toISOString() : new Date().toISOString();
      let newStart = start.split('.')[0];
      newStart += start.includes("Z") ? "Z" : "";
      const newMeeting: NewMeeting ={
        startTime: newStart,
        duration: meetingDuration,
        topic: meetingTopic,
        registrantIds: checkedUuids
      };
      const response = await axios.post(
        `/users/${auth?.uuid}/meetings`,
        JSON.stringify(newMeeting)
      );
      const meeting: DetailedMeeting = response?.data;
      console.log("create meeting response: " + meeting.startTime + ":" + meeting.duration);
      seturlDialog({ open: true, url: meeting.joinUrl });
      handleClose();
    };
  
    return (
      <>
        <Dialog onClose={handleClose} open={open} fullWidth maxWidth="sm">
          <DialogTitle>Schedule A Meeting</DialogTitle>
          <DialogContent  dividers>
            <LocalizationProvider dateAdapter={AdapterDateFns}>
              <DateTimePicker
                label="Meeting Start Date&Time"
                value={meetingStartDate}
                onChange={handleDateChange}
                renderInput={(params) => <TextField {...params} />}
              />
            </LocalizationProvider>
            <TextField
              className="meetingDuration-input"
              id="outlined-number"
              label="Duration in Minutes"
              variant="outlined"
              value={meetingDuration}
              type="number"
              onChange={(event) => {
                setMeetingDuration(parseInt(event.target.value));
              }}
            />
          </DialogContent>
          <DialogContent  dividers>
            <TextField
              fullWidth
              className="meetingTopic-input"
              id="outlined-basic"
              label="Meeting Topic"
              variant="outlined"
              value={meetingTopic}
              onChange={(event) => {
                setMeetingTopic(event.target.value);
              }}
            />
          </DialogContent>
          <DialogContent>
            <GroupSelect
              group={group}
              setGroup={setGroup}
              onGroupChange={handleGroupChange}
            />
          </DialogContent>
          <DialogContent sx={{ height: "40vh" }} dividers>
            <TextField
              label="Search"
              variant="outlined"
              placeholder="Person"
              fullWidth
              sx={{ pb: 1 }}
              onChange={(e) => {
                setInputText(e.target.value);
              }}
            />
            <FormGroup>
              {groupMembers
                .filter((member) =>
                  member.name.toLowerCase().includes(inputText.toLowerCase())
                )
                .map((member) => (
                  <FormControlLabel
                    key={member.uuid}
                    label={member.name}
                    sx={{ pl: 1 }}
                    // eslint-disable-next-line @typescript-eslint/no-explicit-any
                    onChange={(e: any) => {
                      handleCheck(member.uuid, e.target.checked);
                    }}
                    control={
                      <Checkbox
                        color="success"
                        checked={checkedUuids.includes(member.uuid)}
                      />
                    }
                  />
                ))}
            </FormGroup>
          </DialogContent>
    
          <DialogActions>
            <Button color="success" onClick={handleCall}>
              <Typography variant="button" color="black">
                Call
              </Typography>
            </Button>
          </DialogActions>
        </Dialog>
        <Dialog
          open={urlDialog.open}
          onClose={() => {
            seturlDialog({ open: false, url: "" });
          }}
        >
          <DialogTitle>Join</DialogTitle>
          <DialogContent>
            <DialogContentText>{urlDialog.url}</DialogContentText>
          </DialogContent>
        </Dialog>
      </>
    );
  };
  
  export default CallScheduledMeetingDialog;