import { type FC, Suspense, useState } from 'react';

import HuSpinner from '@material-hu/components/design-system/ProgressIndicators/Spinner';

import { lazyRetry } from 'src/utils/lazyRetry';

const NewPeopleDialog = lazyRetry(
  () => import('src/components/dashboard/invitePeople/NewPeopleDialog'),
);
const FeedbackInvitations = lazyRetry(
  () => import('src/components/dashboard/invitePeople/FeedbackInvitations'),
);

type AddPeopleDialogProps = {
  open: boolean;
  onOpenChange: (nextOpen: boolean) => void;
};

export const AddPeopleDialog: FC<AddPeopleDialogProps> = ({
  open,
  onOpenChange,
}) => {
  const [openFeedbackInvitationDialog, setOpenFeedbackInvitationDialog] =
    useState(false);
  const [invitationsEmails, setInvitationsEmails] = useState<string[]>([]);

  const handleAddInvitations = (emailsArray: string[]) => {
    setInvitationsEmails(emailsArray);
    onOpenChange(false);
    setOpenFeedbackInvitationDialog(true);
  };
  const handleOnCloseNewPeopleDialog = () => {
    onOpenChange(false);
  };

  const handleOnCloseFeedbackInvitationDialog = () => {
    setOpenFeedbackInvitationDialog(false);
  };

  const handleInviteMorePeople = () => {
    setOpenFeedbackInvitationDialog(false);
    onOpenChange(true);
  };

  return (
    <>
      {open && (
        <Suspense fallback={<HuSpinner />}>
          <NewPeopleDialog
            open={open}
            handleClose={handleOnCloseNewPeopleDialog}
            handleAddInvitations={handleAddInvitations}
          />
        </Suspense>
      )}
      {openFeedbackInvitationDialog && (
        <Suspense fallback={<HuSpinner />}>
          <FeedbackInvitations
            open={openFeedbackInvitationDialog}
            handleClose={handleOnCloseFeedbackInvitationDialog}
            handleInviteMorePeople={handleInviteMorePeople}
            invitationsEmails={invitationsEmails}
          />
        </Suspense>
      )}
    </>
  );
};

export default AddPeopleDialog;
