import { Controller, useForm } from "react-hook-form";
import * as z from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import { Input } from "@nextui-org/input";
import JoditEditor from "jodit-react";
import { useEffect, useRef, useState } from "react";
import {
  getDetailArticle,
  updateManualArticle,
} from "@/service/generate-article";
import { Button } from "@nextui-org/button";
import Swal from "sweetalert2";
import withReactContent from "sweetalert2-react-content";
import { useRouter } from "next/navigation";
import { error, loading } from "@/config/swal";

const formSchema = z.object({
  mainKeyword: z.string().min(2, {
    message: "Keyword must be at least 2 characters.",
  }),
  title: z.string().min(2, {
    message: "Title must be at least 2 characters.",
  }),
  additionalKeyword: z.string().min(2, {
    message: "Additional Keyword must be at least 2 characters.",
  }),
  metaTitle: z.string().min(2, {
    message: "Meta Title must be at least 2 characters.",
  }),
  metaDescription: z.string().min(2, {
    message: "Meta Description must be at least 2 characters.",
  }),
  articleBody: z.string().min(2, {
    message: "Article Body must be at least 2 characters.",
  }),
});

export default function EditGeneratedArticleContent(props: { id: string }) {
  const MySwal = withReactContent(Swal);
  const router = useRouter();
  const { id } = props;
  const editor = useRef(null);

  const formOptions = { resolver: zodResolver(formSchema) };
  type UserSettingSchema = z.infer<typeof formSchema>;
  const {
    control,
    handleSubmit,
    formState: { errors },
    setValue,
  } = useForm<UserSettingSchema>(formOptions);

  useEffect(() => {
    getArticleDetail();
  }, [id]);

  const getArticleDetail = async () => {
    const res = await getDetailArticle(Number(id));
    // const data = res?.data?.data?.articleBody;
    const data = res?.data?.data;
    setValue("title", data?.title);
    setValue("mainKeyword", data?.mainKeyword);
    setValue("additionalKeyword", data?.additionalKeywords);
    setValue("metaTitle", data?.metaTitle);
    setValue("metaDescription", data?.metaDescription);
    setValue("articleBody", data?.articleBody);
  };

  const onSubmit = async (values: z.infer<typeof formSchema>) => {
    const request = {
      id: Number(id),
      title: values.title,
      articleBody: values.articleBody,
      metaDescription: values.metaDescription,
      metaTitle: values.metaTitle,
      createdBy: "123123",
    };
    console.log("request", request);
    loading();
    const res = await updateManualArticle(request);
    if (res.error) {
      error(res.message);
      return false;
    }
    close();
    successSubmit("/admin/article/generate");
  };

  function successSubmit(redirect: string) {
    MySwal.fire({
      title: "Success",
      icon: "success",
      confirmButtonColor: "#3085d6",
      confirmButtonText: "OK",
    }).then((result) => {
      if (result.isConfirmed) {
        router.push(redirect);
      }
    });
  }

  return (
    <form className="flex flex-col gap-4" onSubmit={handleSubmit(onSubmit)}>
      <Controller
        control={control}
        name="title"
        render={({ field: { onChange, value } }) => (
          <Input
            type="text"
            id="title"
            placeholder="Title"
            label="Title"
            value={value}
            onChange={onChange}
            labelPlacement="outside"
            className="w-full"
            variant="bordered"
          />
        )}
      />
      {errors.title && (
        <p className="text-red-400 text-sm">{errors.title?.message}</p>
      )}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
        <div className="flex flex-col">
          <Controller
            control={control}
            name="mainKeyword"
            render={({ field: { onChange, value } }) => (
              <Input
                type="text"
                id="mainKeyword"
                placeholder="Keyword"
                label="Keyword"
                value={value}
                onChange={onChange}
                labelPlacement="outside"
                className="w-full"
                variant="bordered"
              />
            )}
          />
          {errors.mainKeyword?.message && (
            <p className="text-red-400 text-sm">
              {errors.mainKeyword?.message}
            </p>
          )}
        </div>
        <div className="flex flex-col">
          <Controller
            control={control}
            name="additionalKeyword"
            render={({ field: { onChange, value } }) => (
              <Input
                type="text"
                id="additionalKeyword"
                placeholder="Additional Keyword"
                label="Additional Keyword"
                value={value}
                onChange={onChange}
                labelPlacement="outside"
                className="w-full"
                variant="bordered"
              />
            )}
          />
          {errors.additionalKeyword?.message && (
            <p className="text-red-400 text-sm">
              {errors.additionalKeyword?.message}
            </p>
          )}
        </div>
        <div className="flex flex-col">
          <Controller
            control={control}
            name="metaTitle"
            render={({ field: { onChange, value } }) => (
              <Input
                type="text"
                id="metaTitle"
                placeholder="Meta Title"
                label="Meta Title"
                value={value}
                onChange={onChange}
                labelPlacement="outside"
                className="w-full"
                variant="bordered"
              />
            )}
          />
          {errors.metaTitle?.message && (
            <p className="text-red-400 text-sm">{errors.metaTitle?.message}</p>
          )}
        </div>
        <div className="flex flex-col">
          <Controller
            control={control}
            name="metaDescription"
            render={({ field: { onChange, value } }) => (
              <Input
                type="text"
                id="metaDescription"
                placeholder="Meta Description"
                label="Meta Description"
                value={value}
                onChange={onChange}
                labelPlacement="outside"
                className="w-full"
                variant="bordered"
              />
            )}
          />
          {errors.metaDescription?.message && (
            <p className="text-red-400 text-sm">
              {errors.metaDescription?.message}
            </p>
          )}
        </div>
      </div>
      <div className="flex flex-col">
        <Controller
          control={control}
          name="articleBody"
          render={({ field: { onChange, value } }) => (
            <JoditEditor
              ref={editor}
              value={value}
              onChange={onChange}
              className="dark:text-black"
            />
          )}
        />
        {errors.articleBody?.message && (
          <p className="text-red-400 text-sm">{errors.articleBody?.message}</p>
        )}
      </div>
      <Button color="primary" type="submit">
        Save
      </Button>
    </form>
  );
}
