import type React from "react";
import { useTranslation } from "react-i18next";
import { useGetConfig } from "@/controllers/API/queries/config/use-get-config";
import {
  ENABLE_FILES_ON_PLAYGROUND,
  ENABLE_VOICE_ASSISTANT,
} from "@/customization/feature-flags";
import type { FilePreviewType } from "@/types/components";
import FilePreview from "../../fileComponent/components/file-preview";
import ButtonSendWrapper from "./button-send-wrapper";
import TextAreaWrapper from "./text-area-wrapper";
import UploadFileButton from "./upload-file-button";
import VoiceButton from "./voice-assistant/components/voice-button";

interface InputWrapperProps {
  isBuilding: boolean;
  checkSendingOk: (event: React.KeyboardEvent<HTMLTextAreaElement>) => boolean;
  send: () => void;
  noInput: boolean;
  chatValue: string;
  inputRef: React.RefObject<HTMLTextAreaElement>;
  files: FilePreviewType[];
  isDragging: boolean;
  handleDeleteFile: (file: FilePreviewType) => void;
  fileInputRef: React.RefObject<HTMLInputElement | null>;
  handleFileChange: (event: React.ChangeEvent<HTMLInputElement>) => void;
  handleButtonClick: () => void;
  setShowAudioInput: (value: boolean) => void;
  currentFlowId: string;
  playgroundPage: boolean;
}

const InputWrapper: React.FC<InputWrapperProps> = ({
  isBuilding,
  checkSendingOk,
  send,
  noInput,
  chatValue,
  inputRef,
  files,
  isDragging,
  handleDeleteFile,
  fileInputRef,
  handleFileChange,
  handleButtonClick,
  setShowAudioInput,
  playgroundPage,
}) => {
  const { t } = useTranslation();
  const classNameFilePreview = `flex w-full items-center gap-2 py-2 overflow-auto`;

  // Check if voice mode is available
  // The /config endpoint returns appropriate config based on auth status
  const { data: config } = useGetConfig({});

  const onClick = (e: React.MouseEvent<HTMLDivElement>) => {
    const target = e.target as HTMLElement;
    if (target.closest("textarea")) {
      return;
    }
    inputRef.current?.focus();
    inputRef.current?.setSelectionRange(
      inputRef.current.value.length,
      inputRef.current.value.length,
    );
  };

  const onMouseDown = (e: React.MouseEvent<HTMLDivElement>) => {
    const target = e.target as HTMLElement;
    if (target.closest("textarea")) {
      return;
    }
    e.stopPropagation();
    e.preventDefault();
  };

  const onKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => {
    const target = e.target as HTMLElement;
    if (target.closest("textarea")) {
      return;
    }
    if (e.key !== "Enter" && e.key !== " ") {
      return;
    }
    e.preventDefault();
    inputRef.current?.focus();
    inputRef.current?.setSelectionRange(
      inputRef.current.value.length,
      inputRef.current.value.length,
    );
  };

  return (
    <div className="flex w-full flex-col-reverse">
      <div
        data-testid="input-wrapper"
        className="flex w-full flex-col rounded-md border cursor-text border-input p-4 hover:border-muted-foreground focus:border-[1.75px] has-[:focus]:border-primary"
        onClick={onClick}
        onMouseDown={onMouseDown}
        onKeyDown={onKeyDown}
        role="button"
        tabIndex={0}
        aria-label="Focus chat input"
      >
        <TextAreaWrapper
          isBuilding={isBuilding}
          checkSendingOk={checkSendingOk}
          send={send}
          noInput={noInput}
          chatValue={chatValue}
          CHAT_INPUT_PLACEHOLDER={t("chat.inputPlaceholder")}
          inputRef={inputRef}
          files={files}
          isDragging={isDragging}
        />

        <div className={classNameFilePreview}>
          {files.map((file) => (
            <FilePreview
              error={file.error}
              file={file.file}
              loading={file.loading}
              key={file.id}
              onDelete={() => {
                handleDeleteFile(file);
              }}
            />
          ))}
        </div>
        <div className="flex w-full items-end justify-between">
          <div className={isBuilding ? "cursor-not-allowed" : ""}>
            {(!playgroundPage ||
              (playgroundPage && ENABLE_FILES_ON_PLAYGROUND)) && (
              <UploadFileButton
                isBuilding={isBuilding}
                fileInputRef={fileInputRef}
                handleFileChange={handleFileChange}
                handleButtonClick={handleButtonClick}
              />
            )}
          </div>
          <div className="flex items-center gap-2">
            {ENABLE_VOICE_ASSISTANT && config?.voice_mode_available && (
              <VoiceButton toggleRecording={() => setShowAudioInput(true)} />
            )}

            <div className={playgroundPage ? "ml-auto" : ""}>
              <ButtonSendWrapper
                send={send}
                noInput={noInput}
                chatValue={chatValue}
                files={files}
              />
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default InputWrapper;
