import React, { useState, useEffect } from 'react';
import { Modal, Radio, Form, TimePicker, Checkbox } from 'antd';
import { MinusSquareOutlined, PlusSquareOutlined } from '@ant-design/icons';
import moment from 'moment';
import { deepClone } from '@/utils/utils';
import { saleWeeks } from '../../staticdata';
import styles from '../../style.less';

const WeekTime = options => {
  const [form] = Form.useForm();
  const [type, setType] = useState(0);

  const formItemLayout = {
    labelCol: {
      xs: { span: 24 },
      sm: { span: 6 },
    },
    wrapperCol: {
      xs: { span: 24 },
      sm: { span: 16 },
    },
  };
  const formItemLayoutWithOutLabel = {
    wrapperCol: {
      xs: { span: 22, offset: 0 },
      sm: { span: 16, offset: 6 },
    },
  };

  const onChangeType = ({ target: { value } }) => {
    setType(value);
  };

  const radioOptions = [{ label: $t('all.day'), value: 0 }, { label: $t('custom.sale.time'), value: 1 }];

  const handleCancel = () => {
    options.cancel(false);
  };
  const handleOk = async () => {
    const params = await form.validateFields();
    // const params = values;
    if (params.saleTimes && params.saleTimes.length) {
      params.saleTimes = params.saleTimes.map(item => ({
        startTime: moment(item[0]).format('HH:mm'),
        endTime: moment(item[1]).format('HH:mm'),
      }));
    }

    options.confirm({
      type: 4,
      ...params,
    });
  };

  const onTimeValidator = (rule, value, callback) => {
    if (value && value.length === 2) {
      if (moment(value[0]).format('HH:mm') === moment(value[1]).format('HH:mm')) {
        callback(new Error($t('enter.number.0')));
      } else {
        callback();
      }
    } else {
      callback();
    }
  };

  const initialValues = Object.assign(
    {
      saleTimeType: 0,
      saleDates: [],
      saleTimes: [[]],
    },
    options.initialValues,
  );

  useEffect(() => {
    options.visible && setType(0);
  }, [options.visible]);

  return (
    <Modal
      visible={options.visible}
      title={$t('sale.time')}
      onOk={handleOk}
      confirmLoading={options.loading}
      maskClosable={false}
      keyboard={false}
      destroyOnClose
      onCancel={handleCancel}
    >
      <Form
        name="basic"
        form={form}
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 16 }}
        initialValues={initialValues}
        autoComplete="off"
      >
        <Form.Item
          label={$t('sale.period.type')}
          name="saleTimeType"
          rules={[{ required: true, message: $t('select.time.slot.type') }]}
        >
          <Radio.Group
            options={radioOptions}
            onChange={onChangeType}
            value={type}
            optionType="button"
            buttonStyle="solid"
          />
        </Form.Item>
        {type === 1 ? (
          <>
            <Form.Item
              label={$t('sale.date')}
              name="saleDates"
              rules={[{ required: true, message: $t('select.sale.date') }]}
            >
              <Checkbox.Group options={saleWeeks} />
            </Form.Item>
            <Form.List
              label={$t('sale.time')}
              name="saleTimes"
              rules={[
                {
                  validator: async (_, saleTimes) => {
                    if (!saleTimes || saleTimes.length < 1) {
                      return Promise.reject(new Error($t('sale.time.required')));
                    }
                    return Promise.resolve();
                  },
                },
              ]}
            >
              {(fields, { add, remove }) => (
                <>
                  {fields.map((field, index) => (
                    <Form.Item
                      label={index === 0 ? $t('sale.date') : ''}
                      {...(index === 0 ? formItemLayout : formItemLayoutWithOutLabel)}
                      required
                      key={field.key}
                    >
                      <Form.Item
                        {...field}
                        validateTrigger={['onChange', 'onBlur']}
                        rules={[
                          {
                            required: true,
                            message: $t('select.sale.time'),
                          },
                          {
                            validator: onTimeValidator,
                            message: $t('end.time.start.time'),
                          },
                        ]}
                        noStyle
                      >
                        <TimePicker.RangePicker format="HH:mm" minuteStep={30} />
                      </Form.Item>
                      {index > 0 ? (
                        <MinusSquareOutlined
                          className={[styles['week-time-box--icon'], styles.error]}
                          onClick={() => remove(field.name)}
                        />
                      ) : (
                        <PlusSquareOutlined
                          className={[styles['week-time-box--icon'], styles.primary]}
                          onClick={() => add()}
                        />
                      )}
                    </Form.Item>
                  ))}
                </>
              )}
            </Form.List>
          </>
        ) : (
          ''
        )}
      </Form>
    </Modal>
  );
};

export default WeekTime;
