import React, { useRef, useState, useEffect } from 'react';
import { useHistory } from 'react-router-dom';
import { Form, FormGroup, Input, Label, Card, CardBody, Button, Row, Col } from 'reactstrap';
import FalconCardHeader from '../common/FalconCardHeader';
import JKTooltip from '../common/JKTooltip';
import { useTranslation } from 'react-i18next';
import { useAuth } from '../../context/UserAuth';
import JKFriendsAutoComplete from '../people/JKFriendsAutoComplete';
import JKSessionInviteesChips from '../people/JKSessionInviteesChips';
import { getFriends, createSession, getGenres } from '../../helpers/rest';
import JKModalDialog from '../common/JKModalDialog';
import useNativeAppCheck from '../../hooks/useNativeAppCheck';
import { useNativeApp } from '../../context/NativeAppContext';
import { useResponsive } from '@farfetch/react-context-responsive';
import { SESSION_PRIVACY_MAP } from '../../helpers/globals';
import JKAppLaunch from './JKAppLaunch';
import { formatUtcTime } from '../../helpers/utils';

const JKNewMusicSession = () => {
  const { currentUser } = useAuth();
  const { t } = useTranslation();
  const [friends, setFriends] = useState([]);
  const [genres, setGenres] = useState([]);
  const [isFriendsFetched, setIsFriendsFetched] = useState(false);
  const [description, setDescription] = useState('');
  const [invitees, setInvitees] = useState([]);
  const [privacy, setPrivacy] = useState('1');
  const [submitted, setSubmitted] = useState(false);
  const [showAppLauncher, setShowAppLauncher] = useState(false);
  const [customQueryString, setCustomQueryString] = useState(null);
  const history = useHistory();
  const formRef = useRef();
  const isNativeAppAvailable = useNativeAppCheck();
  const { nativeAppUnavailable, setNativeAppUnavailable } = useNativeApp();
  const { greaterThan } = useResponsive();
  const NATIVE_APP_ON_SUBMIT = false;

  useEffect(() => {
    fetchFriends();
    fetchGenres();
  }, []);

  useEffect(() => {
    if (isFriendsFetched) {
      populateFormDataFromLocalStorage();
    }
  }, [isFriendsFetched]);

  const fetchFriends = () => {
    getFriends(currentUser.id)
      .then(resp => {
        if (resp.ok) {
          return resp.json();
        }
      })
      .then(data => {
        setFriends(data);
        setIsFriendsFetched(true);
      });
  };

  const fetchGenres = () => {
    getGenres()
      .then(resp => {
        if (resp.ok) {
          return resp.json();
        }
      })
      .then(data => {
        setGenres(data)
      });
  }

  const populateFormDataFromLocalStorage = () => {
    try {
      const formData = localStorage.getItem('formData');
      if (formData) {
        const formDataItems = JSON.parse(formData);
        setDescription(formDataItems['description']);
        setPrivacy(formDataItems['privacy']);
        const inviteeIds = formDataItems['inviteeIds'];
        const invitees = friends.filter(f => inviteeIds.includes(f.id));
        updateSessionInvitations(invitees);
      }
    } catch (error) {
      console.error('localStorage is not available', error);
    }
  };

  const handleSubmit = async event => {
    event.preventDefault();
    setSubmitted(true);
    const formData = new FormData(event.target);
    const inviteeIds = invitees.map(i => i.id)
    const payload = {
      privacy: formData.get('privacy'),
      description: formData.get('description'),
      inviteeIds: inviteeIds.join()
    };
    try {
      //store this payload in localstorage.
      localStorage.setItem('formData', JSON.stringify(payload));
    } catch (error) {
      console.error('localStorage is not available', error);
    }

    if (NATIVE_APP_ON_SUBMIT) {
      try {
        //check if jamkazam app is installed
        await isNativeAppAvailable();

        const q = `privacy~${payload.privacy}|description~${payload.description}|inviteeIds~${payload.inviteeIds}`;
        setCustomQueryString(`act=createSession&p=${q}`);
      } catch (error) {
        toggleAppUnavilableModel();
        setSubmitted(false);
        return
      }
    } else {

      switch (parseInt(payload.privacy)) {
        case SESSION_PRIVACY_MAP['public']:
          payload.musician_access = true;
          payload.approval_required = false;
          break;
        case SESSION_PRIVACY_MAP['private_approve']:
          payload.musician_access = true;
          payload.approval_required = true;
          break;
        case SESSION_PRIVACY_MAP['private_invite']:
          payload.musician_access = false;
          payload.approval_required = false;
          break;
        default:
          break;
      }

      payload.legal_terms = true;
      payload.start = new Date().toDateString() + ' ' + formatUtcTime(new Date(), false);
      payload.duration = "60";

      payload.invitations = inviteeIds;
      payload.timezone = 'Central Time (US & Canada),America/Chicago';
      if (genres.length) {
        payload.genres = [genres[0]['id']]
      }
      payload.friends_can_join = true;
      payload.is_unstructured_rsvp = false;
      payload.fan_chat = false;
      payload.fan_access = false;
      payload.legal_policy = 'legal_policy' //TODO: hard coded. need valid value?
      payload.language = 'eng' //TODO: hard coded. need valid value?
      payload.name = 'my session'//TODO: hard coded. name field is no longer been used in the form. therefore this is a dummy name for now.
      payload.rsvp_slots = [{ instrument_id: 'other', proficiency_level: 3, approve: true }] //TODO: hardcoded for now

      console.log("_DEBUG_ payload", payload)

      try {
        const response = await createSession(payload);
        if (!response.ok) {
          throw new Error(`Error occured while creating session`);
        }
        const session = await response.json()
        if (session) {
          history.push(`/client/s/${session.id}`);
        }
      } catch (error) {

      } finally {
        setSubmitted(false)
      }
    }

    return false;
  };

  useEffect(() => {
    if (customQueryString) {
      setShowAppLauncher(true);
    }
  }, [customQueryString]);

  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 = friends.filter(f => !friendIds.includes(f.id));
    setFriends(updatedFriends);
  };

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

  const toggleAppUnavilableModel = () => {
    setNativeAppUnavailable(prev => !prev);
    if (!nativeAppUnavailable) {
      setSubmitted(false);
    }
  };

  const toggleAppLauncher = () => {
    setShowAppLauncher(prev => !prev);
  }

  return (
    <div>
      <Card>
        <FalconCardHeader title={t('new.page_title', { ns: 'sessions' })} titleClass="font-weight-bold" />
        <CardBody className="pt-0">
          <Row>
            <Col>
              <Form onSubmit={handleSubmit} ref={formRef}>
                <FormGroup className="mb-3">
                  <Label>
                    {t('new.privacy', { ns: 'sessions' })}{' '}
                    <JKTooltip title={t('new.privacy_help', { ns: 'sessions' })} />
                  </Label>
                  <Input
                    type="select"
                    aria-label="Session Privacy"
                    name="privacy"
                    value={privacy}
                    onChange={e => setPrivacy(e.target.value)}
                    data-testid="session-privacy"
                  >
                    <option value={SESSION_PRIVACY_MAP['public']}>{t('new.privacy_opt_public', { ns: 'sessions' })}</option>
                    <option value={SESSION_PRIVACY_MAP['private_invite']}>
                      {t('new.privacy_opt_private_invite', { ns: 'sessions' })}
                    </option>
                    <option value={SESSION_PRIVACY_MAP['private_approve']}>
                      {t('new.privacy_opt_private_approve', { ns: 'sessions' })}
                    </option>
                  </Input>
                </FormGroup>

                <FormGroup className="mb-3">
                  <Label>
                    {t('new.invitations', { ns: 'sessions' })}{' '}
                    <JKTooltip title={t('new.invitations_help', { ns: 'sessions' })} />
                  </Label>
                  <JKFriendsAutoComplete friends={friends} onSelect={handleOnSelect} />
                  {invitees.length > 0 && <JKSessionInviteesChips invitees={invitees} removeInvitee={removeInvitee} />}
                </FormGroup>
                <FormGroup className="mb-3">
                  <Label>
                    {t('new.description', { ns: 'sessions' })}{' '}
                    <JKTooltip title={t('new.description_help', { ns: 'sessions' })} />
                  </Label>
                  <Input
                    value={description}
                    onChange={e => setDescription(e.target.value)}
                    name="description"
                    type="textarea"
                    data-testid="session-description"
                    placeholder={t('new.description_placeholder', { ns: 'sessions' })}
                  />
                </FormGroup>

                <FormGroup className="mb-3">
                  <Button color="primary" data-testid="btn-create-session" disabled={submitted}>
                    {t('new.create_session', { ns: 'sessions' })}
                  </Button>
                </FormGroup>
              </Form>
            </Col>
            {greaterThan.lg && (
              <Col />
            )}
          </Row>
        </CardBody>
      </Card>
      <JKModalDialog
        show={nativeAppUnavailable}
        onToggle={toggleAppUnavilableModel}
        title={t('modals.native_app_unavailable.title', { ns: 'common' })}
      >
        <p>{t('modals.native_app_unavailable.body', { ns: 'common' })}</p>
        <div className="d-flex flex-row">
          <a
            href="https://www.jamkazam.com/public/downloads"
            onClick={() => toggleAppUnavilableModel()}
            target="_blank"
            className="btn btn-primary mr-2"
          >
            {t('modals.native_app_unavailable.download_button', { ns: 'common' })}
          </a>
          <a
            href="https://www.jamkazam.com/help_desk"
            onClick={() => toggleAppUnavilableModel()}
            target="_blank"
            className="btn btn-light"
          >
            {t('modals.native_app_unavailable.help_button', { ns: 'common' })}
          </a>
        </div>
      </JKModalDialog>
      <JKModalDialog
        show={showAppLauncher}
        onToggle={toggleAppLauncher}
        title={t('new.page_title', { ns: 'sessions' })}
      >
        <JKAppLaunch customQueryString={customQueryString} toggle={toggleAppLauncher} />
      </JKModalDialog>
    </div>
  );
};

export default JKNewMusicSession;
