"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 {
  getTicketingDetail,
  getTicketingInternalDetail,
  getTicketingInternalDiscussion,
  saveTicketInternalReply,
} from "@/service/communication/communication";
import { Textarea } from "@/components/ui/textarea";

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 escalationDetail = {
  id: number;
  title: string;
  createdAt: string;
  commentFromUserName: string;
  message: string;
  createdBy: {
    id: number;
    fullname: string;
  };
  sendTo: {
    id: number;
    fullname: string;
  };
  status: {
    id: number;
    name: string;
  };
  priority: {
    id: number;
    name: string;
  };
  description: 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 default function FormDetailEscalation() {
  const MySwal = withReactContent(Swal);
  const { id } = useParams() as { id: string };

  const [detail, setDetail] = useState<escalationDetail>();
  const [ticketReply, setTicketReply] = useState<replyDetail[]>([]);
  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 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); // 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);
    }
  };

  return (
    <Card>
      <div className="px-6 py-6">
        <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="px-3 py-3 bg-slate-300 rounded-md text-lg font-semibold">
                  Ticket #{detail.id}
                </p>
                <div className="flex flex-row gap-3 mt-3 bg-blue-300 py-2 px-2">
                  <Avatar>
                    <AvatarImage
                      src={"/images/avatar/avatar-3.png"}
                      alt={`mabes`}
                    />
                  </Avatar>
                  <div>
                    <p>
                      <span className="font-bold">
                        {detail?.commentFromUserName}
                      </span>{" "}
                      mengirimkan pesan untuk{" "}
                      <span className="font-bold">{detail?.message}</span>
                    </p>
                    <p>{detail?.createdAt}</p>
                  </div>
                </div>
                <p className="pl-3 bg-white">{detail.message}</p>
              </div>
            )}
          </div>
        </div>
        {detail !== undefined && (
          <div className="gap-5 mb-5 w-full border mt-3 rounded-md">
            <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="mt-4 px-3 mb-3">
              <Label htmlFor="replyMessage">Tulis Pesan</Label>
              <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>
        )}
      </div>
    </Card>
  );
}
