import React, { FC, useEffect, useRef, useState } from 'react';
import Form from '../../blocks/Form';
import Input from '../../blocks/Input';
import css from './index.module.css';
import booking from '../../templates/BookingFunnel/index.module.css';
import { checkIfDateIsSame } from '../../templates/BookingFunnel';
import Textarea from '../../blocks/Textarea';
import Button from '../../blocks/Button';
import Checkbox from '../../blocks/Checkbox';
import { MilaDatePicker } from '../../index';
import CheckIconSVG from '../../assets/icons/icon_check.svg';
import { getYear } from 'date-fns';

export interface FormServiceDetailsValues {
  date: Date;
  description: string;
  isFlexibleCheckbox: boolean;
  voucher: string;
}

export interface FormServiceDetailsLabels {
  chooseDateTime: string;
  date: string;
  isFlexibleCheckbox: string;
  voucher: string;
  time: string;
  additionalInfo: string;
  problem: string;
  voucherVerify: string;
  voucherVerified: string;
}

export interface FormServiceDetailsErrors {
  date: string;
  description: string;
  isFlexibleCheckbox: string;
  voucher: string;
}

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

export interface FormServiceDetailsProps {
  values: FormServiceDetailsValues;
  touched: FormServiceDetailsTouched;
  errors: FormServiceDetailsErrors;
  labels: FormServiceDetailsLabels;
  handleChange: (e) => void;
  handleBlur: (e) => void;
  handleSubmit: (e) => void;
  verifyVoucher: (code: string) => Promise<string>;
  removeVoucher: (code: string) => void;
  setFieldError: (field: string, errorMsg: string) => void;
  setFieldTouched: (
    field: string,
    isTouched?: boolean,
    shouldValidate?: boolean,
  ) => void;
  setFieldValue: (
    field: string,
    value: string,
    shouldValidate?: boolean,
  ) => void;
  isSubmitting?: boolean;
  wrapperClass?: string;
  status?: {
    msg: string;
  };
  isVerifying: boolean;
  locale: string;
  initialVouchers?: string[];
  checkIfKeyBoardOpen?: (e) => void;
  campaign?: string;
}

export function roundMinutes(minutes: number): number {
  return 30 * Math.ceil(minutes / 30);
}

export function keep2020great(date: Date | number): boolean {
  return getYear(date) === 2020;
}

const FormServiceDetails: FC<FormServiceDetailsProps> = ({
  values,
  errors,
  handleChange,
  handleBlur,
  handleSubmit,
  setFieldTouched,
  setFieldValue,
  setFieldError,
  labels,
  status,
  wrapperClass,
  verifyVoucher,
  isVerifying,
  locale,
  removeVoucher,
  initialVouchers,
  checkIfKeyBoardOpen,
  campaign,
}) => {
  const isUk = locale.slice(3, 5).toLowerCase() === 'gb';

  const inputEl = useRef(null);
  // 24 Hours = 86400000
  const minDate = new Date(new Date().getTime() + 86400000);
  minDate.setMinutes(roundMinutes(minDate.getMinutes()));

  const [isFlexible, setFlexible] = useState(false);
  const [vouchers, setVouchers] = useState([]);
  const [date, setDate] = useState<Date>();
  const [minTime, setMinTime] = useState(minDate);
  const [isVerified, setVerified] = useState(false);

  const handleDateChange = (date): void => {
    if (date && checkIfDateIsSame(date, minDate)) {
      if (
        minDate.getHours() * 60 + minDate.getMinutes() >
        date.getHours() * 60 + date.getMinutes()
      ) {
        date.setMinutes(roundMinutes(minDate.getMinutes()));
        setMinTime(date);
      }
    } else {
      setMinTime(new Date(new Date().setHours(0, 0, 0, 0)));
    }
    setFieldValue('date', date != null ? date : '');
    setDate(date);
  };

  useEffect(() => {
    if (values.date) {
      const date = new Date(values.date);
      setDate(date);
    } else {
      setDate(minDate);
      // eslint-disable-next-line
      setFieldValue('date', minDate as any);
    }
    setFieldTouched('date', true);
  }, [values.date]);

  useEffect(() => {
    setFlexible(values.isFlexibleCheckbox);
  }, [values.isFlexibleCheckbox]);

  useEffect(() => {
    setVouchers(initialVouchers || []);
  }, [initialVouchers]);

  return (
    <Form onSubmit={handleSubmit} novalidate>
      <div className={wrapperClass}>
        <span className={booking.booking__contentTitle}>
          {labels.additionalInfo}
        </span>
        <div className={css.booking__contentInformation}>
          <Textarea
            style={'booking'}
            label={labels.additionalInfo}
            initialRows={2}
            name={'description'}
            onChange={handleChange}
            value={values.description}
            inputRef={inputEl}
            required={false}
            placeholder={labels.problem}
            optional={true}
            isKeyBoardOpen={checkIfKeyBoardOpen}
          />
        </div>
      </div>
      <div className={wrapperClass}>
        <span className={booking.booking__contentTitle}>
          {labels.chooseDateTime}
        </span>
        <div className={css.booking__contentDateTimePicker}>
          <div className={css.booking__contentDateTimePickerContainer}>
            <MilaDatePicker
              showDisabledMonthNavigation
              name="date"
              label={labels.date}
              selected={date}
              onChange={(date): void => {
                setFieldTouched('date', true);
                handleDateChange(date);
              }}
              onBlur={(e): void => {
                setFieldTouched('date', true);
                handleBlur(e);
              }}
              minDate={minDate}
              disabled={isFlexible}
              dateFormat="d. MMMM yyyy"
              error={errors.date}
              locale={locale}
              filterDate={campaign === 'cyberweek' && keep2020great}
            />

            <MilaDatePicker
              shouldCloseOnSelect={true}
              selected={date}
              onChange={(date): void => {
                setFieldTouched('date', true);
                handleDateChange(date);
              }}
              onBlur={(e): void => {
                setFieldTouched('date', true);
                handleBlur(e);
              }}
              error={errors.date}
              hideError={true}
              name="date"
              label={labels.time}
              showTimeSelect
              showTimeSelectOnly
              timeIntervals={30}
              timeCaption="Time"
              timeFormat={`${isUk ? 'h:mm aa' : 'HH:mm'}`}
              dateFormat={`${isUk ? 'h:mm aa' : 'HH:mm'}`}
              locale={locale}
              disabled={isFlexible || date == null}
              minDate={minDate}
              minTime={
                new Date(
                  new Date().setHours(
                    minTime.getHours(),
                    minDate.getMinutes(),
                    0,
                    0,
                  ),
                )
              }
              maxTime={new Date(new Date().setHours(23, 59, 0, 0))}
              filterDate={campaign === 'cyberweek' && keep2020great}
            />
          </div>

          <Checkbox
            onChange={handleChange}
            name="isFlexibleCheckbox"
            label={labels.isFlexibleCheckbox}
            value={values.isFlexibleCheckbox}
          />
        </div>
      </div>

      <div className={wrapperClass}>
        <div className={css.booking__voucher}>
          <div
            className={`${css.booking__voucherInput} ${
              isVerifying ? css.booking__voucherInputVerifying : ''
            }`}
          >
            <div>
              <Input
                type={'text'}
                label={labels.voucher}
                name="voucher"
                value={values.voucher}
                onChange={handleChange}
                error={errors.voucher}
                style={'booking'}
                autocomplete="off"
                isOptionalDisplay={true}
                required={false}
                isKeyBoardOpen={checkIfKeyBoardOpen}
                onFocus={(): void => {
                  setVerified(false);
                }}
              />
            </div>
            <Button
              handleClick={(): void => {
                if (isVerified || isVerifying) return;
                // Prevent to use same voucher
                if (
                  vouchers.filter(function(e) {
                    return e === values.voucher;
                  }).length > 0
                ) {
                  return;
                }
                verifyVoucher(values.voucher)
                  .then(val => {
                    setVouchers([...vouchers, val]);
                    setFieldValue('voucher', '');
                    setVerified(true);
                  })
                  .catch(value => {
                    setFieldError('voucher', value);
                  });
              }}
              size={'small'}
              variant={'tertiary'}
              showThrobber={isVerifying}
              disabled={values.voucher == '' || errors.voucher != null}
            >
              {isVerified ? labels.voucherVerified : labels.voucherVerify}
            </Button>
          </div>
          <div className={css.booking__voucherList}>
            {vouchers.map((val, index) => {
              return (
                <div
                  key={index + 'voucher'}
                  className={css.booking__voucherListItem}
                >
                  <CheckIconSVG width={16} />
                  <span>{val}</span>
                  <Button
                    handleClick={(): void => {
                      removeVoucher(val);
                      setVouchers([
                        ...vouchers.filter((item, i) => i != index),
                      ]);
                    }}
                  >
                    <i className="fa fa-trash" aria-hidden="true"></i>
                  </Button>
                </div>
              );
            })}
          </div>
        </div>
      </div>

      {status && status.msg && (
        <div className={css.formRegister__messages}>{status.msg}</div>
      )}
    </Form>
  );
};

export default FormServiceDetails;
