import { Button, Form, TextArea } from "@nutui/nutui-react-taro";
import { View } from "@tarojs/components";
import { useLayoutEffect, useRef, useState, useEffect } from "react";
import { createCommentApi } from "../../api/comment";
import Taro from "@tarojs/taro";

const CommentInput = ({ postId, parentCommentId, onClose, onOK }) => {
  const textAreaRef = useRef<any>(null);
  const [form] = Form.useForm();
  const [keyboardHeight, setKeyboardHeight] = useState(0);
  const [isInputFocused, setIsInputFocused] = useState(false);
  const [isInitialized, setIsInitialized] = useState(false);

  // 当评论输入框显示时，自动聚焦
  useLayoutEffect(() => {
    const timer = setTimeout(() => {
      if (
        textAreaRef.current &&
        typeof textAreaRef.current.focus === "function"
      ) {
        try {
          textAreaRef.current.focus();
        } catch (error) {
          console.log("焦点设置失败:", error);
        }
      }
    }, 300);
    return () => clearTimeout(timer);
  }, []);

  // 发送评论
  const sendComment = (data) => {
    const params = {
      post_id: postId,
      parent_comment_id: parentCommentId,
      content: data.content,
    };
    createCommentApi(params).then((res: any) => {
      if (res.code === 200) {
        onOK(false);
        form.resetFields();
      }
    });
  };

  return (
    <View
      className="pd-[100px] fixed left-[0] right-[0] z-[1000] text-[14px] text-[#949494] bg-[#f8f8f8] rounded-[10rpx]"
      style={{
        bottom: isInputFocused && isInitialized ? `${keyboardHeight}px` : "0px",
      }}
    >
      {/* 使用原生 Taro Textarea 作为备用方案 */}
      <Form form={form} onFinish={(data) => sendComment(data)}>
        <Form.Item name="content">
          <TextArea
            id="comment-textarea"
            placeholder="说点什么..."
            ref={textAreaRef}
            showConfirmBar={false}
            auto-focus
            auto-height
            fixed
            style={{
              backgroundColor: "#f5f5f5",
              borderRadius: "20rpx",
              width: "calc(100% - 40rpx)",
              fontSize: "28rpx",
              padding: "20rpx",
            }}
            onFocus={() => {
              setIsInputFocused(true);
              // setIsInitialized(true);
              // setKeyboardHeight(300); // 使用估算的键盘高度
            }}
            onBlur={() => {
              setIsInputFocused(false);
              setKeyboardHeight(0);
              onClose(false);
            }}
          />
        </Form.Item>
        <Form.Item>
          <View className="flex justify-end">
            <Button
              type="primary"
              onClick={() => {
                form.submit();
              }}
            >
              发送
            </Button>
          </View>
        </Form.Item>
      </Form>
    </View>
  );
};

export default CommentInput;
