"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, useRouter } from "next/navigation";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Avatar, AvatarImage } from "@/components/ui/avatar";
import {
  getTicketingInternalDetail,
  getTicketingInternalDiscussion,
  saveTicketing,
  saveTicketInternalReply,
} from "@/service/communication/communication";
import { Textarea } from "@/components/ui/textarea";
import { htmlToString } from "@/utils/globals";
import { Icon } from "@iconify/react/dist/iconify.js";

const taskSchema = z.object({
  // description: 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 FormEditInternal() {
  const MySwal = withReactContent(Swal);
  const { id } = useParams() as { id: string };
  const router = useRouter();

  const [detail, setDetail] = useState<any>();
  const [ticketReply, setTicketReply] = useState<replyDetail[]>([]);
  const [replyVisible, setReplyVisible] = useState(false);
  const [replyMessage, setReplyMessage] = useState("");
  const [selectedPriority, setSelectedPriority] = useState("");
  const [selectedStatus, setSelectedStatus] = useState("");
  const [selectedTarget, setSelectedTarget] = useState("");
  const [description, setDescription] = useState("");
  type TaskSchema = z.infer<typeof taskSchema>;

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

  useEffect(() => {
    async function initState() {
      if (id) {
        const response = await getTicketingInternalDetail(id);
        setDetail(response?.data?.data);
        setSelectedPriority(response?.data?.data?.priority?.name);
        console.log("sadad", response?.data?.data);
        setSelectedStatus(response?.data?.data?.status?.name);
        setDescription(htmlToString(response?.data?.data?.message));
      }
    }
    initState();
    getTicketReply();
  }, [id]);

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

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

  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 {
      const response = await saveTicketInternalReply(data);

      // Tambahkan balasan baru ke daftar balasan
      const newReply: replyDetail = {
        id: response?.data?.id,
        message: replyMessage,
        createdAt: response?.data?.createdAt,
        messageFrom: response?.data?.messageFrom,
        messageTo: response?.data?.messageTo,
      };

      setTicketReply((prevReplies) => [newReply, ...prevReplies]);

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

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

  const save = async (data: TaskSchema) => {
    const requestData = {
      // description: data?.description,
      target: selectedTarget,
      priorityId: 1,
      statusId: 1,
      // description: data.description,
      // operatorTeam: selectedOptionId.join(","), // This should work now without the error
    };

    const response = await saveTicketing(requestData);

    console.log("Form Data Submitted:", requestData);
    console.log("response", response);

    MySwal.fire({
      title: "Sukses",
      text: "Data berhasil disimpan.",
      icon: "success",
      confirmButtonColor: "#3085d6",
      confirmButtonText: "OK",
    }).then(() => {
      router.push("/en/shared/communication");
    });
  };

  const onSubmit = (data: TaskSchema) => {
    MySwal.fire({
      title: "Simpan Data",
      text: "Apakah Anda yakin ingin menyimpan data ini?",
      icon: "warning",
      showCancelButton: true,
      cancelButtonColor: "#d33",
      confirmButtonColor: "#3085d6",
      confirmButtonText: "Simpan",
    }).then((result) => {
      if (result.isConfirmed) {
        save(data);
      }
    });
  };

  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-row gap-5 mt-5">
        <div className="flex flex-col w-[70%]">
          {replyVisible && (
            <div>
              <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 mt-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">
                        {list?.messageFrom?.fullname}
                      </span>{" "}
                      mengirimkan pesan untuk{" "}
                      <span className="font-bold">
                        {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="pl-3 bg-white py-2">{list.message}</p>
              </div>
            ))}
          </div>
        </div>
        {detail !== undefined && (
          <form onSubmit={handleSubmit(onSubmit)} className="w-[30%]">
            <div className="gap-5 mb-5  border bg-white rounded-xl">
              <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={selectedPriority}
                >
                  <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={selectedStatus}
                >
                  <SelectTrigger size="md">
                    <SelectValue placeholder="Pilih" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="Open">Open</SelectItem>
                    <SelectItem value="Close">Close</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-2 px-3">
                <Label>Description</Label>

                <Textarea
                  value={description}
                  onChange={(e) => setDescription(e.target.value)}
                  placeholder="Enter description"
                />
              </div>
              <div className="flex justify-end mt-3 mr-3">
                <Button type="submit" color="primary">
                  Update
                </Button>
              </div>
            </div>
          </form>
        )}
      </div>
    </div>
  );
}
