"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 {
  getEscalationDiscussion,
  getQuestionTicket,
  getTicketingDetail,
  getTicketingInternalDetail,
  getTicketingInternalDiscussion,
  saveTicketInternalReply,
  saveTicketsQuestion,
} 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 { DetailTicket } from "../ticketing/info-lainnya-types";
import { Description } from "@radix-ui/react-toast";

const taskSchema = z.object({
  title: z.string().min(1, { message: "Judul diperlukan" }),
  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 FormQuestionsForward() {
  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 [listDiscussion, setListDiscussion] = useState();
  const [message, setMessage] = useState("");

  const [detailTickets, setDetailTickets] = useState<DetailTicket | null>(null);
  const [selectedPriority, setSelectedPriority] = useState("");
  const [replyMessage, setReplyMessage] = useState("");
  const [selectedStatus, setSelectedStatus] = useState("");
  const [replies, setReplies] = useState([
    {
      id: 1,
      name: "Mabes Polri - Approver",
      message: "test",
      timestamp: "2024-12-20 00:56:10",
    },
    {
      id: 2,
      name: "Mabes Polri - Approver",
      message: "balas",
      timestamp: "2025-01-18 17:42:48",
    },
  ]);

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

  useEffect(() => {
    async function initState() {
      const response = await getQuestionTicket(id);
      setDetail(response?.data?.data);

      if (response?.data !== null) {
        setDetailTickets(response?.data?.data);
      }

      if (detailTickets?.emergencyIssue) {
        reset({
          title: detailTickets.emergencyIssue.title || "",
          description: detailTickets.emergencyIssue.description || "",
        });
        // setSelectedPriority(String(detailTickets.emergencyIssue.urgencyId));
        // setSelectedStatus(String(detailTickets.statusId)); // jika ada
      }
    }
    initState();
    getTicketReply();
  }, [id, reset]);

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

  const onSubmit = async (data: any) => {
    try {
      const payload = {
        id,
        title: data.title,
        description: data.description,
        priorityId: selectedPriority,
        statusId: selectedStatus,
        typeId: detailTickets?.typeId,
        parentCommentId: detailTickets?.feedId,
      };

      const response = await saveTicketsQuestion(payload);

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

      // Refresh data jika perlu
      getTicketReply();
    } catch (error) {
      console.error("Gagal update:", error);
      MySwal.fire({
        title: "Error",
        text: "Terjadi kesalahan saat memperbarui.",
        icon: "error",
      });
    }
  };

  const handleSendReply = () => {
    if (replyMessage.trim() === "") return;

    const newReply = {
      id: replies.length + 1,
      name: "Mabes Polri - Approver", // Sesuaikan dengan data dinamis jika ada
      message: replyMessage,
      timestamp: new Date().toISOString().slice(0, 19).replace("T", " "),
    };

    setReplies([...replies, newReply]);
    setReplyMessage("");
  };

  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>
          )}
        </div>
      </div>
      {detailTickets && (
        <form onSubmit={handleSubmit(onSubmit)}>
          <div className="gap-5 mb-5 w-[100%] lg:w-auto 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"
                    {...field}
                    placeholder="Masukkan judul"
                  />
                )}
              />
            </div>

            <div className="mt-5 px-3">
              <Label>Prioritas</Label>
              <Select
                onValueChange={setSelectedPriority}
                value={selectedPriority}
              >
                <SelectTrigger size="md">
                  <SelectValue placeholder="Pilih Prioritas" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="1">Low</SelectItem>
                  <SelectItem value="2">Medium</SelectItem>
                  <SelectItem value="3">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 Status" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="1">Open</SelectItem>
                  <SelectItem value="2">Close</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div className="space-y-2 px-3 py-3">
              <Label>Deskripsi</Label>
              <Controller
                control={control}
                name="description"
                render={({ field }) => (
                  <Textarea {...field} placeholder="Masukkan description" />
                )}
              />
            </div>

            <div className="flex justify-end mt-3 mr-3 py-3">
              <Button type="submit" color="primary">
                Simpan
              </Button>
            </div>
          </div>
        </form>
      )}
    </div>
  );
}
