"use client";
import { close, error, loading } from "@/config/swal";
import { FormEvent, Fragment, useEffect, useRef, useState } from "react";
import { Controller, useForm } from "react-hook-form";
import * as z from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import Swal from "sweetalert2";
import withReactContent from "sweetalert2-react-content";
import { Input, Textarea } from "@heroui/input";
import { Button } from "@heroui/button";
import { useParams, useRouter } from "next/navigation";
import { getCommentById, saveCommentStatus } from "@/services/comment";
import {
  Modal,
  ModalBody,
  ModalContent,
  ModalFooter,
  ModalHeader,
  useDisclosure,
} from "@heroui/react";
import { getArticleById } from "@/services/article";
import Link from "next/link";
import { postArticleComment } from "@/services/master-user";
import Cookies from "js-cookie";

interface DetailComments {
  id: number;
  message: string;
  articleId: number;
  commentFromName: string;
}

export default function ReviewComment() {
  const MySwal = withReactContent(Swal);
  const { isOpen, onOpen, onOpenChange } = useDisclosure();

  const params = useParams();
  const id = Number(params?.id);
  const router = useRouter();
  const [replyValue, setReplyValue] = useState("");

  const [detailData, setDetailData] = useState<DetailComments>();
  const [detailArticle, setDetailArticle] = useState<{
    id: number;
    slug: string;
    title: string;
  }>();
  useEffect(() => {
    initFetch();
  }, []);

  const initFetch = async () => {
    loading();
    const res = await getCommentById(id);
    setDetailData(res?.data?.data);
    const resArticle = await getArticleById(res?.data?.data?.articleId);
    setDetailArticle(resArticle?.data?.data);
    close();
  };

  const handleCommentStatus = async (statusId: number) => {
    MySwal.fire({
      title: "Submit Data",
      text: "",
      icon: "warning",
      showCancelButton: true,
      cancelButtonColor: "#d33",
      confirmButtonColor: "#3085d6",
      confirmButtonText: "Simpan",
    }).then((result) => {
      if (result.isConfirmed) {
        saveStatus(statusId);
      }
    });
  };

  const saveStatus = async (statusId: number) => {
    const req = { id: id, statusId: statusId };
    const res = await saveCommentStatus(req);
    if (res?.error) {
      error(res.message);
      return false;
    }
    successSubmit("/admin/comment");
  };

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

  const sendComment = async () => {
    const data = {
      commentFromEmail: "ppid@polri.go.id",
      commentFromName: "Mabes Polri",
      articleId: detailData?.articleId,
      isPublic: true,
      message: replyValue,
      parentId: id,
    };

    const res = await postArticleComment(data);
    if (res?.error) {
      error(res?.message);
      return false;
    }
    saveStatus(2);
  };

  return (
    <div className="p-8">
      <div className="bg-white text-black shadow-lg p-4 rounded-lg flex flex-col gap-3 text-sm w-full lg:w-1/2">
        <div className="flex flex-col gap-1">
          <p>Artikel</p>
          <Link
            target="_black"
            className="text-primary hover:underline w-fit"
            href={`/news/detail/${detailArticle?.id}-${detailArticle?.slug}`}
          >
            {detailArticle?.title}
          </Link>
        </div>
        <div className="flex flex-col gap-1">
          <p>Nama</p>
          <Input
            type="text"
            id="username"
            placeholder=""
            label=""
            isReadOnly
            value={detailData?.commentFromName}
            labelPlacement="outside"
            className="w-full "
            classNames={{
              inputWrapper: [
                "border-1 rounded-lg",
                "dark:group-data-[focused=false]:bg-transparent !border-1 dark:!border-gray-400",
              ],
            }}
            variant="bordered"
          />
        </div>
        <div className="flex flex-col gap-1">
          <p>Komentar</p>
          <Textarea
            type="text"
            id="address"
            placeholder=""
            label=""
            value={detailData?.message}
            labelPlacement="outside"
            className="w-full "
            classNames={{
              inputWrapper: [
                "border-1 rounded-lg",
                "dark:group-data-[focused=false]:bg-transparent !border-1 dark:!border-gray-400",
              ],
            }}
            variant="bordered"
          />
        </div>
        <div className="flex flex-col gap-1">
          <p>Status</p>
          <div className="flex flex-row gap-3">
            <Button
              onPress={() => handleCommentStatus(1)}
              color="success"
              className="w-fit text-white"
            >
              Setujui
            </Button>
            <Button onPress={onOpen} color="primary" className="w-fit">
              Balas
            </Button>
            <Button
              onPress={() => handleCommentStatus(3)}
              color="danger"
              className="w-fit"
            >
              Tolak
            </Button>
          </div>
        </div>
        <div className="w-full justify-end flex">
          <Button
            onPress={router.back}
            color="danger"
            variant="bordered"
            className="w-fit"
          >
            Kembali
          </Button>
        </div>
      </div>
      <Modal isOpen={isOpen} onOpenChange={onOpenChange}>
        <ModalContent>
          {(onClose) => (
            <>
              <ModalHeader className="flex flex-col gap-1">
                Komentar Balasan
              </ModalHeader>
              <ModalBody>
                <Textarea
                  type="text"
                  id="address"
                  placeholder=""
                  label=""
                  value={replyValue}
                  onValueChange={setReplyValue}
                  labelPlacement="outside"
                  className="w-full "
                  classNames={{
                    inputWrapper: [
                      "border-1 rounded-lg",
                      "dark:group-data-[focused=false]:bg-transparent !border-1 dark:!border-gray-400",
                    ],
                  }}
                  variant="bordered"
                />
              </ModalBody>
              <ModalFooter>
                <Button color="danger" variant="light" onPress={onClose}>
                  Close
                </Button>
                <Button
                  isDisabled={replyValue.length < 2}
                  color="primary"
                  onPress={() => sendComment()}
                >
                  Submit
                </Button>
              </ModalFooter>
            </>
          )}
        </ModalContent>
      </Modal>
    </div>
  );
}
