"use client";
import { getArticleById } from "@/service/article";
import { zodResolver } from "@hookform/resolvers/zod";
import {
  Button,
  Card,
  Chip,
  Input,
  Select,
  SelectItem,
  Selection,
} from "@nextui-org/react";
import JoditEditor from "jodit-react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import React, { 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";

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(),
});

export default function FormUpdateArticle() {
  // 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 [typeId, setTypeId] = 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 TypeId = [
    {
      key: 1,
      label: "Article",
    },
    {
      key: 2,
      label: "Magazine",
    },
  ];

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

  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);
      setTypeId(res.data?.data?.typeId);
      setSlug(res.data?.data?.slug);
      const tagsArray = res.data.data?.tags
        ? res.data.data.tags.split(",")
        : [];
      setTags(tagsArray);

      console.log("Data Aritcle", res.data?.data);
    }

    initState();
  }, []);

  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">
      <form method="POST" onSubmit={handleSubmit(onSubmit)}>
        <Card className="rounded-md p-5 space-y-5">
          <div>
            <Input
              type="title"
              {...register("title")}
              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")}
              selectedKeys={[typeId]}
              onChange={(e) => setTypeId(e.target.value)}
              variant="bordered"
              labelPlacement="outside"
              placeholder="Select"
              className="max-w-xs"
            >
              {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>
          </div>
          <div>
            <Input
              type="text"
              {...register("slug")}
              value={slug}
              onValueChange={setSlug}
              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>
            <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)}
                >
                  {tag}
                </Chip>
              ))}
            </div>
          </div>
          <div>
            <p className="pb-2">Description</p>
            <JoditEditor
              ref={editor}
              value={article?.description}
              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>
            <p>Attachment (Opsional)</p>
            <div className="flex items-center justify-center w-full pt-2 ">
              <label
                htmlFor="dropzone-file"
                className="flex flex-col items-center justify-center w-full h-36 border border-gray-100 border-dashed rounded-lg cursor-pointer bg-gray-50 hover:bg-gray-100 dark:border-gray-600 dark:hover:border-gray-500 dark:hover:bg-gray-200"
              >
                <div className="flex flex-col items-center justify-center pt-5 pb-6 ">
                  <svg
                    className="w-10 h-10 mb-3 text-gray-400"
                    fill="none"
                    stroke="currentColor"
                    viewBox="0 0 24 24"
                    xmlns="http://www.w3.org/2000/svg"
                  >
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      strokeWidth="2"
                      d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12"
                    ></path>
                  </svg>
                  <p className="mb-2 text-sm text-gray-500 dark:text-gray-400">
                    Drag and drop files here
                  </p>
                  <p className="mb-2 text-sm text-gray-500 dark:text-gray-400">
                    <span className="font-semibold underline text-amber-800">
                      Click to upload
                    </span>
                  </p>
                </div>
                <input id="dropzone-file" type="file" />
              </label>
            </div>
          </div>
          <div className="flex justify-end gap-3">
            <Link href={`/admin/article`}>
              <Button color="danger" variant="ghost">
                Cancel
              </Button>
            </Link>
            <Button type="submit" color="primary" variant="solid">
              Publish
            </Button>
          </div>
        </Card>
      </form>
    </div>
  );
}
