import {
  h, useEffect, useEvent, useProp, useState,
} from "atomico";
import { ExerciseRecord } from "@caedman/seek-api/build/api/req-get-exercise-by-series";
import { KunCustomEvent } from "@caedman/spring/build/kun-custom-event";
import { Maybe } from "purify-ts/es/Maybe";
import produce, { Draft } from "immer";
import "../kun-button-puer/kun-button-puer";
import "../kun-checkbox/kun-checkbox";
import style from "./kun-exercise-select.scss";
import { getComponentOrDefine } from "../../hooks/aync-hook/redirect";

interface InputOption {
  checked: boolean;
  option: string;
}

const KunExerciseSelect = (): void => {
  const [kunSeriesId] = useProp<string>("kunSeriesId");
  const [kunPostId] = useProp<string>("kunPostId");

  const [kunExerciseProp] = useProp<ExerciseRecord>("kunExercise");
  const [kunExercise, setKunExercise] = useState(Maybe.fromNullable(kunExerciseProp).orDefault({
    options: [],
  } as ExerciseRecord));

  const [options, setOptions] = useState<InputOption[]>([]);

  useEffect(() => {
    const corrects = kunExerciseProp.correct.map((correctItem) => String(correctItem));
    const opts = kunExerciseProp.options.map((item, optionIndex) => ({ option: item, checked: corrects.indexOf(String(optionIndex)) !== -1 }));
    setOptions(opts);
  }, []);

  const onSubmit = useEvent("MySubmit", {
    bubbles: true,
    composed: true,
  });

  const onSubmitForm = (): void => {
    const data = produce(kunExercise, (draft: Draft<ExerciseRecord>) => {
      draft.seriesId = kunSeriesId;
      draft.postId = kunPostId;
      draft.options = options.map((r) => r.option);
      draft.correct = options.map((option, index) => ({ index, checked: option.checked })).filter((it) => it.checked).map((r) => r.index.toString());
      draft.exerciseType = "SELECT";
    });
    onSubmit(data);
  };

  const changeTitle = (event: MouseEvent): void => {
    setKunExercise(produce(kunExercise, (draft) => {
      draft.title = event.target.value;
    }));
  };

  const toggleCheck = (evt: KunCustomEvent<{checked: boolean}>, index: number): void => {
    const { checked } = evt.detail;
    setOptions(produce(options, (draft) => {
      draft[index].checked = checked;
    }));
  };

  const changeAnswer = (event: MouseEvent): void => {
    setKunExercise(produce(kunExercise, (draft) => {
      draft.answer = event.target.value;
    }));
  };

  const changeDescription = (event: MouseEvent): void => {
    setKunExercise(produce(kunExercise, (draft) => {
      draft.tips = event.target.value;
    }));
  };

  const removeOption = (index: number): void => {
    setOptions(produce(options, (draft) => {
      draft.splice(index, 1);
    }));
  };

  const changeOption = (event: MouseEvent, index1: number): void => {
    setOptions(produce(options, (draft) => {
      draft[index1].option = event.target.value;
    }));
  };

  const onAdd = (): void => {
    setOptions(produce(options, (draft) => {
      draft.push({
        checked: false,
        option: "",
      });
    }));
  };
  return (
    <host>
      <style>{style}</style>
      <div>
        <div className="mb-4">
          <label className="block text-gray-700 text-sm font-bold mb-2" htmlFor="username">
            问题
          </label>
          <input
            className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
            id="username"
            type="text"
            placeholder=""
            onchange={changeTitle}
            value={kunExercise.title}
          />
        </div>

        <div className="mb-4">
          <label className="block text-gray-700 text-sm font-bold mb-2" htmlFor="username">
            解释
          </label>
          <input
            className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
            id="username"
            type="text"
            placeholder=""
            onchange={changeDescription}
            value={kunExercise.tips}
          />
        </div>

        <div className="mb-4">
          <label className="block text-gray-700 text-sm font-bold mb-2" htmlFor="username">
            选项
          </label>
          <div>
            {
              options.map((option, index) => (
                <div class="flex flex-row w-full items-center mb-2">
                  <span class="mr-4">
                    <kun-checkbox checked={option.checked} onMyChecked={(evt) => toggleCheck(evt, index)} />
                  </span>
                  <div class="flex-auto">
                    <input
                      key={String(index)}
                      className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
                      type="text"
                      placeholder=""
                      onchange={(evt) => changeOption(evt, index)}
                      value={option.option}
                    />
                  </div>
                  <span class="px-4">
                    <kun-icon iconType="close" onclick={() => removeOption(index)} iconWidth={18} iconHeight={18} />
                  </span>
                </div>
              ))
            }
          </div>
          <kun-button-puer needleContent="添加选项" onMyClick={onAdd} />
        </div>

        <button
          onclick={onSubmitForm}
          className="bg-orange-400 hover:bg-orange-500 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline"
          type="submit"
        >
          提交
        </button>
      </div>
    </host>
  );
};

KunExerciseSelect.props = {
  kunSeriesId: {
    type: String,
  },
  kunPostId: {
    type: String,
  },
  kunExercise: {
    type: Object,
  },
};

export default getComponentOrDefine("kun-exercise-select", KunExerciseSelect);
