"use client";
'use strict';

const jsxRuntime = require('react/jsx-runtime');
const React = require('react');
const button = require('../../../../../../ui/src/components/button.cjs');
const textarea = require('../../../../../../ui/src/components/textarea.cjs');
const LucideIcons = require('lucide-react');
const utils = require('../../../../../../ui/src/lib/utils.cjs');
const sonner = require('sonner');
const context = require('@btst/stack/context');
const overrides = require('../overrides.cjs');
const index = require('../localization/index.cjs');

const MAX_FILE_SIZE = 10 * 1024 * 1024;
function ChatInput({
  input = "",
  handleInputChange,
  handleSubmit,
  isLoading,
  placeholder,
  variant = "default",
  onFilesAttached,
  attachedFiles: controlledFiles
}) {
  const {
    uploadFile,
    localization: customLocalization,
    mode,
    allowedFileTypes
  } = context.usePluginOverrides(
    "ai-chat",
    {}
  );
  const localization = { ...index.AI_CHAT_LOCALIZATION, ...customLocalization };
  const fileInputRef = React.useRef(null);
  const [internalFiles, setInternalFiles] = React.useState([]);
  const [isUploading, setIsUploading] = React.useState(false);
  const attachedFiles = controlledFiles ?? internalFiles;
  const isControlled = controlledFiles !== void 0;
  const addFile = (file) => {
    if (isControlled && onFilesAttached) {
      onFilesAttached([...attachedFiles, file]);
    } else {
      setInternalFiles((prev) => [...prev, file]);
    }
  };
  const removeFileAtIndex = (index) => {
    if (isControlled && onFilesAttached) {
      onFilesAttached(attachedFiles.filter((_, i) => i !== index));
    } else {
      setInternalFiles((prev) => prev.filter((_, i) => i !== index));
    }
  };
  const isCompact = variant === "compact";
  const isPublicMode = mode === "public";
  const effectiveAllowedTypes = allowedFileTypes ?? overrides.DEFAULT_ALLOWED_FILE_TYPES;
  const acceptString = React.useMemo(() => {
    if (effectiveAllowedTypes.length === 0) return "";
    const mimeTypes = effectiveAllowedTypes.flatMap(
      (type) => overrides.FILE_TYPE_MIME_MAP[type] || []
    );
    return mimeTypes.join(",");
  }, [effectiveAllowedTypes]);
  const canUploadFiles = !isPublicMode && typeof uploadFile === "function" && effectiveAllowedTypes.length > 0;
  const handleKeyDown = (e) => {
    if (e.key === "Enter" && !e.shiftKey) {
      e.preventDefault();
      handleSubmit(
        e,
        attachedFiles.length > 0 ? attachedFiles : void 0
      );
      if (!controlledFiles) {
        setInternalFiles([]);
      }
    }
  };
  const handleFileUpload = async (event) => {
    const file = event.target.files?.[0];
    if (!file) return;
    if (file.size > MAX_FILE_SIZE) {
      sonner.toast.error(localization.FILE_UPLOAD_ERROR_TOO_LARGE);
      return;
    }
    if (uploadFile) {
      try {
        setIsUploading(true);
        const url = await uploadFile(file);
        addFile({ url, mediaType: file.type, filename: file.name });
        sonner.toast.success(localization.FILE_UPLOAD_SUCCESS);
      } catch (error) {
        console.error("Failed to upload file:", error);
        sonner.toast.error(localization.FILE_UPLOAD_FAILURE);
      } finally {
        setIsUploading(false);
      }
    } else {
      setIsUploading(true);
      const reader = new FileReader();
      reader.onload = (e) => {
        const dataUrl = e.target?.result;
        addFile({ url: dataUrl, mediaType: file.type, filename: file.name });
        setIsUploading(false);
      };
      reader.onerror = () => {
        sonner.toast.error(localization.FILE_UPLOAD_FAILURE);
        setIsUploading(false);
      };
      reader.readAsDataURL(file);
    }
    if (fileInputRef.current) {
      fileInputRef.current.value = "";
    }
  };
  const removeFile = (index) => {
    removeFileAtIndex(index);
  };
  const handleFormSubmit = (e) => {
    handleSubmit(e, attachedFiles.length > 0 ? attachedFiles : void 0);
    if (!controlledFiles) {
      setInternalFiles([]);
    }
  };
  const isImageFile = (mediaType) => mediaType.startsWith("image/");
  return /* @__PURE__ */ jsxRuntime.jsxs("form", { onSubmit: handleFormSubmit, className: "space-y-2", children: [
    attachedFiles.length > 0 && /* @__PURE__ */ jsxRuntime.jsx("div", { className: "flex flex-wrap gap-2", children: attachedFiles.map((file, index) => /* @__PURE__ */ jsxRuntime.jsxs(
      "div",
      {
        className: "relative group rounded-lg overflow-hidden border",
        children: [
          isImageFile(file.mediaType) ? (
            // Image preview
            /* @__PURE__ */ jsxRuntime.jsx(
              "img",
              {
                src: file.url,
                alt: file.filename,
                className: "h-16 w-16 object-cover"
              }
            )
          ) : (
            // File preview with icon
            /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "w-32 flex items-center gap-2 p-2 bg-muted", children: [
              /* @__PURE__ */ jsxRuntime.jsx(LucideIcons.FileText, { className: "h-5 w-5 shrink-0 text-muted-foreground" }),
              /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-xs truncate", title: file.filename, children: file.filename })
            ] })
          ),
          /* @__PURE__ */ jsxRuntime.jsx(
            "button",
            {
              type: "button",
              onClick: () => removeFile(index),
              className: "absolute top-0.5 right-0.5 p-0.5 rounded-full bg-background/80 opacity-0 group-hover:opacity-100 transition-opacity",
              children: /* @__PURE__ */ jsxRuntime.jsx(LucideIcons.X, { className: "h-3 w-3" })
            }
          )
        ]
      },
      index
    )) }),
    /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "relative flex items-center gap-2", children: [
      canUploadFiles && /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
        /* @__PURE__ */ jsxRuntime.jsx(
          "input",
          {
            ref: fileInputRef,
            type: "file",
            accept: acceptString,
            onChange: handleFileUpload,
            className: "hidden"
          }
        ),
        /* @__PURE__ */ jsxRuntime.jsx(
          button.Button,
          {
            type: "button",
            variant: "ghost",
            size: "icon",
            onClick: () => fileInputRef.current?.click(),
            disabled: isLoading || isUploading,
            className: utils.cn("shrink-0", isCompact ? "h-8 w-8" : "h-9 w-9"),
            "aria-label": localization.FILE_UPLOAD_BUTTON,
            children: isUploading ? /* @__PURE__ */ jsxRuntime.jsx(LucideIcons.Loader2, { className: "h-4 w-4 animate-spin" }) : /* @__PURE__ */ jsxRuntime.jsx(LucideIcons.Paperclip, { className: "h-4 w-4" })
          }
        )
      ] }),
      /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "relative flex-1 min-w-0", children: [
        /* @__PURE__ */ jsxRuntime.jsx(
          textarea.Textarea,
          {
            value: input,
            onChange: handleInputChange,
            onKeyDown: handleKeyDown,
            placeholder: placeholder || localization.CHAT_PLACEHOLDER,
            className: utils.cn(
              "resize-none pr-12 max-w-full",
              isCompact ? "min-h-[40px] max-h-[120px] py-2" : "min-h-[50px] max-h-[200px] py-3"
            ),
            rows: 1
          }
        ),
        /* @__PURE__ */ jsxRuntime.jsx(
          button.Button,
          {
            type: "submit",
            size: "icon",
            disabled: isLoading || !input?.trim() && attachedFiles.length === 0,
            className: utils.cn(
              "absolute right-2 bottom-2",
              isCompact ? "h-7 w-7" : "h-8 w-8"
            ),
            "aria-label": localization.CHAT_SEND_BUTTON,
            children: /* @__PURE__ */ jsxRuntime.jsx(LucideIcons.Send, { className: utils.cn(isCompact ? "h-3.5 w-3.5" : "h-4 w-4") })
          }
        )
      ] })
    ] })
  ] });
}

exports.ChatInput = ChatInput;
