"use client";
import { error } from "@/config/swal";
import { getArticleById } from "@/service/article";
import { getSeoScore } from "@/service/generate-article";
import { zodResolver } from "@hookform/resolvers/zod";
import {
  Accordion,
  AccordionItem,
  Button,
  Card,
  Chip,
  CircularProgress,
  Input,
  Select,
  SelectItem,
} from "@nextui-org/react";
import JoditEditor from "jodit-react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { useEffect, useRef, useState } from "react";
import { useForm } from "react-hook-form";
import Swal from "sweetalert2";
import withReactContent from "sweetalert2-react-content";
import * as z from "zod";
import { TimesIcon } from "../icons";

const articleSchema = z.object({
  title: z.string().min(1, { message: "Required" }),
  article: z.string().min(1, { message: "Required" }),
  slug: z.string().min(1, { message: "Required" }),
  tags: z.string().min(0, { message: "Required" }).optional(),
  description: z.string().min(1, { message: "Required" }).optional(),
});

const TypeId = [
  {
    key: "1",
    label: "Article",
  },
  {
    key: "2",
    label: "Magazine",
  },
];

export default function FormDetailArticle() {
  // const [id, setId] = useState<any>();
  const [title, setTitle] = useState<string>("");
  const [slug, setSlug] = useState<string>("");
  const [tags, setTags] = useState<string[]>([]);
  const [newTags, setNewTags] = useState<string>("");
  const editor = useRef(null);
  const [content, setContent] = useState("");
  const MySwal = withReactContent(Swal);
  const [article, setArticle] = useState<any>();
  const [typeArticle, setTypeArticle] = useState("");
  const pathname = usePathname();
  const splitPathname = pathname.split("/");
  const id = splitPathname[splitPathname.length - 1];
  console.log(id, "pathnamesplit");

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

  const editorConfig = {
    readonly: true,
  };

  const handleClose = (tagsToRemove: string) => {
    setTags(tags.filter((tag) => tag !== tagsToRemove));
    if (tags.length === 1) {
      setTags([]);
    }
  };

  const handleAddTags = (e: any) => {
    if (newTags.trim() !== "") {
      setTags([...tags, newTags.trim()]);
      setNewTags("");
      e.preventDefault();
    }
  };

  const handleKeyDown = (event: any) => {
    if (event.key === "Enter") {
      handleAddTags(event);
    }
  };

  useEffect(() => {
    async function initState() {
      const res = await getArticleById(id);
      setArticle(res.data?.data);
      setTitle(res.data?.data?.title);
      setTypeArticle(String(res.data.data?.typeId));
      console.log("ii", String(res.data.data?.typeId));
      const tagsArray = res.data.data?.tags
        ? res.data.data.tags.split(",")
        : [];
      setTags(tagsArray);

      console.log("Data Aritcle", tagsArray);
    }

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

  const [totalScoreSEO, setTotalScoreSEO] = useState();
  const [errorSEO, setErrorSEO] = useState<any>([]);
  const [warningSEO, setWarningSEO] = useState<any>([]);
  const [optimizedSEO, setOptimizedSEO] = useState<any>([]);

  const fetchSeoScore = async () => {
    const res = await getSeoScore("1931");
    if (res.error) {
      error(res.message);
      return false;
    }
    setTotalScoreSEO(res.data.data?.seo_analysis?.score || 0);
    let errorList: any[] = [
      ...res.data.data?.seo_analysis?.analysis?.keyword_optimization?.error,
      ...res.data.data?.seo_analysis?.analysis?.content_quality?.error,
    ];
    setErrorSEO(errorList);
    let warningList: any[] = [
      ...res.data.data?.seo_analysis?.analysis?.keyword_optimization?.warning,
      ...res.data.data?.seo_analysis?.analysis?.content_quality?.warning,
    ];
    setWarningSEO(warningList);
    let optimizedList: any[] = [
      ...res.data.data?.seo_analysis?.analysis?.keyword_optimization?.optimized,
      ...res.data.data?.seo_analysis?.analysis?.content_quality?.optimized,
    ];
    setOptimizedSEO(optimizedList);
  };

  async function save(data: any) {
    const formData = {
      id: id,
      title: title,
      typeId: parseInt(String(Array.from(article)[0])),
      slug: slug,
      tags: tags.join(","),
      description: content,
      htmlDescription: content,
    };

    console.log("Form Data:", formData);
    // const response = await createArticle(formData);

    // if (response?.error) {
    //     error(response.message);
    //     return false;
    // }
  }

  async 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 (
    <div className="mx-5 my-5 overflow-y-auto">
      <div className="text-black px-3 flex flex-col rounded-md gap-3">
        <p className="font-semibold text-lg"> SEO Score</p>
        <div className="flex flex-row gap-5 w-full">
          <CircularProgress
            aria-label=""
            color="warning"
            showValueLabel={true}
            size="lg"
            value={Number(totalScoreSEO) * 100}
          />
          <div>
            {/* <ApexChartDonut value={Number(totalScoreSEO) * 100} /> */}
          </div>
          <div className="flex flex-row gap-5">
            <div className="px-2 py-1 border radius-md flex flex-row gap-2 items-center border-red-500 rounded-lg">
              {/* <TimesIcon size={15} className="text-danger" /> */}
              Error : {errorSEO.length || 0}
            </div>
            <div className="px-2 py-1 border radius-md flex flex-row gap-2 items-center border-yellow-500 rounded-lg">
              {/* <p className="text-warning w-[15px] h-[15px] text-center mt-[-10px]">
                !
              </p> */}
              Warning : {warningSEO.length || 0}
            </div>
            <div className="px-2 py-1 border radius-md flex flex-row gap-2 items-center border-green-500 rounded-lg">
              {/* <CheckIcon size={15} className="text-success" /> */}
              Optimize : {optimizedSEO.length || 0}
            </div>
          </div>
        </div>
        <Accordion
          variant="splitted"
          itemClasses={{
            base: "!bg-transparent",
            title: "text-black",
          }}
        >
          <AccordionItem
            key="1"
            aria-label="Error"
            // startContent={<TimesIcon size={20} className="text-danger" />}
            title={`${errorSEO?.length || 0} Errors`}
          >
            <div className="flex flex-col gap-2">
              {errorSEO?.map((item: any) => (
                <p
                  key={item}
                  className="w-full border border-red-500 rounded-md h-[40px] text-left flex flex-col justify-center px-3"
                >
                  {item}
                </p>
              ))}
            </div>
          </AccordionItem>
          <AccordionItem
            key="2"
            aria-label="Warning"
            // startContent={
            //   <p className="text-warning w-[20px] h-[20px] text-center mt-[-10px]">
            //     !
            //   </p>
            // }
            title={`${warningSEO?.length || 0} Warnings`}
          >
            <div className="flex flex-col gap-2">
              {warningSEO?.map((item: any) => (
                <p
                  key={item}
                  className="w-full border border-yellow-500 rounded-md h-[40px] text-left flex flex-col justify-center px-3"
                >
                  {item}
                </p>
              ))}
            </div>
          </AccordionItem>
          <AccordionItem
            key="3"
            aria-label="Optimized"
            // startContent={<CheckIcon size={20} className="text-success" />}
            title={`${optimizedSEO?.length || 0} Optimized`}
          >
            <div className="flex flex-col gap-2">
              {optimizedSEO?.map((item: any) => (
                <p
                  key={item}
                  className="w-full border border-green-500 rounded-md h-[40px] text-left flex flex-col justify-center px-3"
                >
                  {item}
                </p>
              ))}
            </div>
          </AccordionItem>
        </Accordion>
      </div>
      <form method="POST" onSubmit={handleSubmit(onSubmit)}>
        <Card className="rounded-md p-5 space-y-5">
          <div>
            <Input
              type="title"
              {...register("title")}
              isReadOnly
              value={title}
              onValueChange={setTitle}
              label="Judul"
              variant="bordered"
              placeholder="Enter Text"
              labelPlacement="outside"
            />
            <div className="text-sm text-red-500">
              {title.length === 0 && errors.title && errors.title.message}
            </div>
          </div>
          <div>
            <Select
              label="Jenis Artikel"
              {...register("article")}
              variant="bordered"
              labelPlacement="outside"
              placeholder="Select"
              selectedKeys={[typeArticle]}
              className="max-w-xs"
              onChange={(e) => setTypeArticle(e.target.value)}
            >
              {TypeId.map((data) => (
                <SelectItem key={data.key} value={data.key}>
                  {data.label}
                </SelectItem>
              ))}
            </Select>
            <div className="text-sm text-red-500">
              {errors.article?.message}
            </div>
            {/* <p>{article}</p> */}
          </div>
          <div>
            <Input
              isReadOnly
              type="text"
              {...register("slug")}
              value={article?.slug}
              onChange={(e) => setSlug(e.target.value)}
              label="Slug"
              variant="bordered"
              placeholder="Enter Text"
              labelPlacement="outside"
            />
            <div className="text-sm text-red-500">
              {slug.length === 0 && errors.slug && errors.slug.message}
            </div>
          </div>
          <div>
            <p className="text-sm">Tags</p>
            {/* <Input
                            label="Tags (Optional)"
                            {...register("tags")}
                            labelPlacement='outside'
                            type="text"
                            value={newTags}
                            onChange={(e) => setNewTags(e.target.value)}
                            onKeyDown={handleKeyDown}
                            placeholder="Tambahkan tag baru dan tekan Enter"
                        /> */}
            <div className="text-sm text-red-500">
              {tags.length === 0 && errors.tags && errors.tags.message}
            </div>
            <div className="flex gap-2 border border-inherit mt-2 rounded-md p-1 items-center h-11">
              {tags.map((tag, index) => (
                <Chip
                  key={index}
                  color="primary"
                  onClose={() => handleClose("")}
                >
                  {tag}
                </Chip>
              ))}
            </div>
          </div>
          <div>
            <p className="pb-2">Description</p>
            <JoditEditor
              ref={editor}
              value={article?.description}
              // config={editorConfig}
              onChange={(newContent) => setContent(newContent)}
              className="dark:text-black"
            />
            <div className="text-sm text-red-500">
              {content.length === 0 &&
                errors.description &&
                errors.description.message}
            </div>
          </div>

          <div className="flex justify-end gap-3">
            <Link href={`/admin/master-role`}>
              <Button color="danger" variant="ghost">
                Cancel
              </Button>
            </Link>
            <Button
              // type="submit"
              color="primary"
              variant="solid"
            >
              Publish
            </Button>
          </div>
        </Card>
      </form>
    </div>
  );
}
