import React, { useContext, useState, useCallback } from 'react';
import styled from 'styled-components';
import debounce from 'lodash.debounce';

import { CodeWalkthroughControlsStateContext } from '@redocly/theme/core/contexts';

export type InputProps = {
  id: string;
  label?: string;
  placeholder?: string;
  value?: string;
};

const DEBOUNCE_TIME = 500;

export function Input(props: InputProps) {
  const { id, label, placeholder } = props;
  const { getControlState, changeControlState } = useContext(CodeWalkthroughControlsStateContext);

  const inputState = getControlState(id);

  const [value, setValue] = useState(inputState?.value || '');

  // eslint-disable-next-line react-hooks/exhaustive-deps
  const debouncedSave = useCallback(
    debounce((id: string, value: string) => {
      changeControlState(id, value);
    }, DEBOUNCE_TIME),
    [],
  );

  if (!inputState?.render) {
    return null;
  }

  const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const inputValue = event.target.value;

    setValue(inputValue);
    debouncedSave(id, inputValue);
  };

  return (
    <InputWrapper data-component-name="Markdoc/CodeWalkthrough/Input">
      {label && <Label>{label}</Label>}
      <StyledInput
        id={id}
        value={value as string}
        onChange={handleChange}
        aria-label={label}
        placeholder={placeholder}
      />
    </InputWrapper>
  );
}

const InputWrapper = styled.div`
  display: flex;
  flex-direction: column;
  margin-top: var(--spacing-base);
  margin-bottom: var(--spacing-base);
`;

const Label = styled.p`
  color: var(--text-color-secondary);
  font-size: var(--font-size-base);
  line-height: var(--line-height-base);
  font-family: var(--font-family-base);
  font-weight: var(--font-weight-medium);
  margin-bottom: var(--spacing-xxs) !important;
`;

const StyledInput = styled.input`
  border: 1px solid var(--border-color-primary);
  width: 224px;
  outline: none;
  padding: var(--input-padding) var(--spacing-sm);
  border-radius: var(--input-border-radius);
  background-color: var(--input-bg-color);
  color: var(--text-color-secondary);
  font-family: var(--font-family-base);
  font-size: var(--font-size-base);
  line-height: var(--input-line-height);

  &::placeholder {
    opacity: 1;
    color: var(--input-content-placeholder-color);
  }

  &:hover {
    color: var(--text-color-primary);
    border: 1px solid var(--border-color-primary);
  }

  &:focus {
    color: var(--text-color-primary);
    border: 1px solid var(--border-color-primary);
  }

  &:-webkit-autofill {
    background-color: var(--input-bg-color);
  }
`;
