import React, { FC, useState, useRef, useEffect } from 'react';
import Button from '../../blocks/Button';
import Form from '../../blocks/Form';
import Textarea from '../../blocks/Textarea';
import Rating from 'react-rating';
import css from './index.module.css';
import IconStarEmptySVG from '../../assets/icons/icon-star-empty.svg';
import IconStarFullSVG from '../../assets/icons/icon-star-full.svg';
import classnames from 'classnames';

export interface FormCustomerFeedbackValues {
  isSolvedMatter?: boolean;
  technicianPerformanceRating?: number;
  technicianImproveWork?: string[];
  technicianImproveWorkReason?: string;
  milaServiceRating?: number;
  milaServiceRatingReason?: string;
}

export interface FormCustomerFeedbackLabels {
  isSolvedMatter?: string;
  yes?: string;
  no?: string;
  technicianPerformanceRating?: string;
  unhappy?: string;
  happy?: string;
  technicianImproveWork?: string;
  technicianImproveWorkOptions?: { [key: string]: string };
  technicianImproveWorkReason?: string;
  milaServiceRating?: string;
  leastLikely?: string;
  mostLikely?: string;
  milaServiceRatingReason?: string;
  thanksText?: string;
  feedbackButton?: string;
}

export interface FormCustomerFeedbackErrors {
  isSolvedMatter?: string;
  technicianPerformanceRating?: string;
  technicianImproveWork?: string;
  technicianImproveWorkReason?: string;
  milaServiceRating?: string;
  milaServiceRatingReason?: string;
}

export interface FormCustomerFeedbackTouched {
  [key: string]: unknown;
}

export interface FormCustomerFeedbackProps {
  values: FormCustomerFeedbackValues;
  touched: FormCustomerFeedbackTouched;
  errors: FormCustomerFeedbackErrors;
  labels: FormCustomerFeedbackLabels;
  setFieldValue: (field, value) => void;
  handleChange: (e) => void;
  handleBlur: (e) => void;
  handleSubmit: (e) => void;
  isSubmitting?: boolean;
  technician: string;
  status?: {
    msg: string;
  };
}

const FormCustomerFeedback: FC<FormCustomerFeedbackProps> = ({
  values,
  errors,
  handleChange,
  handleSubmit,
  labels,
  isSubmitting,
  technician,
  setFieldValue,
}) => {
  const [isSolvedMatter, setIsSolvedMatter] = useState(null);
  const inputEl = useRef(null);
  const [isDisabled, setDisable] = useState(true);
  const [rating, setRating] = useState(0);
  const [selectedValues, setSelectedValues] = useState([]);
  const [scrollToError, setScrollToError] = useState(true);
  const startRating = useRef(null);

  const [
    technicianPerformanceRating,
    setTechnicianPerformanceRating,
  ] = useState(0);

  const ratingChanged = (newRating): void => {
    setTechnicianPerformanceRating(newRating);
    setFieldValue('technicianPerformanceRating', newRating);
  };

  const createRatingButton = (value): JSX.Element => {
    value += 1;
    return (
      <li
        className={`${rating == value ? css.formFeedback__active : ''}`}
        key={value}
      >
        <Button
          handleClick={(): void => {
            setRating(value);
            setFieldValue('milaServiceRating', value);
          }}
          size={'small'}
          variant={'tertiary'}
        >
          {value}
        </Button>
      </li>
    );
  };

  values.technicianImproveWork = selectedValues;

  useEffect(() => {
    setDisable(Object.keys(errors).length != 0);
  }, [errors]);

  useEffect(() => {
    if (errors.technicianImproveWork && scrollToError) {
      setScrollToError(false);
      window.scrollTo({
        top: startRating.current.offsetTop,
        behavior: 'smooth',
      });
    }
  }, [errors.technicianImproveWork]);

  useEffect(() => {
    setFieldValue('technicianImproveWork', selectedValues);
  }, [selectedValues, values.technicianPerformanceRating]);

  return (
    <Form onSubmit={handleSubmit} novalidate>
      <div className={css.formFeedback__contentWrap}>
        <h2 className={css.formFeedback__contentText}>
          {labels.isSolvedMatter}
        </h2>
        <div className={css.formFeedback__option}>
          <div className={css.formFeedback__optionYes}>
            <Button
              type="button"
              variant={isSolvedMatter ? 'verified' : 'tertiary'}
              fullwidth={false}
              handleClick={(): void => {
                setIsSolvedMatter(true);
                setFieldValue('isSolvedMatter', true);
              }}
            >
              {labels.yes}
            </Button>
          </div>
          <div className={css.formFeedback__optionNo}>
            <Button
              type="button"
              variant={
                !isSolvedMatter && isSolvedMatter != null
                  ? 'verified'
                  : 'tertiary'
              }
              fullwidth={false}
              handleClick={(): void => {
                setIsSolvedMatter(false);
                setFieldValue('isSolvedMatter', false);
              }}
            >
              {labels.no}
            </Button>
          </div>
        </div>
      </div>
      <div className={css.formFeedback__contentWrap}>
        <h2 className={css.formFeedback__contentText}>
          {labels.technicianPerformanceRating + ' ' + technician + ' ' + '?'}
        </h2>
        <div className={css.formFeedback__ratingBox}>
          <div className={css.formFeedback__ratingBoxtitle}>
            <div className={css.formFeedback__ratingUnhappytext}>
              {labels.unhappy}
            </div>
            <div className={css.formFeedback__ratingHappytext}>
              {labels.happy}
            </div>
          </div>
        </div>
        <div className={css.formFeedback__ratingStarbox}>
          <Rating
            direction={'ltr'}
            initialRating={technicianPerformanceRating}
            emptySymbol={
              <IconStarEmptySVG className={css.formFeedback__star} />
            }
            fullSymbol={<IconStarFullSVG className={css.formFeedback__star} />}
            onClick={ratingChanged}
          />
        </div>
        {technicianPerformanceRating > 0 && (
          <>
            <div
              className={css.formFeedback__ratingStarimprovebox}
              ref={startRating}
            >
              {technicianPerformanceRating < 5 && (
                <>
                  <div className={css.formFeedback__technicianText}>
                    <div>{labels.technicianImproveWork}</div>
                    {errors && errors.technicianImproveWork ? (
                      <div className={css.formFeedback__error}>
                        {errors.technicianImproveWork}
                      </div>
                    ) : (
                      ''
                    )}
                  </div>
                  <div className={css.formFeedback__technicianOptions}>
                    {labels.technicianImproveWorkOptions &&
                      Object.keys(labels.technicianImproveWorkOptions).length >
                        0 &&
                      Object.entries(labels.technicianImproveWorkOptions).map(
                        ([key, value]) => (
                          <div
                            key={key}
                            className={
                              css.formFeedback__technicianOptionsbutton
                            }
                          >
                            <Button
                              type="button"
                              variant={
                                selectedValues.indexOf(key) !== -1
                                  ? 'verified'
                                  : 'tertiary'
                              }
                              fullwidth={false}
                              handleClick={(): void => {
                                if (selectedValues.indexOf(key) !== -1) {
                                  const index = selectedValues.indexOf(key);
                                  selectedValues.splice(index, 1);
                                  setSelectedValues([...selectedValues]);
                                } else {
                                  setSelectedValues([...selectedValues, key]);
                                }
                              }}
                            >
                              {value}
                            </Button>
                          </div>
                        ),
                      )}
                  </div>
                </>
              )}

              <div className={css.formFeedback__input}>
                <Textarea
                  style={'booking'}
                  label={labels.technicianImproveWorkReason}
                  initialRows={2}
                  name={'technicianImproveWorkReason'}
                  onChange={handleChange}
                  value={values.technicianImproveWorkReason}
                  inputRef={inputEl}
                  required={false}
                  placeholder={labels.technicianImproveWorkReason}
                  optional={true}
                />
              </div>
            </div>
          </>
        )}
      </div>
      <div className={css.formFeedback__contentWrap}>
        <h2 className={css.formFeedback__contentText}>
          {labels.milaServiceRating}
        </h2>
        <div className={css.formFeedback__likeBox}>
          <div className={css.formFeedback__leastLikely}>
            {'1 - ' + labels.leastLikely}
          </div>
          <div className={css.formFeedback__mostLikely}>
            {'10 - ' + labels.mostLikely}
          </div>
        </div>
        <div className={css.formFeedback__ratingNumber}>
          <ul>
            {Array(10)
              .fill(1)
              .map((el, i) => createRatingButton(i))}
          </ul>
        </div>
        {rating > 0 && (
          <div className={css.formFeedback__input}>
            <Textarea
              style={'booking'}
              label={labels.milaServiceRatingReason}
              initialRows={2}
              name={'milaServiceRatingReason'}
              onChange={handleChange}
              value={values.milaServiceRatingReason}
              inputRef={inputEl}
              required={false}
              placeholder={labels.milaServiceRatingReason}
              optional={true}
            />
          </div>
        )}
      </div>
      <div className={css.formFeedback__contentWrap}>
        <h2 className={css.formFeedback__contentThankstext}>
          {labels.thanksText}
        </h2>
        <div className={css.formFeedback__submit}>
          <Button type="submit" disabled={isDisabled || isSubmitting}>
            {!isSubmitting ? (
              <>{labels.feedbackButton}</>
            ) : (
              <>
                <span
                  className={classnames([
                    css.loading__dot,
                    css.loading__dotOne,
                  ])}
                />
                <span
                  className={classnames([
                    css.loading__dot,
                    css.loading__dotTwo,
                  ])}
                />
                <span
                  className={classnames([
                    css.loading__dot,
                    css.loading__dotThree,
                  ])}
                />
              </>
            )}
          </Button>
        </div>
      </div>
    </Form>
  );
};

export default FormCustomerFeedback;
