import React from 'react';
import PropTypes from 'prop-types';
import {
  Divider,
  Text,
  QuestionIcon,
  IconArrowPopover,
  LoadingAnimation,
  Link,
  Button,
  Popover,
} from '@bufferapp/components';

import {
  ScheduleTable,
  EmptyState,
} from '@bufferapp/publish-shared-components';

import PostingTimeForm from '../PostingTimeForm';
import TimezoneInputForm from '../TimezoneInputForm';
import debounce from '../../utils/debounce';
import ConfirmClear from '../ConfirmClear';

const headerStyle = {
  marginBottom: '0.5rem',
  width: '100%',
};

const timezoneStyle = {
  marginTop: '1rem',
  marginBottom: '1.5rem',
  width: '100%',
};

const sectionStyle = {
  marginTop: '1.5rem',
  marginBottom: '1.5rem',
  width: '100%',
};

const postingTimesSection = {
  display: 'flex',
  flexDirection: 'row',
  justifyContent: 'flex-end',
  flexWrap: 'wrap',
  marginTop: '1.5rem',
  marginBottom: '1.5rem',
}

const postingTimesStyle = {
  margin: '0 auto 0 0',
};

const loadingContainerStyle = {
  width: '100%',
  height: '100%',
  textAlign: 'center',
  paddingTop: '5rem',
};

const scheduleLoadingContainerStyle = {
  textAlign: 'center',
};

const pauseQueueContainerStyle = {
  marginBottom: '3rem',
};

const pauseButtonContainerStyle = {
  margin: '1rem 0 .25rem',
};

const tableStyle = {
  flexBasis: '100%',
}

/* eslint no-console: 0 */
const ProfileSettings = ({
  days,
  items,
  loading,
  scheduleLoading,
  onUpdateTime,
  onAddPostingTime,
  onUpdateTimezone,
  onGetTimezones,
  settingsHeader,
  hasTwentyFourHourTimeFormat,
  onRemoveTimeClick,
  onTimezoneInputFocus,
  onTimezoneInputBlur,
  onPauseToggleClick,
  paused,
  onPauseClick,
  onUnpauseClick,
  showClearAllModal,
  onClearAllClick,
  profileName,
  profileType,
  onConfirmClearClick,
  onCancelClearClick,
  closePopover,
  avatar,
  profileService,
}) => {
  if (loading) {
    return (
      <div style={loadingContainerStyle}>
        <LoadingAnimation />
      </div>
    );
  }
  const emptySchedule = days.filter(day => day.postingTimesTotal > 0).length < 1;
  // TODO: is this the right place?
  if (items.length > 0) {
    items.forEach(item =>
      item.label = item.city,
    );
  }

  const debouncedOnChange = debounce(onGetTimezones, 500);
  return (
    <div>
      <div style={headerStyle}>
        <Text color="black">{settingsHeader}</Text>
      </div>
      <Divider />
      <div style={timezoneStyle}>
        <TimezoneInputForm
          handleSubmit={({ city, timezone }) => onUpdateTimezone({ city, timezone })}
          items={items}
          onTimezoneChange={debouncedOnChange}
          onTimezoneInputFocus={onTimezoneInputFocus}
          onTimezoneInputBlur={onTimezoneInputBlur}
        />
      </div>
      <Divider />
      <div style={sectionStyle}>
        <PostingTimeForm
          onSubmit={({ day, time }) => {
            time.hours = time.hours < 10 ? `0${time.hours}` : time.hours;
            time.minutes = time.minutes < 10 ? `0${time.minutes}` : time.minutes;
            onAddPostingTime({
              day,
              time,
            });
          }}
          twentyfourHourTime={hasTwentyFourHourTimeFormat}
        />
      </div>
      <Divider />
      <div style={postingTimesSection}>
        <div style={postingTimesStyle}>
          <Text
            color="black"
            weight="thin"
            size="small"
          >
            Posting times
            {/* Need to move the tooltip a bit for visual accuracy! */}
            <div style={{ display: 'inline-block', position: 'relative', top: '4px', left: '5px' }}>
              <IconArrowPopover icon={<QuestionIcon />} position="below" shadow oneLine={false} width="320px" label="Posting Times">
                <div style={{ padding: '.5rem .25rem' }}>
                  {/* eslint-disable max-len */}
                  Your posting schedule tells Buffer when to send out posts in your Queue. <br /><br />
                  For example, the next 10 posts you add to your Queue will go out in the next 10 upcoming time/date slots you
                  decide below. You can change this schedule at any time!
                </div>
              </IconArrowPopover>
            </div>
          </Text>
        </div>
        {!emptySchedule &&
            <Button secondary onClick={onClearAllClick}>
              Clear all Posting Times
            </Button>}
        <Popover
          hidden={!showClearAllModal}
          onOverlayClick={closePopover}
        >
          <ConfirmClear
            onConfirmClick={onConfirmClearClick}
            onCancelClick={onCancelClearClick}
            profileName={profileName}
            profileType={profileType}
            profileService={profileService}
            onCloseClick={closePopover}
            avatar={avatar}
          />
        </Popover>
        <div style={tableStyle}>
          <Divider color="white" />
          {scheduleLoading &&
            <div style={scheduleLoadingContainerStyle}>
              <LoadingAnimation />
            </div>}
          {!scheduleLoading && emptySchedule &&
            <EmptyState
              title="Looks like you don't have any posting times set!"
              subtitle="Add a new posting time to start publishing posts from your queue."
              heroImg="https://s3.amazonaws.com/buffer-publish/images/clock2x.png"
              heroImgSize={{ width: '40px', height: '40px' }}
              height={'30vh'}
            />}
          {!emptySchedule &&
            <ScheduleTable
              days={days}
              select24Hours={hasTwentyFourHourTimeFormat}
              onRemoveTimeClick={onRemoveTimeClick}
              onUpdateTime={onUpdateTime}
              onPauseToggleClick={onPauseToggleClick}
            />}
        </div>
      </div>
      <div style={headerStyle}>
        <Text color="black">Pause Queue</Text>
      </div>
      <Divider />
      {paused
        ? <div style={pauseQueueContainerStyle}>
          <Text size="mini">
            <b>Your queue is currently paused.</b>&nbsp;
          </Text>
          <div style={pauseButtonContainerStyle}>
            <Button
              onClick={onUnpauseClick}
            >
              Resume Queue
            </Button>
          </div>
          <Text size="small">
            <Link newTab href="https://faq.buffer.com/article/681-how-to-pause-your-queue">
              How does this work?
            </Link>.
          </Text>
        </div>
        : <div style={pauseQueueContainerStyle}>
          <Text size="mini">
            Pausing your queue prevents all posts from being sent until you resume it.&nbsp;
          </Text>
          <div style={pauseButtonContainerStyle}>
            <Button
              onClick={onPauseClick}
            >
              Pause Queue
            </Button>
          </div>
          <Text size="small">
            <Link newTab href="https://faq.buffer.com/article/681-how-to-pause-your-queue">
              How does this work?
            </Link>.
          </Text>
        </div>
      }
    </div>
  );
};

ProfileSettings.propTypes = {
  days: PropTypes.arrayOf(
    PropTypes.shape({
      dayName: PropTypes.string,
      postingTimesTotal: PropTypes.number,
      times: PropTypes.arrayOf(
        PropTypes.shape({
          value: PropTypes.oneOfType([
            PropTypes.shape({
              hours: PropTypes.number.isRequired,
              minutes: PropTypes.number.isRequired,
            }),
            PropTypes.string,
          ]),
        }).isRequired,
      ).isRequired,
    }),
  ).isRequired,
  hasTwentyFourHourTimeFormat: PropTypes.bool.isRequired,
  items: PropTypes.arrayOf(PropTypes.shape({
    label: PropTypes.string.isRequired,
  })).isRequired,
  loading: PropTypes.bool.isRequired,
  scheduleLoading: PropTypes.bool.isRequired,
  settingsHeader: PropTypes.string.isRequired,
  onRemoveTimeClick: PropTypes.func.isRequired,
  onUpdateTime: PropTypes.func.isRequired,
  onAddPostingTime: PropTypes.func.isRequired,
  onUpdateTimezone: PropTypes.func.isRequired,
  onGetTimezones: PropTypes.func.isRequired,
  onTimezoneInputFocus: PropTypes.func.isRequired,
  onTimezoneInputBlur: PropTypes.func.isRequired,
  onPauseToggleClick: PropTypes.func.isRequired,
  paused: PropTypes.bool.isRequired,
  onPauseClick: PropTypes.func.isRequired,
  onUnpauseClick: PropTypes.func.isRequired,
  onClearAllClick: PropTypes.func.isRequired,
  showClearAllModal: PropTypes.bool.isRequired,
  profileName: PropTypes.string.isRequired,
  profileType: PropTypes.string.isRequired,
  onCancelClearClick: PropTypes.func.isRequired,
  onConfirmClearClick: PropTypes.func.isRequired,
  closePopover: PropTypes.func,
  avatar: PropTypes.string,
  profileService: PropTypes.string.isRequired,
};

ProfileSettings.defaultProps = {
  loading: false,
};

export default ProfileSettings;
