"use client";
import { error } from "@/config/swal";
import { createArticle, getArticleByCategory } from "@/service/article";
import { zodResolver } from "@hookform/resolvers/zod";
import {
  Button,
  Card,
  Chip,
  Input,
  Select,
  SelectItem,
  SelectSection,
  Selection,
  Spinner,
} from "@nextui-org/react";
import JoditEditor from "jodit-react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import React, { ChangeEvent, 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 ReactSelect from "react-select";
import makeAnimated from "react-select/animated";
import GenerateSingleArticle from "./generate-single-article-form";
import { getDetailArticle } from "@/service/generate-article";
import { delay } from "@/utils/global";
import GenerateBulkArticle from "./generate-bulk-article-form";
import generatedArticleIds from "@/store/generated-article-store";
import SpeechToTextOperator from "./speech-to-text-form";
import GenerateRewriteArticle from "./generate-rewrite-form";
import SpeechToText from "./speech-to-text-form";

const dummyCategory = [
  {
    id: 1,
    label: "Category 1",
    value: "category-1",
  },
  {
    id: 2,
    label: "Category 2",
    value: "category-2",
  },
  {
    id: 3,
    label: "Category 3",
    value: "category-3",
  },
  {
    id: 4,
    label: "Category 4",
    value: "category-4",
  },
  {
    id: 5,
    label: "Category 5",
    value: "category-5",
  },
];

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

export default function GenerateArticleForm() {
  const animatedComponents = makeAnimated();

  const router = useRouter();
  const [title, setTitle] = useState<string>("");
  const [article, setArticle] = useState("");
  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 [selectedImages, setSelectedImages] = useState<File[]>([]);
  const [selectedCategory, setSelectedCategory] = useState<any>();
  const [selectedContentType, setSelectedContentType] =
    useState("single-article");

  const [collectSingleArticleId, setCollectSingleArticleId] = useState<
    number[]
  >([]);
  const [collectBulkArticleId, setCollectBulkArticleId] = useState<number[]>(
    []
  );
  const [collectRewriteArticleId, setCollectRewriteArticleId] = useState<
    number[]
  >([]);

  const [generatedTranscriptId, setGeneratedTranscriptId] = useState<number>();

  const generatedArticleIdStore = generatedArticleIds(
    (state) => state.articleIds
  );
  const setGeneratedArticleIdStore = generatedArticleIds(
    (state) => state.setArticleIds
  );

  const [selectedGeneratedArticleId, setSelectedGeneratedArticleId] =
    useState<number>();
  const [listCategory, setListCategory] = useState<
    { id: number; label: string; value: number }[]
  >([]);

  useEffect(() => {
    setCollectSingleArticleId(generatedArticleIdStore.singleArticle);
    setCollectBulkArticleId(generatedArticleIdStore.bulkArticle);
    setCollectRewriteArticleId(generatedArticleIdStore.rewriteArticle);
  });

  useEffect(() => {
    fetchCategory();
  }, []);

  const fetchCategory = async () => {
    const res = await getArticleByCategory();
    if (res?.data?.data) {
      setupCategory(res?.data?.data);
    }
  };

  const setupCategory = (data: any) => {
    const temp = [];
    for (const element of data) {
      temp.push({
        id: element.id,
        label: element.title,
        value: element.id,
      });
    }
    setListCategory(temp);
  };

  const handleImageChange = (event: ChangeEvent<HTMLInputElement>) => {
    if (event.target.files) {
      const files = Array.from(event.target.files);
      setSelectedImages((prevImages) => [...prevImages, ...files]);
    }
  };

  const handleRemoveImage = (index: number) => {
    setSelectedImages((prevImages) => prevImages.filter((_, i) => i !== index));
  };

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

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

    const response = await createArticle(formData);

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

    successSubmit("/admin/article");
  }

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

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

  const singleArticleId = (id: number) => {
    const temp = [...collectSingleArticleId, id];
    const tempStore = generatedArticleIdStore;
    tempStore.singleArticle = temp;
    setCollectSingleArticleId(temp);
    setGeneratedArticleIdStore(tempStore);
  };
  const bulkArticleId = (id: number[]) => {
    const temp: number[] = [...collectBulkArticleId, ...id];
    const tempStore = generatedArticleIdStore;
    tempStore.bulkArticle = temp;
    setCollectBulkArticleId(temp);
    setGeneratedArticleIdStore(tempStore);
  };
  const rewriteArticleId = (id: number) => {
    const temp = [...collectRewriteArticleId, id];
    const tempStore = generatedArticleIdStore;
    tempStore.rewriteArticle = temp;
    setCollectRewriteArticleId(temp);
    setGeneratedArticleIdStore(tempStore);
  };

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

  const checkArticleStatus = async (data: string | null) => {
    if (data === null) {
      delay(10000).then(() => {
        getArticleDetail();
      });
    }
  };

  const getArticleDetail = async () => {
    if (selectedGeneratedArticleId) {
      const res = await getDetailArticle(selectedGeneratedArticleId);
      const data = res?.data?.data?.articleBody;
      checkArticleStatus(data);
      if (data !== null) {
        setContent(data);
      } else {
        setContent("");
      }
    }
  };

  const goEdit = () => {
    const temp = generatedArticleIdStore;
    temp.singleArticle = collectSingleArticleId;
    temp.bulkArticle = collectBulkArticleId;
    setGeneratedArticleIdStore(temp);
    router.push(`/admin/article/generate/edit/${selectedGeneratedArticleId}`);
  };

  return (
    <div className="mx-5 my-5 overflow-y-auto">
      <div>
        <Card className="rounded-md p-5 space-y-5">
          <div>
            <Input
              type="title"
              value={title}
              onChange={(e) => setTitle(e.target.value)}
              label="Judul"
              variant="bordered"
              placeholder="Enter Text"
              labelPlacement="outside"
            />
            <div className="text-sm text-red-500">
              {title.length === 0 && <p className="text-danger">Required</p>}
            </div>
          </div>
          <div>
            <Select
              label="Jenis Artikel"
              variant="bordered"
              labelPlacement="outside"
              placeholder="Select"
              selectedKeys={[article]}
              className="max-w-xs"
              onChange={(e) => setArticle(e.target.value)}
            >
              {TypeId.map((data) => (
                <SelectItem key={data.key} value={data.key}>
                  {data.label}
                </SelectItem>
              ))}
            </Select>
            {article === "" && <p className="text-danger">Required</p>}
          </div>
          <div>
            <p className="text-sm mb-1">Category</p>
            <ReactSelect
              className="basic-single text-black z-50"
              classNames={{
                control: (state: any) =>
                  "!rounded-xl bg-white !border-1 !border-gray-200",
              }}
              classNamePrefix="select"
              onChange={setSelectedCategory}
              closeMenuOnSelect={false}
              components={animatedComponents}
              isClearable={true}
              isSearchable={true}
              isMulti={true}
              placeholder="Category ..."
              name="sub-module"
              options={listCategory}
            />
            <div className="text-sm text-red-500">
              {(!selectedCategory || selectedCategory?.length < 1) && (
                <p>Required</p>
              )}
            </div>
          </div>
          <div>
            <Input
              type="text"
              value={slug}
              onChange={(e) => setSlug(e.target.value)}
              label="Slug"
              variant="bordered"
              placeholder="Enter Text"
              labelPlacement="outside"
            />
            {slug.length === 0 && <div className=" text-danger">Required</div>}
          </div>
          <div>
            <Input
              label="Tags (Optional)"
              labelPlacement="outside"
              type="text"
              value={newTags}
              onChange={(e) => setNewTags(e.target.value)}
              onKeyDown={handleKeyDown}
              placeholder="Tambahkan tag baru dan tekan Enter"
            />
            {tags.length === 0 && <div className=" text-red-500">Required</div>}

            <div className="flex gap-2 border border-inherit mt-2 rounded-md p-1 items-center h-11">
              {tags.map((tag, index) => (
                <Chip
                  color="primary"
                  key={index}
                  onClose={() => handleClose(tag)}
                >
                  {tag}
                </Chip>
              ))}
            </div>
          </div>
          <Select
            label="Content Type"
            variant="bordered"
            labelPlacement="outside"
            placeholder=""
            selectedKeys={[selectedContentType]}
            onChange={(e) =>
              e.target.value !== ""
                ? setSelectedContentType(e.target.value)
                : ""
            }
            className="w-full md:w-1/4 py-4"
          >
            <SelectSection>
              <SelectItem key="single-article">Single Article</SelectItem>
              {/* <SelectItem key="bulk-article">Bulk Article</SelectItem>
              <SelectItem key="rewrite">Content Rewrite</SelectItem>
              <SelectItem key="speech-to-text">Speech to Text</SelectItem> */}
            </SelectSection>
          </Select>
          {selectedContentType === "single-article" ? (
            <div className="flex flex-col">
              <GenerateSingleArticle
                articleId={(data) => singleArticleId(data)}
              />
              <div className="flex flex-wrap gap-3">
                {collectSingleArticleId.length > 0 &&
                  collectSingleArticleId.map((data) => (
                    <Button
                      key={data}
                      color={
                        selectedGeneratedArticleId === data
                          ? "primary"
                          : "warning"
                      }
                      onPress={() => setSelectedGeneratedArticleId(data)}
                    >
                      {data}
                    </Button>
                  ))}
              </div>
              {selectedGeneratedArticleId &&
                collectSingleArticleId.includes(selectedGeneratedArticleId) &&
                (selectedGeneratedArticleId && content !== "" ? (
                  <div>
                    <p className="pb-2">Description</p>
                    <a
                      className="text-primary cursor-pointer"
                      onClick={() => goEdit()}
                    >
                      Edit
                    </a>
                    <JoditEditor
                      ref={editor}
                      value={content}
                      onChange={(newContent) => setContent(newContent)}
                      className="dark:text-black"
                    />
                  </div>
                ) : selectedGeneratedArticleId && content == "" ? (
                  <Spinner size="lg" />
                ) : collectSingleArticleId.length > 0 ? (
                  <p className="text-lg">Select Article ID</p>
                ) : (
                  ""
                ))}
            </div>
          ) : selectedContentType === "bulk-article" ? (
            <div className="flex flex-col">
              <GenerateBulkArticle articleId={(data) => bulkArticleId(data)} />
              <div className="flex flex-wrap gap-3 mt-3">
                {collectBulkArticleId.length > 0 &&
                  collectBulkArticleId.map((data) => (
                    <Button
                      key={data}
                      color={
                        selectedGeneratedArticleId === data
                          ? "primary"
                          : "warning"
                      }
                      onPress={() => setSelectedGeneratedArticleId(data)}
                    >
                      {data}
                    </Button>
                  ))}
              </div>
              {selectedGeneratedArticleId &&
                collectBulkArticleId.includes(selectedGeneratedArticleId) &&
                (selectedGeneratedArticleId && content !== "" ? (
                  <div>
                    <p className="pb-2">Description</p>
                    <JoditEditor
                      ref={editor}
                      value={content}
                      onChange={(newContent) => setContent(newContent)}
                      className="dark:text-black"
                    />
                  </div>
                ) : selectedGeneratedArticleId && content == "" ? (
                  <Spinner size="lg" />
                ) : collectSingleArticleId.length > 0 ? (
                  <p className="text-lg">Select Article ID</p>
                ) : (
                  ""
                ))}
            </div>
          ) : selectedContentType === "rewrite" ? (
            <div className="flex flex-col">
              <GenerateRewriteArticle
                articleId={(data) => rewriteArticleId(data)}
                initTranscript={generatedTranscriptId}
              />
              <div className="flex flex-wrap gap-3 mt-3">
                {collectRewriteArticleId.length > 0 &&
                  collectRewriteArticleId.map((data) => (
                    <Button
                      key={data}
                      color={
                        selectedGeneratedArticleId === data
                          ? "primary"
                          : "warning"
                      }
                      onPress={() => setSelectedGeneratedArticleId(data)}
                    >
                      {data}
                    </Button>
                  ))}
              </div>
              {selectedGeneratedArticleId &&
                collectRewriteArticleId.includes(selectedGeneratedArticleId) &&
                (selectedGeneratedArticleId && content !== "" ? (
                  <div>
                    <p className="pb-2">Description</p>
                    <JoditEditor
                      ref={editor}
                      value={content}
                      onChange={(newContent) => setContent(newContent)}
                      className="dark:text-black"
                    />
                  </div>
                ) : selectedGeneratedArticleId && content == "" ? (
                  <Spinner size="lg" />
                ) : collectRewriteArticleId.length > 0 ? (
                  <p className="text-lg">Select Article ID</p>
                ) : (
                  ""
                ))}
            </div>
          ) : selectedContentType === "speech-to-text" ? (
            <SpeechToText
              generateArticleFromTranscript={(transcriptId) => {
                setGeneratedTranscriptId(transcriptId);
                setSelectedContentType("rewrite");
              }}
            />
          ) : (
            ""
          )}

          <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">
                    {/* or{" "} */}
                    <span className="font-semibold underline text-amber-800">
                      Click to upload
                    </span>
                  </p>
                </div>
                <input
                  id="dropzone-file"
                  type="file"
                  onChange={handleImageChange}
                  className="hidden"
                />
              </label>
            </div>
            {selectedImages?.length > 0 ? (
              <div>
                <h4>Pratinjau:</h4>
                <div className="flex gap-2 pt-2">
                  {selectedImages.map((image, index) => (
                    <div key={index} className="flex flex-col items-end">
                      <Chip
                        color="danger"
                        size="sm"
                        className="cursor-pointer"
                        onClick={() => handleRemoveImage(index)}
                      >
                        X
                      </Chip>
                      <img
                        src={URL.createObjectURL(image)}
                        alt="Pratinjau Gambar"
                        style={{ maxWidth: "200px", maxHeight: "200px" }}
                      />
                    </div>
                  ))}
                </div>
              </div>
            ) : (
              ""
            )}
          </div>
          <div className="flex justify-end gap-3">
            <Link href={`/admin/article`}>
              <Button color="danger" variant="ghost">
                Cancel
              </Button>
            </Link>
            <Button
              type="button"
              color="primary"
              variant="solid"
              isDisabled={content === ""}
              onPress={onSubmit}
            >
              Save
            </Button>
          </div>
        </Card>
      </div>
    </div>
  );
}
