import * as React from "react";
import { Col, Input, Row } from "reactstrap";
import { IChoiceProps } from "./Choice";
import { IInternalPromptProps, IPromptProps } from "./Prompt";
import { MultipleChoicePromptData } from "./QuizData";

export interface IMultipleChoicePromptProps extends IPromptProps {
  onlyOne?: boolean;
  randomOrder?: boolean;
  choices: Array<React.ReactElement<IChoiceProps>>;
}

export class MultipleChoicePrompt extends React.PureComponent<
  IMultipleChoicePromptProps
> {
  static is(value: any): value is MultipleChoicePrompt {
    return React.isValidElement(value) && value.type === MultipleChoicePrompt;
  }

  render() {
    return null;
  }
}

export interface IInternalMultipleChoicePromptProps
  extends IInternalPromptProps {
  prompt: MultipleChoicePromptData;
  input: boolean[];
  update(fn: (input: boolean[]) => boolean[]): boolean[];
}

export class InternalMultipleChoicePrompt extends React.PureComponent<
  IInternalMultipleChoicePromptProps
> {
  createOnChange = (index: number) => () => {
    this.props.update(input => {
      const nextInput = this.props.prompt.onlyOne ? [] : input.slice();
      nextInput[index] = !nextInput[index];
      return nextInput;
    });
  };
  render() {
    return (
      <div>
        <div>{this.props.prompt.prompt}</div>
        {this.props.prompt.choices.map((child, index) => (
          <div key={index}>
            <Row>
              <Col sm={1}>
                <Input
                  className={`MultipleChoice Input ${index}`}
                  disabled={this.props.disabled}
                  onChange={this.createOnChange(index)}
                  type="checkbox"
                  checked={!!this.props.input[index]}
                />
              </Col>
              <Col sm={11}>{child.children}</Col>
            </Row>
            {index < this.props.prompt.choices.length - 1 && <hr />}
          </div>
        ))}
      </div>
    );
  }
}
