"use client";
'use strict';

const jsxRuntime = require('react/jsx-runtime');
const schemas = require('../../../schemas.cjs');
const button = require('../../../../../../../ui/src/components/button.cjs');
const form = require('../../../../../../../ui/src/components/form.cjs');
const input = require('../../../../../../../ui/src/components/input.cjs');
const _switch = require('../../../../../../../ui/src/components/switch.cjs');
const textarea = require('../../../../../../../ui/src/components/textarea.cjs');
const blogHooks = require('../../hooks/blog-hooks.cjs');
const utils = require('../../../utils.cjs');
const alertDialog = require('../../../../../../../ui/src/components/alert-dialog.cjs');
const zod = require('@hookform/resolvers/zod');
const LucideIcons = require('lucide-react');
const React = require('react');
const reactHookForm = require('react-hook-form');
const sonner = require('sonner');
const imageField = require('./image-field.cjs');
const index = require('../../localization/index.cjs');
const context = require('@btst/stack/context');
const emptyList = require('../shared/empty-list.cjs');
const tagsMultiselect = require('./tags-multiselect.cjs');

const MarkdownEditor = React.lazy(
  () => import('./markdown-editor-with-overrides.cjs').then((module) => ({
    default: module.MarkdownEditorWithOverrides
  }))
);
function PostFormBody({
  form: form$1,
  onSubmit,
  submitLabel,
  onCancel,
  disabled,
  errorMessage,
  setFeaturedImageUploading,
  initialSlugTouched = false
}) {
  const { localization } = context.usePluginOverrides("blog", {
    localization: index.BLOG_LOCALIZATION
  });
  const [slugTouched, setSlugTouched] = React.useState(initialSlugTouched);
  const nameTitle = "title";
  const nameSlug = "slug";
  const nameExcerpt = "excerpt";
  const nameImage = "image";
  const nameTags = "tags";
  const nameContent = "content";
  const namePublished = "published";
  return /* @__PURE__ */ jsxRuntime.jsx(form.Form, { ...form$1, children: /* @__PURE__ */ jsxRuntime.jsxs("form", { className: "w-full space-y-4", onSubmit: form$1.handleSubmit(onSubmit), children: [
    errorMessage && /* @__PURE__ */ jsxRuntime.jsx("div", { className: "rounded-md border border-red-200 bg-red-50 p-3 text-red-600 text-sm", children: errorMessage }),
    /* @__PURE__ */ jsxRuntime.jsx(
      form.FormField,
      {
        control: form$1.control,
        name: nameTitle,
        render: ({ field }) => /* @__PURE__ */ jsxRuntime.jsxs(form.FormItem, { children: [
          /* @__PURE__ */ jsxRuntime.jsxs(form.FormLabel, { children: [
            localization.BLOG_FORMS_TITLE_LABEL,
            /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-destructive", children: localization.BLOG_FORMS_REQUIRED_ASTERISK })
          ] }),
          /* @__PURE__ */ jsxRuntime.jsx(form.FormControl, { children: /* @__PURE__ */ jsxRuntime.jsx(
            input.Input,
            {
              placeholder: localization.BLOG_FORMS_TITLE_PLACEHOLDER,
              ...field,
              value: String(field.value ?? ""),
              onChange: (e) => {
                const newTitle = e.target.value;
                field.onChange(e);
                if (!slugTouched) {
                  form$1.setValue(nameSlug, utils.slugify(newTitle));
                }
              }
            }
          ) }),
          /* @__PURE__ */ jsxRuntime.jsx(form.FormMessage, {})
        ] })
      }
    ),
    /* @__PURE__ */ jsxRuntime.jsx(
      form.FormField,
      {
        control: form$1.control,
        name: nameSlug,
        render: ({ field }) => {
          const currentTitle = form$1.getValues(nameTitle);
          const autoGeneratedSlug = utils.slugify(String(currentTitle ?? ""));
          const currentSlug = String(field.value ?? "");
          return /* @__PURE__ */ jsxRuntime.jsxs(form.FormItem, { children: [
            /* @__PURE__ */ jsxRuntime.jsx(form.FormLabel, { children: localization.BLOG_FORMS_SLUG_LABEL }),
            /* @__PURE__ */ jsxRuntime.jsx(form.FormControl, { children: /* @__PURE__ */ jsxRuntime.jsx(
              input.Input,
              {
                placeholder: localization.BLOG_FORMS_SLUG_PLACEHOLDER,
                ...field,
                value: currentSlug,
                onChange: (e) => {
                  const newSlug = e.target.value;
                  field.onChange(e);
                  if (newSlug !== autoGeneratedSlug) {
                    setSlugTouched(true);
                  }
                }
              }
            ) }),
            /* @__PURE__ */ jsxRuntime.jsx(form.FormMessage, {})
          ] });
        }
      }
    ),
    /* @__PURE__ */ jsxRuntime.jsx(
      form.FormField,
      {
        control: form$1.control,
        name: nameExcerpt,
        render: ({ field }) => /* @__PURE__ */ jsxRuntime.jsxs(form.FormItem, { className: "flex flex-col", children: [
          /* @__PURE__ */ jsxRuntime.jsxs(form.FormLabel, { children: [
            localization.BLOG_FORMS_EXCERPT_LABEL,
            /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-destructive", children: localization.BLOG_FORMS_REQUIRED_ASTERISK })
          ] }),
          /* @__PURE__ */ jsxRuntime.jsx(form.FormControl, { children: /* @__PURE__ */ jsxRuntime.jsx(
            textarea.Textarea,
            {
              placeholder: localization.BLOG_FORMS_EXCERPT_PLACEHOLDER,
              className: "min-h-20",
              value: String(field.value ?? ""),
              onChange: field.onChange
            }
          ) }),
          /* @__PURE__ */ jsxRuntime.jsx(form.FormDescription, {}),
          /* @__PURE__ */ jsxRuntime.jsx(form.FormMessage, {})
        ] })
      }
    ),
    /* @__PURE__ */ jsxRuntime.jsx(
      form.FormField,
      {
        control: form$1.control,
        name: nameImage,
        render: ({ field }) => /* @__PURE__ */ jsxRuntime.jsx(
          imageField.FeaturedImageField,
          {
            isRequired: false,
            value: String(field.value ?? ""),
            onChange: field.onChange,
            setFeaturedImageUploading
          }
        )
      }
    ),
    /* @__PURE__ */ jsxRuntime.jsx(
      form.FormField,
      {
        control: form$1.control,
        name: nameTags,
        render: ({ field }) => /* @__PURE__ */ jsxRuntime.jsxs(form.FormItem, { className: "flex flex-col", children: [
          /* @__PURE__ */ jsxRuntime.jsx(form.FormLabel, { children: localization.BLOG_FORMS_TAGS_LABEL }),
          /* @__PURE__ */ jsxRuntime.jsx(form.FormControl, { children: /* @__PURE__ */ jsxRuntime.jsx(
            tagsMultiselect.TagsMultiSelect,
            {
              value: Array.isArray(field.value) ? field.value : [],
              onChange: field.onChange,
              placeholder: localization.BLOG_FORMS_TAGS_PLACEHOLDER
            }
          ) }),
          /* @__PURE__ */ jsxRuntime.jsx(form.FormDescription, {}),
          /* @__PURE__ */ jsxRuntime.jsx(form.FormMessage, {})
        ] })
      }
    ),
    /* @__PURE__ */ jsxRuntime.jsx(
      form.FormField,
      {
        control: form$1.control,
        name: nameContent,
        render: ({ field }) => /* @__PURE__ */ jsxRuntime.jsxs(form.FormItem, { className: "flex flex-col", children: [
          /* @__PURE__ */ jsxRuntime.jsxs(form.FormLabel, { children: [
            localization.BLOG_FORMS_CONTENT_LABEL,
            /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-destructive", children: localization.BLOG_FORMS_REQUIRED_ASTERISK })
          ] }),
          /* @__PURE__ */ jsxRuntime.jsx(form.FormControl, { children: /* @__PURE__ */ jsxRuntime.jsx(
            React.Suspense,
            {
              fallback: /* @__PURE__ */ jsxRuntime.jsx("div", { className: "min-h-80 max-w-full border-input rounded-md border shadow-xs flex items-center justify-center bg-muted/50", children: /* @__PURE__ */ jsxRuntime.jsx(LucideIcons.Loader2, { className: "h-6 w-6 animate-spin text-muted-foreground" }) }),
              children: /* @__PURE__ */ jsxRuntime.jsx(
                MarkdownEditor,
                {
                  className: "min-h-80 max-w-full border-input rounded-md border shadow-xs",
                  value: typeof field.value === "string" ? field.value : "",
                  onChange: (content) => {
                    field.onChange(content);
                  }
                }
              )
            }
          ) }),
          /* @__PURE__ */ jsxRuntime.jsx(form.FormDescription, {}),
          /* @__PURE__ */ jsxRuntime.jsx(form.FormMessage, {})
        ] })
      }
    ),
    /* @__PURE__ */ jsxRuntime.jsx(
      form.FormField,
      {
        control: form$1.control,
        name: namePublished,
        render: ({ field }) => /* @__PURE__ */ jsxRuntime.jsxs(form.FormItem, { className: "flex flex-row items-center justify-between rounded-lg border p-3 shadow-sm", children: [
          /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-0.5", children: [
            /* @__PURE__ */ jsxRuntime.jsx(form.FormLabel, { children: localization.BLOG_FORMS_PUBLISHED_LABEL }),
            /* @__PURE__ */ jsxRuntime.jsx(form.FormDescription, { children: localization.BLOG_FORMS_PUBLISHED_DESCRIPTION })
          ] }),
          /* @__PURE__ */ jsxRuntime.jsx(form.FormControl, { children: /* @__PURE__ */ jsxRuntime.jsx(
            _switch.Switch,
            {
              checked: !!field.value,
              onCheckedChange: field.onChange
            }
          ) })
        ] })
      }
    ),
    /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex gap-2 pt-4", children: [
      /* @__PURE__ */ jsxRuntime.jsx(button.Button, { type: "submit", disabled, children: submitLabel }),
      /* @__PURE__ */ jsxRuntime.jsx(
        button.Button,
        {
          variant: "outline",
          onClick: onCancel,
          disabled,
          type: "button",
          children: localization.BLOG_FORMS_CANCEL_BUTTON
        }
      )
    ] })
  ] }) });
}
const CustomPostCreateSchema = schemas.createPostSchema.omit({
  createdAt: true,
  updatedAt: true,
  publishedAt: true
});
const CustomPostUpdateSchema = schemas.updatePostSchema.omit({
  id: true,
  createdAt: true,
  updatedAt: true,
  publishedAt: true
});
const addPostFormPropsAreEqual = (prevProps, nextProps) => {
  if (prevProps.onClose !== nextProps.onClose) return false;
  if (prevProps.onSuccess !== nextProps.onSuccess) return false;
  if (prevProps.onFormReady !== nextProps.onFormReady) return false;
  return true;
};
const AddPostFormComponent = ({
  onClose,
  onSuccess,
  onFormReady
}) => {
  const [featuredImageUploading, setFeaturedImageUploading] = React.useState(false);
  const { localization } = context.usePluginOverrides("blog", {
    localization: index.BLOG_LOCALIZATION
  });
  const schema = CustomPostCreateSchema;
  const {
    mutateAsync: createPost,
    isPending: isCreatingPost,
    error: createPostError
  } = blogHooks.useCreatePost();
  const onSubmit = async (data) => {
    const slug = data.slug || utils.slugify(data.title);
    const createdPost = await createPost({
      title: data.title,
      content: data.content,
      excerpt: data.excerpt ?? "",
      slug,
      published: data.published ?? false,
      publishedAt: data.published ? /* @__PURE__ */ new Date() : void 0,
      image: data.image,
      tags: data.tags || []
    });
    sonner.toast.success(localization.BLOG_FORMS_TOAST_CREATE_SUCCESS);
    onSuccess({ published: createdPost?.published ?? false });
  };
  const form = reactHookForm.useForm({
    resolver: zod.zodResolver(schema),
    defaultValues: {
      title: "",
      content: "",
      excerpt: "",
      slug: void 0,
      published: false,
      image: "",
      tags: []
    }
  });
  React.useEffect(() => {
    onFormReady?.(form);
  }, []);
  return /* @__PURE__ */ jsxRuntime.jsx(
    PostFormBody,
    {
      form,
      onSubmit,
      submitLabel: isCreatingPost ? localization.BLOG_FORMS_SUBMIT_CREATE_PENDING : localization.BLOG_FORMS_SUBMIT_CREATE_IDLE,
      onCancel: onClose,
      disabled: isCreatingPost || featuredImageUploading,
      errorMessage: createPostError?.message,
      setFeaturedImageUploading
    }
  );
};
const AddPostForm = React.memo(AddPostFormComponent, addPostFormPropsAreEqual);
const editPostFormPropsAreEqual = (prevProps, nextProps) => {
  if (prevProps.postSlug !== nextProps.postSlug) return false;
  if (prevProps.onClose !== nextProps.onClose) return false;
  if (prevProps.onSuccess !== nextProps.onSuccess) return false;
  if (prevProps.onDelete !== nextProps.onDelete) return false;
  if (prevProps.onFormReady !== nextProps.onFormReady) return false;
  return true;
};
const EditPostFormComponent = ({
  postSlug,
  onClose,
  onSuccess,
  onDelete,
  onFormReady
}) => {
  const [featuredImageUploading, setFeaturedImageUploading] = React.useState(false);
  const [deleteDialogOpen, setDeleteDialogOpen] = React.useState(false);
  const { localization } = context.usePluginOverrides("blog", {
    localization: index.BLOG_LOCALIZATION
  });
  const { post } = blogHooks.useSuspensePost(postSlug);
  const initialData = React.useMemo(() => {
    if (!post) return {};
    return {
      title: post.title,
      content: post.content,
      excerpt: post.excerpt,
      slug: post.slug,
      published: post.published,
      image: post.image || "",
      tags: post.tags.map((tag) => ({
        id: tag.id,
        name: tag.name,
        slug: tag.slug
      }))
    };
  }, [post]);
  const schema = CustomPostUpdateSchema;
  const {
    mutateAsync: updatePost,
    isPending: isUpdatingPost,
    error: updatePostError
  } = blogHooks.useUpdatePost();
  const { mutateAsync: deletePost, isPending: isDeletingPost } = blogHooks.useDeletePost();
  const onSubmit = async (data) => {
    const updatedPost = await updatePost({
      id: post.id,
      data: {
        id: post.id,
        title: data.title,
        content: data.content,
        excerpt: data.excerpt ?? "",
        slug: data.slug,
        published: data.published ?? false,
        publishedAt: data.published && !post?.published ? /* @__PURE__ */ new Date() : post?.publishedAt ? new Date(post.publishedAt) : void 0,
        image: data.image,
        tags: data.tags || []
      }
    });
    sonner.toast.success(localization.BLOG_FORMS_TOAST_UPDATE_SUCCESS);
    onSuccess({
      slug: updatedPost?.slug ?? "",
      published: updatedPost?.published ?? false
    });
  };
  const handleDelete = async () => {
    if (!post?.id) return;
    await deletePost({ id: post.id });
    sonner.toast.success(localization.BLOG_FORMS_TOAST_DELETE_SUCCESS);
    setDeleteDialogOpen(false);
    if (onDelete) {
      onDelete();
    } else {
      onClose();
    }
  };
  const form = reactHookForm.useForm({
    resolver: zod.zodResolver(schema),
    defaultValues: {
      title: "",
      content: "",
      excerpt: "",
      slug: "",
      published: false,
      image: "",
      tags: []
    },
    values: initialData
  });
  React.useEffect(() => {
    onFormReady?.(form);
  }, []);
  if (!post) {
    return /* @__PURE__ */ jsxRuntime.jsx(emptyList.EmptyList, { message: localization.BLOG_PAGE_NOT_FOUND_DESCRIPTION });
  }
  return /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
    /* @__PURE__ */ jsxRuntime.jsx(
      PostFormBody,
      {
        form,
        onSubmit,
        submitLabel: isUpdatingPost ? localization.BLOG_FORMS_SUBMIT_UPDATE_PENDING : localization.BLOG_FORMS_SUBMIT_UPDATE_IDLE,
        onCancel: onClose,
        disabled: isUpdatingPost || featuredImageUploading,
        errorMessage: updatePostError?.message,
        setFeaturedImageUploading,
        initialSlugTouched: !!post?.slug
      }
    ),
    /* @__PURE__ */ jsxRuntime.jsx("div", { className: "w-full", children: /* @__PURE__ */ jsxRuntime.jsxs(alertDialog.AlertDialog, { open: deleteDialogOpen, onOpenChange: setDeleteDialogOpen, children: [
      /* @__PURE__ */ jsxRuntime.jsx(alertDialog.AlertDialogTrigger, { asChild: true, children: /* @__PURE__ */ jsxRuntime.jsx(
        button.Button,
        {
          variant: "destructive",
          type: "button",
          disabled: isUpdatingPost || featuredImageUploading || isDeletingPost,
          className: "mt-4",
          children: localization.BLOG_FORMS_DELETE_BUTTON
        }
      ) }),
      /* @__PURE__ */ jsxRuntime.jsxs(alertDialog.AlertDialogContent, { children: [
        /* @__PURE__ */ jsxRuntime.jsxs(alertDialog.AlertDialogHeader, { children: [
          /* @__PURE__ */ jsxRuntime.jsx(alertDialog.AlertDialogTitle, { children: localization.BLOG_FORMS_DELETE_DIALOG_TITLE }),
          /* @__PURE__ */ jsxRuntime.jsx(alertDialog.AlertDialogDescription, { children: localization.BLOG_FORMS_DELETE_DIALOG_DESCRIPTION })
        ] }),
        /* @__PURE__ */ jsxRuntime.jsxs(alertDialog.AlertDialogFooter, { children: [
          /* @__PURE__ */ jsxRuntime.jsx(alertDialog.AlertDialogCancel, { disabled: isDeletingPost, children: localization.BLOG_FORMS_DELETE_DIALOG_CANCEL }),
          /* @__PURE__ */ jsxRuntime.jsx(
            alertDialog.AlertDialogAction,
            {
              onClick: (e) => {
                e.preventDefault();
                void handleDelete();
              },
              disabled: isDeletingPost,
              children: isDeletingPost ? localization.BLOG_FORMS_DELETE_PENDING : localization.BLOG_FORMS_DELETE_DIALOG_CONFIRM
            }
          )
        ] })
      ] })
    ] }) })
  ] });
};
const EditPostForm = React.memo(
  EditPostFormComponent,
  editPostFormPropsAreEqual
);

exports.AddPostForm = AddPostForm;
exports.EditPostForm = EditPostForm;
