import {
  Component, h, useEffect, useEvent, useProp, useState,
} from "atomico";
import { KunCommentWithDate } from "@caedman/seek-api/build/api/get-comments-by-post";
import "../kun-button-puer/kun-button-puer";
import "../kun-input-comment/kun-input-comment";
import "../kun-child-comment-item-comp/kun-child-comment-item-comp";
import "../kun-image-or-default/kun-image-or-default";
import { Option } from "funfix";
import "../kun-icon/kun-icon";
import { reqLikeComment } from "@caedman/seek-api/build/api/req-like-comment";
import produce from "immer";
import {
  requestCreateComment,
  ReqCreateComment,
} from "@caedman/seek-api/build/api/create-comment";
import { KunCustomEvent } from "@caedman/spring/build/kun-custom-event";
import { getComponentOrDefine } from "../../hooks/aync-hook/redirect";
import { formatDate } from "./format-date";
import { execWithSixLoad } from "../../common/exec-confirm";
import { toastrMessage } from "../kun-editor/extenstions/extensions/exec-toastr";
import { getKunImageUrl } from "../kun-chat-message/kun-chat-message";

const style = `
  .kun-item-comment-bg {
    background: #f9f9f9;
  }
  
  .comment-max-width {
    max-width: calc(100% - 60px);
  }
`;

const KunItemComment = () => {
  const [itemProps, setItemProps] = useProp<KunCommentWithDate>("kunItem");

  const item = Option.of(itemProps).getOrElse({
    postId: "132",
    commentUserName: "蓝小球",
    createAt: "2020-06-07",
    commentId: "xxx",
    niceLookCount: 10,
    content: "加油啊，很不错",
    childComments: {
      records: [
        {
          createAt: "2020-06-07",
          content: "111",
          parentUserName: "ddd",
          commentUserName: "蓝小球",
        },
        {
          createAt: "2020-06-07",
          parentUserName: "ddd",
          content: "111",
          commentUserName: "蓝小球",
        },
        {
          parentUserName: "ddd",
          createAt: "2020-06-07",
          content: "111",
          commentUserName: "蓝小球",
        },
      ],
    },
  } as KunCommentWithDate);

  const [seriesIdProp] = useProp<string>("seriesId");
  const [currentCommentId] = useProp<string>("currentCommentId");

  const [like, setLike] = useState(false);

  const [showResponse, setShowResponse] = useState(false);

  const myRefresh = useEvent("MyRefresh", {
    composed: true,
    bubbles: true,
  });

  const toogleCurrentCommentEvent = useEvent("MyChange", {
    composed: true,
    bubbles: true,
  });

  useEffect(() => {
    if (item == null) {
      return;
    }
    if (currentCommentId === item.commentId) {
      setShowResponse(true);
    } else {
      setShowResponse(false);
    }
  }, [currentCommentId]);

  const toogleClick = (): void => {
    if (item?.commentId == null) {
      return;
    }
    setShowResponse(!showResponse);
    toogleCurrentCommentEvent(item.commentId);
  };

  const onCancel = (): void => {
    setShowResponse(false);
  };

  const onHandleComment = async (event: KunCustomEvent<{ text: string }>): Promise<void> => {
    const data: ReqCreateComment = {
      postId: item.postId,
      parentCommentId: item.commentId,
      firstCommentId: item.firstCommentId ?? item.commentId,
      seriesId: seriesIdProp,
      content: event.detail.text,
    } as unknown as ReqCreateComment;

    await execWithSixLoad(async () => {
      await requestCreateComment(data);
      myRefresh({});
      setShowResponse(false);
      toastrMessage("评论成功");
    });
  };

  const onHandleChildComment = async (event: KunCustomEvent<{ text: string }>): Promise<void> => {
    const data: ReqCreateComment = {
      postId: item.postId,
      parentCommentId: item.commentId,
      firstCommentId: item.firstCommentId ?? item.commentId,
      seriesId: seriesIdProp,
      content: event.detail.text,
    } as ReqCreateComment;

    await execWithSixLoad(async () => {
      await requestCreateComment(data);
      myRefresh({});
      setShowResponse(false);
      toastrMessage("评论成功");
    });
  };

  const toogle = async (event: Event): Promise<void> => {
    await execWithSixLoad(async () => {
      await reqLikeComment({
        feedId: String(item.postId),
        commentId: String(item.commentId),
        isLike: true,
      } as any);

      const newData = produce(item, (draft) => {
        draft.niceLookCount = like ? item.niceLookCount - 1 : item.niceLookCount + 1;
      });
      setItemProps(newData);
      setLike(!like);
    });
    event.preventDefault();
    event.stopPropagation();
  };
  return (
    <host>
      <style>{style}</style>

      <div className="flex justify-start w-full kun-item-comment-bg py-4 px-4">
        <div class="flex-none flex w-16">
          <kun-image-or-default url={getKunImageUrl(item.commentUserAvatarOpt)} width={56} height={56} />
        </div>

        <div class="flex flex-col px-2 flex-auto relative w-full comment-max-width">
          <div class="flex flex-col w-full">
            <div class="flex flex-row justify-between w-full">
              <span class="flex items-center">
                <span>{item.commentUserName ?? "用户"}</span>
              </span>

              <span className="ml-2">
                {
                  formatDate(item.createAt)
              }
              </span>
            </div>

            <div>
              <div class="flex flex-row">
                <div class="flex justify-start items-center">
                  {
                                !like && (
                                <kun-icon iconType="to-dian-zan" iconWidth={18} iconHeight={18} onclick={toogle} />
                                )
                            }
                  {
                                like && (
                                <kun-icon iconType="dianzan" iconWidth={18} iconHeight={18} onclick={toogle} />
                                )
                            }
                  {/* TODO  add number */}
                  {
                                item.niceLookCount > 0 && (
                                <span className="ml-1">{item.niceLookCount}</span>
                                )
                            }
                </div>
                <div>
                  <span onclick={toogleClick} class="cursor-pointer ml-2">回复</span>
                </div>
              </div>

              <div class="flex-auto flex flex-grow-0">
                {
                  showResponse && (
                  <kun-input-comment
                    onMySubmit={onHandleChildComment}
                    onMyCancel={onCancel}
                    className="w-full flex flex-auto box-border"
                  />
                  )
                }
              </div>

              <div>
                {
                  item.childComments.records.map((child) => (
                    <kun-child-comment-item-comp kunItem={child} seriesId={seriesIdProp} firstCommentId={item.parentCommentId} />
                  ))
                }
              </div>
            </div>
          </div>
        </div>
      </div>
    </host>
  );
};

KunItemComment.props = {
  isPractice: {
    type: Boolean,
  },
  currentCommentId: {
    type: String,
  },
  seriesId: {
    type: String,
  },
  kunItem: {
    type: Object,
    reflect: true,
  },
};

export default getComponentOrDefine("kun-item-comment", KunItemComment);
