import React, { useState, useEffect, ChangeEvent } from 'react';
import classNames from 'classnames/bind';

import { OpportunityExpectedOutcome } from 'typings';

import SVGArrow from 'assets/svg/arrow.svg';
import SVGArrowLeft from 'assets/svg/arrow-left.svg';

import s from './Opportunity.module.scss';

const cn = classNames.bind(s);

interface IOpportunityProps {
  id: string;
  title: string;
  description?: string;
  reference?: string;
  expectedOutcome: OpportunityExpectedOutcome;
  color: string;
  callToAction: string;
  onExpectedOutcomeClick(id: string, expectedOutcome: OpportunityExpectedOutcome): any;
  onInvalidatedClick(id: string, note: string): any;
  onViewOpportunity(id: string): any;
  onCloseOpportunity: any;
}

const Opportunity = ({
  id,
  title,
  description,
  reference,
  expectedOutcome,
  color,
  callToAction,
  onExpectedOutcomeClick,
  onInvalidatedClick,
  onViewOpportunity,
  onCloseOpportunity,
}: IOpportunityProps) => {
  const [invalidatedNote, setInvalidatedNote] = useState('');
  const [isInvalidatedOpen, setIsInvalidatedOpen] = useState(false);
  const [showInvalidatedError, setShowInvalidatedError] = useState(false);
  const [loadingInvalidatedButton, setLoadingInvalidatedButton] = useState(false);

  useEffect(() => {
    onViewOpportunity(id);
  });

  const handleChange = (e: ChangeEvent<HTMLTextAreaElement>) => {
    setInvalidatedNote(e.target.value);

    if (e.target.value !== '') {
      setShowInvalidatedError(false);
    }
  };

  const onStatusClick = (id: string, expectedOutcome: OpportunityExpectedOutcome) => {
    onExpectedOutcomeClick(id, expectedOutcome);

    if (
      callToAction &&
      OpportunityExpectedOutcome[expectedOutcome] ===
        OpportunityExpectedOutcome[OpportunityExpectedOutcome.Success]
    ) {
      window.open(callToAction);
    }
  };

  const onInvalidatedButtonClick = () => {
    setIsInvalidatedOpen(!isInvalidatedOpen);
  };

  const onInvalidatedSubmit = (id: string) => {
    if (invalidatedNote === '') {
      setShowInvalidatedError(true);
      return false;
    }

    onInvalidatedClick(id, invalidatedNote);

    setLoadingInvalidatedButton(true);

    setTimeout(() => {
      setShowInvalidatedError(false);
      setIsInvalidatedOpen(false);
    }, 2000);
  };

  const onInvalidatedClose = () => {
    setIsInvalidatedOpen(false);
    setShowInvalidatedError(false);
  };

  const oneSelected =
    OpportunityExpectedOutcome[expectedOutcome] !== OpportunityExpectedOutcome.Unknown;

  return (
    <div className={s.opportunity}>
      <div className={s.opportunity__header}>
        <h2 className={cn(s.opportunity__subtitle, 'arrow')}>Af hverju ég?</h2>
        <div className={s.opportunity__title}>{title}</div>
        {description && <div className={s.opportunity__description}>{description}</div>}
      </div>

      {reference && <div className={s.opportunity__reference}>Vegna: {reference}</div>}

      {!isInvalidatedOpen && (
        <div className={s.opportunity__status}>
          <h2 className={cn(s.opportunity__subtitle, 'arrow')}>Hvernig er tilfinningin?</h2>
          <div className={s.opportunity__statusList}>
            <button
              type="button"
              className={cn(s.opportunity__statusItem, {
                selected:
                  OpportunityExpectedOutcome[expectedOutcome] ===
                  OpportunityExpectedOutcome.Success,
                oneSelected,
              })}
              onClick={() => onStatusClick(id, OpportunityExpectedOutcome.Success)}
            >
              <div className={s.opportunity__statusEmoji}>
                <img
                  src={require('assets/images/emojis/success.png').default.src}
                  alt="Customer is happy"
                />
              </div>
              <div className={s.opportunity__statuslabel}>Selt</div>
            </button>
            <button
              type="button"
              className={cn(s.opportunity__statusItem, {
                selected:
                  OpportunityExpectedOutcome[expectedOutcome] === OpportunityExpectedOutcome.Mixed,
                oneSelected,
              })}
              onClick={() => onStatusClick(id, OpportunityExpectedOutcome.Mixed)}
            >
              <div className={s.opportunity__statusEmoji}>
                <img
                  src={require('assets/images/emojis/mixed.png').default.src}
                  alt="Customer is nutral"
                />
              </div>
              <div className={s.opportunity__statuslabel}>Heitur</div>
            </button>
            <button
              type="button"
              className={cn(s.opportunity__statusItem, {
                selected:
                  OpportunityExpectedOutcome[expectedOutcome] ===
                  OpportunityExpectedOutcome.Failure,
                oneSelected,
              })}
              onClick={() => onStatusClick(id, OpportunityExpectedOutcome.Failure)}
            >
              <div className={s.opportunity__statusEmoji}>
                <img
                  src={require('assets/images/emojis/failure.png').default.src}
                  alt="Customer is unhappy"
                />
              </div>
              <div className={s.opportunity__statuslabel}>Nei</div>
            </button>
            <button
              type="button"
              className={cn(s.opportunity__statusItem, { oneSelected })}
              onClick={() => onInvalidatedButtonClick()}
            >
              <div className={s.opportunity__statusEmoji}>
                <img
                  src={require('assets/images/emojis/invalidated.png').default.src}
                  alt="Opportunity does not apply to customer"
                />
              </div>
              <div className={s.opportunity__statuslabel}>Á ekki við</div>
            </button>
          </div>
        </div>
      )}

      {isInvalidatedOpen && (
        <div className={s.opportunity__invalidated}>
          <h2 className={cn(s.opportunity__subtitle, 'arrow')}>
            Afherju á þetta sölutækifæri ekki við?
          </h2>
          <div className={s.opportunity__inputWrapper}>
            <textarea
              className={s.opportunity__note}
              value={invalidatedNote}
              onChange={handleChange}
              autoFocus
            />
            {showInvalidatedError && (
              <div className={s.opportunity__invalidatedError}>
                Úps, þú gleymdir að skrifa afhverju!
              </div>
            )}
          </div>
          <div className={s.opportunity__buttonWrapper}>
            <button
              type="button"
              className={cn(s.opportunity__closeButton, `color-${color}`)}
              onClick={() => onInvalidatedClose()}
            >
              <SVGArrow className={s.opportunity__closeButtonIcon} />
              Til baka
            </button>
            <button
              type="button"
              className={cn(s.opportunity__sendButton, `color-${color}`, {
                loading: loadingInvalidatedButton,
              })}
              onClick={() => onInvalidatedSubmit(id)}
            >
              Senda
            </button>
          </div>
        </div>
      )}

      {onCloseOpportunity && (
        <button
          type="button"
          className={s.opportunity__closeOpportunity}
          onClick={onCloseOpportunity}
        >
          <span className={s.opportunity__closeOpportunityLabel}>Loka tækifæri</span>
          <SVGArrowLeft className={s.opportunity__closeOpportunitySVG} />
        </button>
      )}
    </div>
  );
};

export default Opportunity;
