"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 {
  getTicketingInternalDetail,
  getTicketingInternalDiscussion,
  saveTicketInternalReply,
} from "@/service/communication/communication";
import { Icon } from "@iconify/react/dist/iconify.js";
import { list } from "postcss";
import { htmlToString } from "@/utils/globals";

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 taskDetail = {
  id: number;
  title: string;
  createdAt: string;
  referenceNumber: string | number;
  createdBy: {
    id: number;
    fullname: string;
  };
  sendTo: {
    id: number;
    fullname: string;
  };
  status: {
    id: number;
    name: string;
  };
  priority: {
    id: number;
    name: string;
  };
  broadcastType: string;
  narration: string;
  is_active: string;
};

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

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

  const [detail, setDetail] = useState<taskDetail>();
  const [ticketReply, setTicketReply] = useState<replyDetail[]>([]);
  const [ticketInternal, setTicketInternal] = useState<internalDetail | null>(
    null
  );
  const [replyVisible, setReplyVisible] = useState(false);
  const [replyMessage, setReplyMessage] = useState("");
  const [selectedPriority, setSelectedPriority] = useState("");
  const [selectedStatus, setSelectedStatus] = useState("");

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

  useEffect(() => {
    async function initState() {
      if (id) {
        const response = await getTicketingInternalDetail(id);
        setTicketInternal(response?.data?.data || null);
        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);
  };

  const handleSendReply = async () => {
    if (replyMessage.trim() === "") {
      MySwal.fire({
        title: "Error",
        text: "Pesan tidak boleh kosong!",
        icon: "error",
      });
      return;
    }

    const data = {
      ticketId: id,
      message: replyMessage,
    };

    try {
      await saveTicketInternalReply(data);

      await getTicketReply();

      MySwal.fire({
        title: "Sukses",
        text: "Pesan berhasil dikirim.",
        icon: "success",
      });

      setReplyMessage("");
      setReplyVisible(false);
    } catch (error) {
      MySwal.fire({
        title: "Error",
        text: "Gagal mengirim balasan.",
        icon: "error",
      });
      console.error("Error sending reply:", error);
    }
  };

  return (
    <div className="py-5">
      <div className="mt-4 flex flex-row items-center gap-3">
        <Button onClick={handleReply} color="default" variant={"outline"}>
          Balas
        </Button>

        <Button color="default" variant={"outline"}>
          Hapus
        </Button>
      </div>

      <div className="flex flex-col md:flex-row    lg:flex-row gap-5 mt-5">
        <div className="flex flex-col w-[100%] lg:w-[70%]">
          {replyVisible && (
            <div className="">
              <textarea
                id="replyMessage"
                className="w-full h-24 border rounded-md p-2"
                value={replyMessage}
                onChange={(e) => setReplyMessage(e.target.value)}
                placeholder="Tulis pesan di sini..."
              />
              <div className="flex justify-end gap-3 my-2">
                <Button
                  onClick={() => setReplyVisible(false)}
                  color="default"
                  variant="outline"
                >
                  Batal
                </Button>
                <Button onClick={handleSendReply} color="primary">
                  Kirim
                </Button>
              </div>
            </div>
          )}
          <div className="border rounded-t-xl">
            <p className="p-4 bg-slate-300 rounded-t-xl text-lg font-semibold">
              Ticket #{detail?.referenceNumber}
            </p>

            {ticketReply?.map((list) => (
              <div key={list.id} className="flex flex-col">
                <div className="flex flex-row gap-3 bg-sky-100 p-4 items-center">
                  <Icon icon="qlementine-icons:user-16" width={36} />
                  <div>
                    <p>
                      <span className="font-bold text-sm">
                        {list?.messageFrom?.fullname}
                      </span>{" "}
                      mengirimkan pesan untuk{" "}
                      <span className="font-bold text-sm">
                        {list?.messageTo?.fullname}
                      </span>
                    </p>
                    <p className="text-xs">
                      {`${new Date(list?.createdAt).getDate()}-${
                        new Date(list?.createdAt).getMonth() + 1
                      }-${new Date(list?.createdAt).getFullYear()} ${new Date(
                        list?.createdAt
                      ).getHours()}:${new Date(list?.createdAt).getMinutes()}`}
                    </p>
                  </div>
                </div>
                <p className="p-4 bg-white text-sm">{list.message}</p>
              </div>
            ))}
            {ticketInternal && (
              <div key={ticketInternal.id} className="flex flex-col">
                <div className="flex flex-row gap-3 bg-sky-100 p-4 items-center">
                  <Icon icon="qlementine-icons:user-16" width={36} />
                  <div>
                    <p>
                      <span className="font-bold text-sm">
                        {ticketInternal?.createdBy?.fullname}
                      </span>{" "}
                      mengirimkan pesan untuk{" "}
                      <span className="font-bold text-sm">
                        {ticketInternal?.sendTo?.fullname}
                      </span>
                    </p>
                    <p className="text-xs">
                      {`${new Date(ticketInternal?.createdAt).getDate()}-${
                        new Date(ticketInternal?.createdAt).getMonth() + 1
                      }-${new Date(
                        ticketInternal?.createdAt
                      ).getFullYear()} ${new Date(
                        ticketInternal?.createdAt
                      ).getHours()}:${new Date(
                        ticketInternal?.createdAt
                      ).getMinutes()}`}
                    </p>
                  </div>
                </div>
                <p className="p-4 bg-white text-sm">
                  {htmlToString(ticketInternal.message)}
                </p>
              </div>
            )}
          </div>
        </div>
        {detail !== undefined && (
          <div className="gap-5 mb-5 w-[100%] lg:w-[30%] border bg-white rounded-md">
            <p className="mx-3 mt-3">Properties</p>
            <div className="space-y-2 px-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">
                  <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="mt-5 px-3 mb-3">
              <Label>Status</Label>
              <Select
                onValueChange={setSelectedStatus}
                value={detail?.status?.name}
              >
                <SelectTrigger size="md">
                  <SelectValue placeholder="Pilih" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="Open">Open</SelectItem>
                  <SelectItem value="Close">Close</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
