/**
 * Copyright (c) 2023-present Plane Software, Inc. and contributors
 * SPDX-License-Identifier: AGPL-3.0-only
 * See the LICENSE file for details.
 */

import { useState } from "react";
import { observer } from "mobx-react";
import { useTranslation } from "@plane/i18n";
import { Button } from "@plane/propel/button";
import { TOAST_TYPE, setToast } from "@plane/propel/toast";
import { TextArea } from "@plane/ui";
import { useProjectExternalContours } from "@/hooks/store/use-project-external-contours";

type Props = {
  workspaceSlug: string;
  sourceProjectId: string;
  requestId: string;
};

export const ExternalContoursSourceReplyBox = observer(function ExternalContoursSourceReplyBox(props: Props) {
  const { workspaceSlug, sourceProjectId, requestId } = props;
  const { t } = useTranslation();
  const { loader, replyToRequest } = useProjectExternalContours();
  const [comment, setComment] = useState("");

  const isSubmitting = loader === "mutation-loading";

  const handleSubmit = async () => {
    if (!comment.trim() || isSubmitting) return;

    try {
      await replyToRequest(workspaceSlug, sourceProjectId, requestId, comment.trim());
      setComment("");
      setToast({
        type: TOAST_TYPE.SUCCESS,
        title: t("success"),
        message: t("external_contours_page.reply.success"),
      });
    } catch (error: any) {
      setToast({
        type: TOAST_TYPE.ERROR,
        title: t("error"),
        message: error?.error || t("external_contours_page.reply.error"),
      });
    }
  };

  return (
    <div className="nodedc-external-section space-y-3 px-4 py-4">
      <div className="text-body-sm-medium">{t("external_contours_page.reply.title")}</div>
      <TextArea
        value={comment}
        onChange={(e) => setComment(e.target.value)}
        rows={4}
        placeholder={t("external_contours_page.reply.placeholder")}
        disabled={isSubmitting}
        className="nodedc-modal-input min-h-[7rem] resize-none !rounded-[1.2rem] !border-0 !bg-white/4"
      />
      <div className="flex justify-end">
        <Button
          variant="primary"
          onClick={handleSubmit}
          disabled={isSubmitting || !comment.trim()}
          className="nodedc-modal-primary-button"
        >
          {t("external_contours_page.reply.submit")}
        </Button>
      </div>
    </div>
  );
});
