"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 { 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";

const page = (props: any) => {
  const { states } = props;
  const [profile, setProfile] = useState();
  const MySwal = withReactContent(Swal);
  const searchParams = useSearchParams();
  const router = useRouter();
  const [, setLoadingState] = useState(false);
  const id: any = searchParams?.get("title");
  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 [selectedArticleId, setSelectedArticleId] = useState(null);
  const [articleBody, setArticleBody] = useState<any>("");
  const [selectedAdvConfig, setSelectedAdvConfig] = useState("");
  const [selectedWritingStyle, setSelectedWritingStyle] = useState("");
  const [selectedContextType, setSelectedContextType] = useState("");
  const [selectedLanguage, setSelectedLanguage] = useState("");
  const [selectedTitle, setSelectedTitle] = useState("");
  const [selectedMainKeyword, setSelectedMainKeyword] = useState("");
  const [selectedSEO, setSelectedSEO] = 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-row">
        <SidebarManagement />
        <div className="w-2/3 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-3">
                      <p className="font-semibold">Judul</p>
                    </div>
                    <input
                      type="text"
                      className={`w-full p-2 border rounded-md mb-3 border-black ${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 lg:flex-row">
                    <div className="w-50%">
                      <div className="mb-3">
                        <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-50%">
                      <div className="mb-3">
                        <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 flex-col justify-between lg:flex-row">
                    <div className="w-50%">
                      <div className="font-semibold mb-3">
                        <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-50%">
                      <div className="font-semibold mb-3">
                        <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">
                      <label htmlFor="description">Deskripsi Artikel</label>
                    </div>
                    {articleBody === null || articleBody === "" ? <div className="w-full px-0 text-sm">Deskripsi tidak boleh kosong</div> : ""}
                  </div>
                </>
                 {/* )}  */}
              </form>
            </div>
          </div>
        </div>
      </div>
    </>
  );
};

export default page;
