"use client";
import { Button } from "@/components/ui/button";
import { Separator } from "@/components/ui/separator";
import { Textarea } from "@/components/ui/textarea";
import { useToast } from "@/components/ui/use-toast";
import { close, loading } from "@/config/swal";
import {
  deleteCollabDiscussion,
  getCollabDiscussion,
  getCuratorUser,
  getTicketCollaborationTeams,
  saveCollabDiscussion,
} from "@/service/communication/communication";
import {
  getLocaleTimestamp,
  htmlToString,
  textEllipsis,
} from "@/utils/globals";
import { Icon } from "@iconify/react/dist/iconify.js";
import { useParams } from "next/navigation";
import { stringify } from "querystring";
import { useEffect, useState } from "react";
import Swal from "sweetalert2";
import withReactContent from "sweetalert2-react-content";
import SiteBreadcrumb from "@/components/site-breadcrumb";
import UsersCard from "./component/users-card";

export default function CollaborationPage() {
  const params = useParams();
  const id = params?.id;
  const { toast } = useToast();

  const [detailTickets, setDetailTickets] = useState<any>();
  const [teams, setTeams] = useState([]);
  const [listDiscussion, setListDiscussion] = useState([]);
  const [replyValue, setReplyValue] = useState("");
  const MySwal = withReactContent(Swal);

  useEffect(() => {
    async function getCollabTeam() {
      if (id != undefined) {
        const res = await getTicketCollaborationTeams(String(id));

        if (res?.data !== null) {
          console.log("response teams:", res);

          setDetailTickets(res?.data?.data?.tickets);
          setTeams(res?.data?.data?.userTeam);
          console.log("userteam", res?.data?.data?.userTeam);
        }
      }
    }

    initState();
    getCollabTeam();
  }, [id]);

  async function initState() {
    if (id != undefined) {
      loading();
      const responseGet = await getCollabDiscussion(String(id));
      console.log("get res data", responseGet?.data?.data);
      close();
      setListDiscussion(responseGet?.data?.data);
    }
  }

  async function deleteDataSuggestion(dataId: string | number) {
    loading();
    const response = await deleteCollabDiscussion(dataId);
    console.log(response);

    close();
    initState();
  }

  async function sendDiscussionParent() {
    if (replyValue?.length > 0) {
      loading();
      const data = {
        ticketId: id,
        replyValue,
        parentId: null,
      };

      const response = await saveCollabDiscussion(data);
      if (response?.error) {
        toast({
          title: stringify(response?.message),
        });
        return false;
      }
      toast({
        title: "Sukses Komen",
      });
      setReplyValue("");

      close();
      initState();
    }
  }
  return (
    <div>
      <SiteBreadcrumb />
      <div className="flex flex-row gap-4 pt-6">
        <div className="flex flex-col gap-4 w-[70%]">
          <div className="bg-white flex flex-col rounded-t-xl">
            <div className="flex flex-row gap-2 bg-slate-300 rounded-t-xl p-4 items-center">
              <Icon icon="qlementine-icons:user-16" width={36} />
              <div className="flex flex-col gap-1">
                <div className="flex flex-row">
                  <p className="text-sm">
                    <span className="font-semibold">
                      {detailTickets?.commentFromUserName}
                    </span>{" "}
                    mengirimkan komentar untuk
                  </p>
                  <a
                    href={detailTickets?.feed?.permalink_url}
                    className="font-weight-bold"
                  >
                    {textEllipsis(detailTickets?.feed?.message, 25)}
                  </a>
                </div>
                <p className="text-xs">
                  {" "}
                  {`${new Date(detailTickets?.createdAt).getDate()}-${
                    new Date(detailTickets?.createdAt).getMonth() + 1
                  }-${new Date(
                    detailTickets?.createdAt
                  ).getFullYear()} ${new Date(
                    detailTickets?.createdAt
                  ).getHours()}:${new Date(
                    detailTickets?.createdAt
                  ).getMinutes()}`}
                </p>
              </div>
            </div>
            <div className="p-4"> {htmlToString(detailTickets?.message)}</div>
          </div>
          <div className="bg-white rounded-b-xl flex flex-col p-4">
            <p className="font-bold text-sm">{listDiscussion?.length} Respon</p>
            <Separator className="my-2" />

            <div className="flex flex-col gap-2 max-h-[360px]">
              {listDiscussion?.length > 1 ? (
                listDiscussion?.map((data: any) => (
                  <div key={data?.id} className="flex flex-col ">
                    <div className="flex flex-row gap-2 items-center">
                      <Icon icon="qlementine-icons:user-16" width={36} />
                      <div className="flex flex-col w-full">
                        <div className="flex justify-between items-center">
                          <p className="text-sm font-semibold">
                            {data?.messageFrom?.fullname}
                          </p>
                          <p className="text-xs">
                            {getLocaleTimestamp(new Date(data?.createdAt))}
                          </p>
                        </div>
                        <div className="flex justify-between items-center">
                          <p className="text-sm">{data?.message}</p>
                          <a
                            onClick={() => deleteDataSuggestion(data?.id)}
                            className="text-destructive cursor-pointer text-xs"
                          >
                            Hapus
                          </a>
                        </div>
                      </div>
                    </div>
                    <Separator className="my-2" />
                  </div>
                ))
              ) : (
                <p>Belum Ada Tanggapan</p>
              )}
            </div>
            <Textarea
              value={replyValue}
              onChange={(e) => setReplyValue(e.target.value)}
            />
            <div className="flex justify-end py-3">
              <Button
                className="w-fit"
                color="primary"
                size="sm"
                type="button"
                onClick={sendDiscussionParent}
              >
                Kirim
              </Button>
            </div>
          </div>
        </div>{" "}
        <UsersCard team={teams} fetchData={() => initState()} />
      </div>
    </div>
  );
}
