import React, { useState, useEffect } from 'react';
import { Button, Modal, ModalHeader, ModalBody, ModalFooter, Form } from 'reactstrap';
import JKModalDialog from '../common/JKModalDialog';
import JKFriendsAutoComplete from '../people/JKFriendsAutoComplete';
import JKSessionInviteesChips from '../people/JKSessionInviteesChips';
import { useTranslation } from 'react-i18next';


//TODO: show already invited friends as chips and prevent re-inviting them
const JKSessionInviteModal = ({ currentSession, show, onToggle, friends, initialInvitees = [], onSubmit, loading, size }) => {
  const { t } = useTranslation();
  const [availableFriends, setAvailableFriends] = useState([]);
  const [invitees, setInvitees] = useState([]);

  useEffect(() => {
    const filteredFriends = friends.filter(f => !initialInvitees.some(i => i.id === f.id));
    setAvailableFriends(filteredFriends);
    setInvitees(initialInvitees);
  }, [friends, initialInvitees, show]);

  const handleOnSelect = submittedItems => {
    updateSessionInvitations(submittedItems);
  };

  const updateSessionInvitations = submittedInvitees => {
    const updatedInvitees = Array.from(new Set([...invitees, ...submittedInvitees]));
    setInvitees(updatedInvitees);

    const friendIds = submittedInvitees.map(si => si.id);
    const updatedFriends = availableFriends.filter(f => !friendIds.includes(f.id));
    setAvailableFriends(updatedFriends);
  };

  const removeInvitee = invitee => {
    const updatedInvitees = invitees.filter(i => i.id !== invitee.id);
    setInvitees(updatedInvitees);
    const updatedFriends = [...availableFriends, invitee];
    setAvailableFriends(updatedFriends);
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    onSubmit(invitees);
    onToggle();
  };

  return (
    <Modal isOpen={show} toggle={onToggle} modalClassName="theme-modal" contentClassName="border" size={size}>
      <Form onSubmit={handleSubmit}>
        <ModalHeader toggle={onToggle} className="bg-light d-flex flex-between-center border-bottom-0">
          Invite to Session
        </ModalHeader>
        <ModalBody>
          <JKFriendsAutoComplete friends={availableFriends} onSelect={handleOnSelect} />
          {invitees.length > 0 && <JKSessionInviteesChips invitees={invitees} removeInvitee={removeInvitee} />}
        </ModalBody>
        <ModalFooter>
          <Button color="secondary" onClick={onToggle} disabled={loading}>
            Cancel
          </Button>
          <Button color="primary" type="submit" disabled={loading}>
            {loading ? 'Sending...' : 'Send'}
          </Button>
        </ModalFooter>
      </Form>
    </Modal>
  );

};

export default JKSessionInviteModal;
