"use client";
import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
import { createPostSchema, updatePostSchema } from '../../../schemas.mjs';
import { Button } from '../../../../../../../ui/src/components/button.mjs';
import { Form, FormField, FormItem, FormLabel, FormControl, FormMessage, FormDescription } from '../../../../../../../ui/src/components/form.mjs';
import { Input } from '../../../../../../../ui/src/components/input.mjs';
import { Switch } from '../../../../../../../ui/src/components/switch.mjs';
import { Textarea } from '../../../../../../../ui/src/components/textarea.mjs';
import { useCreatePost, useSuspensePost, useUpdatePost, useDeletePost } from '../../hooks/blog-hooks.mjs';
import { slugify } from '../../../utils.mjs';
import { AlertDialog, AlertDialogTrigger, AlertDialogContent, AlertDialogHeader, AlertDialogTitle, AlertDialogDescription, AlertDialogFooter, AlertDialogCancel, AlertDialogAction } from '../../../../../../../ui/src/components/alert-dialog.mjs';
import { zodResolver } from '@hookform/resolvers/zod';
import { Loader2 } from 'lucide-react';
import { memo, useState, useEffect, useMemo, Suspense, lazy } from 'react';
import { useForm } from 'react-hook-form';
import { toast } from 'sonner';
import { FeaturedImageField } from './image-field.mjs';
import { BLOG_LOCALIZATION } from '../../localization/index.mjs';
import { usePluginOverrides } from '@btst/stack/context';
import { EmptyList } from '../shared/empty-list.mjs';
import { TagsMultiSelect } from './tags-multiselect.mjs';

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

export { AddPostForm, EditPostForm };
