"use client";

import { close, error, loading } from "@/config/swal";
import { useRouter } from "@/i18n/routing";
import { getCookiesDecrypt } from "@/lib/utils";
import { getContentRewrite, getInfoProfile } from "@/service/landing/landing";
import { useParams, useSearchParams } from "next/navigation";
import React, { useEffect, useState } from "react";
import Swal from "sweetalert2";
import withReactContent from "sweetalert2-react-content";
import * as Yup from "yup";
import { yupResolver } from "@hookform/resolvers/yup";
import { useForm } from "react-hook-form";
import { generateDataArticle } from "@/service/content/ai";
import HeaderManagement from "@/components/landing-page/header-management";
import SidebarManagement from "@/components/landing-page/sidebar-management";
import { saveContentRewrite } from "@/service/content/content";
import CustomEditor from "@/components/editor/custom-editor";
import { Input } from "@/components/ui/input";

const page = () => {
  const [profile, setProfile] = useState();
  const MySwal = withReactContent(Swal);
  const searchParams = useSearchParams();
  const router = useRouter();
  const [, setLoadingState] = useState(false);
  const getParams = useParams();
  const id: any = getParams?.id;
  const [content, setContent] = useState<any>([]);
  const [isFromSPIT, setIsFromSPIT] = useState(false);
  const [listSuggestion, setListSuggestion] = useState();
  const [main, setMain] = useState();
  const userId = getCookiesDecrypt("uie");
  const userRoleId = getCookiesDecrypt("urie");
  const [articleIds, setArticleIds] = useState<any>([]);
  const [isGeneratedArticle, setIsGeneratedArticle] = useState(false);
  const [articleBody, setArticleBody] = useState<any>("");
  const [selectedAdvConfig, setSelectedAdvConfig] = useState("");
  const [selectedWritingStyle, setSelectedWritingStyle] = useState("");
  const [selectedContextType, setSelectedContextType] = useState("");
  const [selectedLanguage, setSelectedLanguage] = useState("");
  const [selectedMainKeyword, setSelectedMainKeyword] = useState("");
  const [selectedSize, setSelectedSize] = useState("");
  const [detailArticle, setDetailArticle] = useState<any>(null);
  const userLevelId = getCookiesDecrypt("ulie");
  const roleId = getCookiesDecrypt("urie");

  // useEffect(() => {
  //   let userLevelId: number | undefined;

  //   if (userLevelId != undefined && userLevelId == 216) {
  //     setIsMabesApprover(true);
  //   }
  // }, [userLevelId]);

  useEffect(() => {
    async function initState() {
      loading();
      const response = await getInfoProfile();

      // console.log(response?.data?.data);
      setProfile(response?.data?.data);
      close();
    }

    async function getInitData() {
      const response = await getContentRewrite(id);
      const data = response?.data?.data;
      setContent(data);

      const cleanArticleBody = data?.articleBody?.replace(/<img[^>]*>/g, "");
      setArticleBody(cleanArticleBody || "");
    }

    initState();
    getInitData();
  }, []);

  const validationSchema = Yup.object().shape({
    title: Yup.string().required("Judul tidak boleh kosong"),
  });

  const formOptions = {
    resolver: yupResolver(validationSchema),
  };

  const {
    register,
    handleSubmit,
    reset,
    formState: { errors },
    setValue,
  } = useForm(formOptions);

  const handleGenerateArtikel = async () => {
    loading();
    const request: any = {
      advConfig: selectedAdvConfig,
      style: selectedWritingStyle,
      website: "None",
      connectToWeb: true,
      lang: selectedLanguage,
      pointOfView: "None",
      title: content?.title,
      imageSource: "Web",
      mainKeyword: content?.title,
      additionalKeywords: content?.htmlDescription,
      targetCountry: null,
      articleSize: selectedSize,
      projectId: 2,
      createdBy: roleId,
      clientId: "ngDLPPiorplznw2jTqVe3YFCz5xqKfUJ",
    };

    const res = await generateDataArticle(request);
    close();

    if (res?.error) {
      console.error(res.message);
      return false;
    }

    const newArticleId = res?.data?.data?.id;
    setIsGeneratedArticle(true);

    setArticleIds((prevIds: any) => {
      if (prevIds.length < 5) {
        return [...prevIds, newArticleId];
      } else {
        const updatedIds = [...prevIds];
        updatedIds[4] = newArticleId;
        return updatedIds;
      }
    });

    // Cookies.set("nulisAIArticleIdTemp", articleIds);
  };
  const save = async (data: any) => {
    const request = {
      id: 1,
      articleId: id.split("-")?.[0],
      title: data.title,
      articleBody: detailArticle?.articleBody,
      metaTitle: detailArticle?.metaTitle,
      metaDescription: detailArticle?.metaDescription,
      mainKeyword: detailArticle?.mainKeyword,
      additionalKeyword: detailArticle?.additionalKeyword,
      articleSize: detailArticle?.articleSize,
      style: detailArticle?.style,
      website: detailArticle?.website,
      imageUrl: detailArticle?.imageUrl,
    };
    loading();
    const res = await saveContentRewrite(request);
    if (res?.error) {
      error(res?.message);
      return false;
    }
    successSubmit();
  };

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

  function onSubmit(data: any) {
    MySwal.fire({
      title: "Simpan Data",
      text: "",
      icon: "warning",
      showCancelButton: true,
      cancelButtonColor: "#d33",
      confirmButtonColor: "#3085d6",
      confirmButtonText: "Simpan",
    }).then((result) => {
      if (result.isConfirmed) {
        save(data);
      }
    });
  }

  return (
    <>
      <HeaderManagement />
      <div className="flex flex-col lg:flex-row">
        <SidebarManagement />
        <div className="w-full lg:w-2/3 p-8 lg:p-12">
          <div className="flex flex-col">
            <div className="text-xl font-bold mb-5">Detail Content Rewrite</div>
            <div className="p-8 border border-black rounded-lg">
              <form method="POST" onSubmit={handleSubmit(onSubmit)}>
                {content && (
                  <>
                    <div className="w-full">
                      <div className="mb-1">
                        <p className="font-bold text-base">Judul</p>
                      </div>
                      <Input
                        type="text"
                        className={`w-full mb-3 ${errors.title ? "is-invalid" : ""}`}
                        {...register("title", {
                          value: content?.title,
                        })}
                        id="title"
                        defaultValue={content?.title}
                        // onChange={(e) => setSelectedTitle(e.target.value)}
                      />
                    </div>
                    <div className="flex flex-col justify-between gap-3 lg:flex-row">
                      <div className="w-full lg:w-1/2">
                        <div className="mb-1">
                          <p className="font-semibold">Main Keyword</p>
                        </div>
                        <div>
                          <Input type="text" className="border mb-3 w-full rounded-md p-2 border-black" id="mainKeyword" name="mainKeyword" placeholder="Masukan Main Keyword disini!" defaultValue={content?.mainKeyword} />
                        </div>
                      </div>
                      <div className="w-full lg:w-1/2">
                        <div className="mb-1">
                          <label htmlFor="title" className="font-semibold">
                            Additional Keyword{" "}
                          </label>
                        </div>
                        <Input
                          className="border mb-3 rounded-md p-2 border-black"
                          type="text"
                          id="additionalKeyword"
                          name="additionalKeyword"
                          // onChange={(e) =>
                          //   setSelectedMainKeyword(e.target.value)
                          // }
                          placeholder="Masukan Additional Keyword disini!"
                          defaultValue={content?.additionalKeyword}
                        />
                      </div>
                    </div>

                    <div className="flex gap-3 justify-between flex-col lg:flex-row">
                      <div className="w-full lg:w-1/2">
                        <div className="font-semibold mb-1">
                          <label htmlFor="metaTitle">Meta Title</label>
                        </div>
                        <Input
                          type="text"
                          className="border rounded-md mb-3 p-2 border-black"
                          id="metaTitle"
                          name="metaTitle"
                          // onChange={(e) =>
                          //   setSelectedMainKeyword(e.target.value)
                          // }
                          placeholder="Masukan Meta Title disini!"
                          defaultValue={content?.metaTitle}
                        />
                      </div>
                      <div className="w-full lg:w-1/2">
                        <div className="font-semibold mb-1">
                          <label htmlFor="metaDescription">Meta Description</label>
                        </div>
                        <Input
                          type="text"
                          className="border rounded-md mb-3 p-2 border-black"
                          id="metaDescription"
                          name="metaDescription"
                          // onChange={(e) =>
                          //   setSelectedMainKeyword(e.target.value)
                          // }
                          placeholder="Masukan Meta Description disini!"
                          defaultValue={content?.metaDescription}
                        />
                      </div>
                    </div>

                    <div className="w-full">
                      <div className="font-semibold mb-3 text-black gap-2">
                        <label htmlFor="description" className="text-black dark:text-white">
                          Deskripsi Artikel
                        </label>
                        <CustomEditor onChange={(e: any) => {}} initialData={articleBody || ""} />
                      </div>
                    </div>
                  </>
                )}
              </form>
            </div>
          </div>
        </div>
      </div>
    </>
  );
};

export default page;
