import { Select } from '@chakra-ui/react';
import { useState, useEffect } from 'react';

import { VIEW_ACTION_TYPES } from '../../constants/define';
import PuppeteerCodeGenerator from '../../modules/code-generator/puppeteer';

const EventFormatSelector = (props) => {
  const { code } = props;
  const [formatOption, setFormatOption] = useState(VIEW_ACTION_TYPES.STEPS);
  const [formatedCode, setFormatedCode] = useState(``);

  useEffect(() => {
    if (formatOption === VIEW_ACTION_TYPES.JSON) {
      setFormatedCode(JSON.stringify(code, null, 4));
    } else if (formatOption === VIEW_ACTION_TYPES.PUPPETEER_CODE) {
      const puppeteerCodeGenerate = new PuppeteerCodeGenerator({
        wrapAsync: true,
      });
      const puppeteeCode = puppeteerCodeGenerate.generate(code);
      setFormatedCode(puppeteeCode);
    } else if (formatOption === VIEW_ACTION_TYPES.STEPS) {
      setFormatedCode(JSON.stringify(code, null, 4));
    }
  }, [code, formatOption]);

  const handleOnSelect = (e) => {
    setFormatOption(e.target.value);
  };

  return (
    <>
      <Select onChange={handleOnSelect}>
        {Object.values(VIEW_ACTION_TYPES).map((option) => (
          <option key={option} value={option}>
            {option}
          </option>
        ))}
      </Select>
      {props.render(formatOption, formatedCode, setFormatedCode)}
    </>
  );
};

export default EventFormatSelector;
