import React, { useState, useEffect } from 'react';
import styled from 'styled-components';

import type { JSX } from 'react';

import { FeedbackType } from '@redocly/theme/core/types';
import { Button } from '@redocly/theme/components/Button/Button';
import { CloseIcon } from '@redocly/theme/icons/CloseIcon/CloseIcon';
import { ArrowLeftIcon } from '@redocly/theme/icons/ArrowLeftIcon/ArrowLeftIcon';
import { SendIcon } from '@redocly/theme/icons/SendIcon/SendIcon';
import { useThemeHooks } from '@redocly/theme/core/hooks';

export type SearchAiNegativeFeedbackFormProps = {
  messageId: string;
  onClose: (messageId: string, feedback: FeedbackType, reason?: string) => void;
  onSubmit: (reason: string) => void;
  formRef?: React.Ref<HTMLDivElement>;
};

const NEGATIVE_FEEDBACK_DEFAULT_REASONS = [
  "Didn't answer my question",
  "Couldn't find what I was looking for",
  'Wrong topic',
  'Partially helpful, but missing details',
];

export function SearchAiNegativeFeedbackForm({
  messageId,
  onClose,
  onSubmit,
  formRef,
}: SearchAiNegativeFeedbackFormProps): JSX.Element {
  const { useTranslate } = useThemeHooks();
  const { translate } = useTranslate();
  const [showMoreInput, setShowMoreInput] = useState(false);
  const [detailedFeedback, setDetailedFeedback] = useState('');
  const textAreaRef = React.useRef<HTMLTextAreaElement>(null);

  const adjustTextAreaHeight = () => {
    const textArea = textAreaRef.current;
    if (textArea) {
      textArea.style.height = 'auto';
      textArea.style.height = `${textArea.scrollHeight}px`;
    }
  };

  const handleTextChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
    setDetailedFeedback(e.target.value);
    adjustTextAreaHeight();
  };

  useEffect(() => {
    if (showMoreInput) {
      adjustTextAreaHeight();
    }
  }, [showMoreInput]);

  return (
    <FeedbackFormWrapper data-component-name="Search/SearchAiNegativeFeedbackForm" ref={formRef}>
      <FeedbackHeader>
        {showMoreInput ? (
          <BackButton
            variant="text"
            size="small"
            icon={<ArrowLeftIcon />}
            onClick={() => setShowMoreInput(false)}
            aria-label="Back to feedback reasons"
          />
        ) : null}
        <FeedbackTitle data-translation-key="search.ai.feedback.title">
          {translate('search.ai.feedback.title', "What didn't you like about this response?")}
        </FeedbackTitle>
        <CloseButton
          variant="text"
          size="small"
          icon={<CloseIcon />}
          onClick={() => onClose(messageId, FeedbackType.Dislike, undefined)}
          aria-label="Close feedback form"
        />
      </FeedbackHeader>

      {!showMoreInput ? (
        <FeedbackReasonsWrapper>
          {NEGATIVE_FEEDBACK_DEFAULT_REASONS.map((reason) => (
            <Button key={reason} variant="outlined" size="small" onClick={() => onSubmit(reason)}>
              {reason}
            </Button>
          ))}
          <Button variant="outlined" size="small" onClick={() => setShowMoreInput(true)}>
            {translate('search.ai.feedback.more', 'More...')}
          </Button>
        </FeedbackReasonsWrapper>
      ) : (
        <FeedbackInputWrapper>
          <FeedbackTextArea
            ref={textAreaRef}
            placeholder={translate('search.ai.feedback.detailsPlaceholder', 'Add specific details')}
            value={detailedFeedback}
            onChange={handleTextChange}
            rows={1}
            autoFocus
          />
          <SendButton
            size="small"
            icon={
              <SendIcon
                color={
                  !detailedFeedback.trim()
                    ? '--button-content-color-disabled'
                    : 'var(--search-ai-conversation-input-send-button-icon-color)'
                }
              />
            }
            onClick={() => onSubmit(detailedFeedback)}
            disabled={!detailedFeedback.trim()}
            aria-label="Send feedback"
          />
        </FeedbackInputWrapper>
      )}
    </FeedbackFormWrapper>
  );
}

const FeedbackFormWrapper = styled.div`
  display: flex;
  flex-direction: column;
  gap: var(--spacing-sm);
  padding: var(--spacing-xs);
  background: var(--search-ai-feedback-form-bg-color);
  border: 1px solid var(--search-ai-feedback-form-border-color);
  border-radius: var(--border-radius-lg);
`;

const FeedbackHeader = styled.div`
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: var(--spacing-sm);
`;

const FeedbackTitle = styled.div`
  font-size: var(--font-size-base);
  color: var(--text-color);
  flex: 1;
`;

const BackButton = styled(Button)`
  flex-shrink: 0;
`;

const CloseButton = styled(Button)`
  flex-shrink: 0;
`;

const FeedbackReasonsWrapper = styled.div`
  display: flex;
  flex-wrap: wrap;
  gap: var(--spacing-xs);
`;

const FeedbackInputWrapper = styled.div`
  position: relative;
  width: 100%;
`;

const FeedbackTextArea = styled.textarea`
  width: 100%;
  min-height: 5rem;
  max-height: 12.5rem;
  padding: var(--spacing-xs);
  padding-right: 3rem;
  border: 1px solid var(--border-color-primary);
  border-radius: var(--border-radius-md);
  font-family: inherit;
  font-size: var(--font-size-base);
  line-height: var(--line-height-base);
  background: var(--background-color);
  color: var(--text-color);
  resize: none;
  overflow-y: auto;

  &:focus {
    outline: 1px solid var(--button-border-color-focused);
    border-color: var(--button-border-color-focused);
  }

  &::placeholder {
    color: var(--text-color-helper);
  }
`;

const SendButton = styled(Button)`
  position: absolute;
  right: var(--search-ai-conversation-input-send-button-right);
  bottom: var(--spacing-sm);
  transition: background-color 0.2s ease;
  background-color: var(--search-ai-conversation-input-send-button-bg-color);
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: var(--search-ai-conversation-input-send-button-border-radius);
  padding: var(--search-ai-conversation-input-send-button-padding);

  &:hover {
    background-color: var(--search-ai-conversation-input-send-button-bg-color-hover);
  }

  &:disabled {
    background-color: var(--search-ai-conversation-input-send-button-bg-color-disabled);
    border: var(--search-ai-conversation-input-send-button-border-disabled);
  }
`;
