"use client";
"use client";
import React, { useEffect, useState } from "react";
import { useForm, Controller } from "react-hook-form";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import { Card } from "@/components/ui/card";
import { zodResolver } from "@hookform/resolvers/zod";
import * as z from "zod";
import Swal from "sweetalert2";
import withReactContent from "sweetalert2-react-content";
import { useParams } from "next/navigation";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Avatar, AvatarImage } from "@/components/ui/avatar";
import {
  deleteEscalationDiscussion,
  getEscalationDiscussion,
  getTicketingDetail,
  getTicketingInternalDetail,
  getTicketingInternalDiscussion,
  saveEscalationDiscussion,
  saveTicketInternalReply,
} from "@/service/communication/communication";
import { Textarea } from "@/components/ui/textarea";
import { Icon } from "@iconify/react/dist/iconify.js";
import { Link } from "@/i18n/routing";
import { loading } from "@/lib/swal";
import { id } from "date-fns/locale";
import { htmlToString } from "@/utils/globals";
import InfoLainnyaModal from "../ticketing/info-lainnya";
import { PlusIcon } from "lucide-react";

const taskSchema = z.object({
  title: z.string().min(1, { message: "Judul diperlukan" }),
  naration: z.string().min(2, {
    message: "Narasi Penugasan harus lebih dari 2 karakter.",
  }),
});

export type replyDetail = {
  id: number;
  message: string;
  createdAt: string;
  messageFrom: {
    id: number;
    fullname: string;
  };
  messageTo: {
    id: number;
    fullname: string;
  };
};

export default function FormDetailEscalation() {
  const MySwal = withReactContent(Swal);
  const { id } = useParams() as { id: string };

  const [detail, setDetail] = useState<any>();
  const [ticketReply, setTicketReply] = useState<replyDetail[]>([]);
  const [replyVisible, setReplyVisible] = useState(false);
  const [activeReplyId, setActiveReplyId] = useState<number | null>(null);
  const [selectedPriority, setSelectedPriority] = useState("");
  const [openEmergencyModal, setOpenEmergencyModal] = useState(false);
  const [replyMessage, setReplyMessage] = useState("");
  const [listDiscussion, setListDiscussion] = useState([]);
  const [message, setMessage] = useState("");

  const {
    control,
    handleSubmit,
    formState: { errors },
  } = useForm({
    resolver: zodResolver(taskSchema),
  });

  useEffect(() => {
    async function initState() {
      if (id) {
        const response = await getTicketingDetail(id);
        setDetail(response?.data?.data);
      }
    }
    initState();
    getTicketReply();
  }, [id]);

  async function getTicketReply() {
    const res = await getTicketingInternalDiscussion(id);
    if (res?.data !== null) {
      setTicketReply(res?.data?.data);
    }
  }

  const handleReply = () => {
    setReplyVisible((prev) => !prev);
  };

  useEffect(() => {
    const fetchDiscussion = async () => {
      const response = await getEscalationDiscussion(id);
      setListDiscussion(response?.data?.data || []);
    };

    fetchDiscussion();
  }, []);

  const postData = async () => {
    if (!message.trim()) return;

    const payload = {
      ticketId: id,
      message,
      parentId: null,
    };

    try {
      await saveEscalationDiscussion(payload);
      setMessage("");

      const response = await getEscalationDiscussion(id);
      setListDiscussion(response?.data?.data || []);
    } catch (error) {
      console.error("Gagal mengirim tanggapan:", error);
    }
  };

  const postDataChild = async (parentId: any) => {
    const textarea = document.getElementById(
      `input-comment-${parentId}`
    ) as HTMLTextAreaElement | null;
    const replyMessage = textarea?.value;

    if (!replyMessage?.trim()) return;

    const payload = {
      ticketId: Number(id),
      parentMessageId: parentId,
      message: replyMessage,
    };

    try {
      await saveEscalationDiscussion(payload);
      if (textarea) textarea.value = "";

      const response = await getEscalationDiscussion(id);
      setListDiscussion(response?.data?.data || []);
    } catch (error) {
      console.error("Gagal mengirim balasan:", error);
    }
  };

  const openEmergencyIssueDetail = () => {
    setOpenEmergencyModal(true);
  };

  async function deleteDataSuggestion(dataId: any) {
    const response = await deleteEscalationDiscussion(dataId);
    console.log(response);

    const responseGet = await getEscalationDiscussion(id);
    setListDiscussion(responseGet?.data?.data);
  }

  return (
    <div>
      <div className="flex">
        <div className="flex flex-col mt-6 w-full mb-3">
          {detail !== undefined && (
            <div key={detail?.id} className="bg-slate-300  rounded-md">
              <p className="p-5 bg-slate-300 rounded-md text-lg font-semibold">
                Ticket #{detail.id}
              </p>
              <div className="flex flex-row gap-3 bg-sky-100 p-5 items-center">
                <Icon icon="qlementine-icons:user-16" width={36} />

                <div>
                  <p>
                    <span className="font-bold">
                      {detail?.commentFromUserName}
                    </span>
                    {` `}
                    mengirimkan pesan untuk{` `}
                    <Link
                      href={
                        detail?.feed
                          ? detail?.feed?.permalink_url == undefined
                            ? detail?.feedUrl
                            : detail?.feed?.permalink_url
                          : ""
                      }
                      target="_blank"
                      className="font-bold"
                    >
                      {detail?.message}
                    </Link>
                  </p>
                  <p className="text-xs">
                    {`${new Date(detail?.createdAt).getDate()}-${
                      new Date(detail?.createdAt).getMonth() + 1
                    }-${new Date(detail?.createdAt).getFullYear()} ${new Date(
                      detail?.createdAt
                    ).getHours()}:${new Date(detail?.createdAt).getMinutes()}`}
                  </p>
                </div>
              </div>
              <p className="p-5 bg-white">{detail.message}</p>
              <div className="px-4 py-1 bg-white text-sm">
                {detail?.typeId === 6 && detail?.emergencyIssue ? (
                  <div className="row mx-0 mb-3 emergency-attachments">
                    <div className=" mr-4">
                      <Button
                        color="primary"
                        size="md"
                        onClick={openEmergencyIssueDetail}
                      >
                        Info Lainnya
                      </Button>
                    </div>
                  </div>
                ) : null}

                {detail?.emergencyIssue && (
                  <InfoLainnyaModal
                    open={openEmergencyModal}
                    onClose={() => setOpenEmergencyModal(false)}
                    data={detail.emergencyIssue}
                  />
                )}
              </div>
            </div>
          )}
        </div>
      </div>
      {detail !== undefined && (
        <div className="gap-5 mb-5 w-full border mt-3 rounded-md bg-white">
          <div className="space-y-2 px-3 mt-3">
            <Label>Judul</Label>
            <Controller
              control={control}
              name="title"
              render={({ field }) => (
                <Input
                  size="md"
                  type="text"
                  value={detail?.title}
                  onChange={field.onChange}
                  placeholder="Enter Title"
                />
              )}
            />
            {/* {errors.title?.message && (
                  <p className="text-red-400 text-sm">
                    {errors.title.message}
                  </p>
                )} */}
          </div>
          <div className="mt-5 px-3">
            <Label>Prioritas</Label>
            <Select
              onValueChange={setSelectedPriority}
              value={detail?.priority?.name}
            >
              <SelectTrigger size="md" className="w-3/12">
                <SelectValue placeholder="Pilih" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="Low">Low</SelectItem>
                <SelectItem value="Medium">Medium</SelectItem>
                <SelectItem value="High">High</SelectItem>
              </SelectContent>
            </Select>
          </div>
          <div className="space-y-2 px-3 mt-3">
            <Label>Description</Label>
            <Controller
              control={control}
              name="title"
              render={({ field }) => (
                <Textarea
                  value={detail?.description}
                  onChange={field.onChange}
                  placeholder="Enter Title"
                />
              )}
            />
            {/* {errors.title?.message && (
                  <p className="text-red-400 text-sm">
                    {errors.title.message}
                  </p>
                )} */}
          </div>
          <div className="mx-3 my-3">
            <h3 className="text-gray-700 font-medium">Tanggapan</h3>
            <div className="space-y-4 ml-5 mt-5">
              {listDiscussion.map((parent: any) => (
                <div key={parent.id} className="border-b pb-4">
                  <div className="flex justify-between items-start">
                    <div>
                      <p className="font-semibold text-gray-800">
                        {parent.messageFrom?.fullname}
                      </p>
                      <p className="text-gray-600">{parent.message}</p>
                      <p className="text-sm text-gray-400">
                        {parent.createdAt}
                      </p>
                    </div>
                    <button
                      onClick={() => deleteDataSuggestion(parent.id)}
                      className="text-red-500 text-sm hover:underline ml-2"
                    >
                      Hapus
                    </button>
                  </div>

                  {activeReplyId !== parent.id && (
                    <button
                      onClick={() => setActiveReplyId(parent.id)}
                      className="text-blue-500 text-sm mt-2 hover:underline"
                    >
                      Balas
                    </button>
                  )}

                  {activeReplyId === parent.id && (
                    <div className="mt-2">
                      <textarea
                        id={`input-comment-${parent.id}`}
                        className="w-full h-20 border border-gray-300 rounded-md p-2"
                        placeholder="Tulis balasan di sini..."
                      />
                      <div className="flex justify-end gap-2 mt-2">
                        <button
                          onClick={() => setActiveReplyId(null)}
                          className="px-4 py-1 text-sm bg-gray-200 text-gray-800 rounded-md"
                        >
                          Batal
                        </button>
                        <button
                          onClick={() => {
                            postDataChild(parent.id);
                            setActiveReplyId(null);
                          }}
                          className="px-4 py-1 text-sm bg-blue-600 text-white rounded-md"
                        >
                          Kirim
                        </button>
                      </div>
                    </div>
                  )}

                  {parent.children?.length > 0 && (
                    <div className="ml-4 mt-3 space-y-3 border-l-2 pl-4 border-gray-200">
                      {parent.children.map((child: any) => (
                        <div
                          key={child.id}
                          className="flex justify-between items-start"
                        >
                          <div>
                            <p className="font-semibold text-gray-800">
                              {child.messageFrom?.fullname}
                            </p>
                            <p className="text-gray-600">{child.message}</p>
                            <p className="text-sm text-gray-400">
                              {child.createdAt}
                            </p>
                          </div>
                          <button
                            onClick={() => deleteDataSuggestion(child.id)}
                            className="text-red-500 text-sm hover:underline ml-2"
                          >
                            Hapus
                          </button>
                        </div>
                      ))}
                    </div>
                  )}
                </div>
              ))}
            </div>

            <div className="mt-6">
              <label className="block text-gray-700 font-medium mb-2">
                Tulis Tanggapan Anda
              </label>
              <textarea
                value={message}
                onChange={(e) => setMessage(e.target.value)}
                className="w-full h-24 border border-gray-300 rounded-md p-2"
                placeholder="Tulis tanggapan anda di sini..."
              />
              <Button size="sm" variant={"outline"} color="primary">
                <PlusIcon />
                Lampiran
              </Button>
              <div className="flex justify-end gap-3 mt-2 mb-3">
                <button
                  onClick={() => setMessage("")}
                  className="px-4 py-2 bg-gray-200 text-gray-800 rounded-md"
                >
                  Batal
                </button>
                <button
                  onClick={postData}
                  className="px-4 py-2 bg-blue-600 text-white rounded-md"
                >
                  Kirim Pesan
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
