import * as React from 'react';
import styled from 'styled-components';

import type { JSX } from 'react';

import { useThemeHooks } from '@redocly/theme/core/hooks';

export type ReasonsProps = {
  onChange: (value: string[]) => void;
  settings: {
    label?: string;
    component?: string;
    items: string[];
  };
  className?: string;
};

export function Reasons({ settings, onChange, className }: ReasonsProps): JSX.Element | null {
  const { label, component, items = [] } = settings;
  const [checkedState, setCheckedState] = React.useState(new Array(items.length).fill(false));
  const { useTranslate } = useThemeHooks();
  const { translate } = useTranslate();

  if (!items.length) {
    return null;
  }

  const input_type = component || 'checkbox';

  const handleOptionChange = (position: number) => {
    const updatedCheckedState =
      component === 'checkbox'
        ? checkedState.map((item, index) => (index === position ? !item : item))
        : items.map((_, idx) => position === idx);
    setCheckedState(updatedCheckedState);

    onChange(items.filter((_, index) => !!updatedCheckedState[index]));
  };

  return (
    <ReasonsWrapper
      data-component-name="Feedback/Reasons"
      data-translation-key="feedback.settings.reasons.label"
      className={className}
    >
      <Label>
        {label ||
          translate(
            'feedback.settings.reasons.label',
            'Which statement describes your thoughts about this page?',
          )}
      </Label>
      {items.map((reason, idx) => (
        <OptionWrapper key={reason}>
          <input
            type={input_type}
            value={reason}
            checked={checkedState[idx]}
            name="reasons"
            onChange={() => handleOptionChange(idx)}
          />
          <label
            data-translation-key={`feedback.settings.reasons.items.${idx + 1}`}
            id={reason}
            onClick={() => handleOptionChange(idx)}
          >
            {translate(`feedback.settings.reasons.items.${idx + 1}`, reason)}
          </label>
        </OptionWrapper>
      ))}
    </ReasonsWrapper>
  );
}

const ReasonsWrapper = styled.div`
  font-family: var(--feedback-font-family);
  display: flex;
  flex-direction: column;
`;

const Label = styled.h4`
  font-family: var(--feedback-font-family);
  font-weight: var(--font-weight-regular);
  font-size: var(--feedback-font-size);
  line-height: var(--feedback-header-line-height);
  color: var(--feedback-header-text-color);
  margin: 0;
`;

const OptionWrapper = styled.div`
  margin: 5px 0;
  display: flex;
  input {
    margin-right: 10px;
    cursor: pointer;
  }
  label {
    font-size: var(--feedback-font-size);
    cursor: pointer;
  }
`;
