"use client";

import { useState, useEffect } from "react";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import { MessageCircle, Share2, Trash2 } from "lucide-react";
import { useRouter, useParams } from "next/navigation";
import {
  getArticleDetail,
  createArticleComment,
  getArticleComments,
  deleteArticleComment,
} from "@/service/content/content";
import { getCookiesDecrypt } from "@/lib/utils";
import Swal from "sweetalert2";
import withReactContent from "sweetalert2-react-content";

// 🎨 Avatar color helper
function getAvatarColor(name: string) {
  const colors = [
    "#F87171",
    "#FB923C",
    "#FACC15",
    "#4ADE80",
    "#60A5FA",
    "#A78BFA",
    "#F472B6",
  ];
  const index = name.charCodeAt(0) % colors.length;
  return colors[index];
}

export default function DetailCommentText() {
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const [currentUserId, setCurrentUserId] = useState<number | null>(null);
  const [textArticle, setTextArticle] = useState<any>(null);
  const [comments, setComments] = useState<any[]>([]);
  const [newComment, setNewComment] = useState("");
  const [replyParentId, setReplyParentId] = useState<number | null>(null);
  const [replyMessage, setReplyMessage] = useState("");
  const router = useRouter();
  const params = useParams();
  const MySwal = withReactContent(Swal);
  const id = Number(params?.id);

  // 🚀 Initial load
  useEffect(() => {
    checkLoginStatus();
    if (id) {
      fetchTextDetail(id);
      fetchComments(id);
    }
  }, [id]);

  // 🔐 Cek login user dari cookies
  const checkLoginStatus = () => {
    const userId = getCookiesDecrypt("urie");
    if (userId) {
      setIsLoggedIn(true);
      setCurrentUserId(Number(userId));
    } else {
      setIsLoggedIn(false);
      setCurrentUserId(null);
    }
  };

  // 📄 Ambil detail artikel text
  const fetchTextDetail = async (textId: number) => {
    try {
      const res = await getArticleDetail(textId);
      if (res?.data?.data) setTextArticle(res.data.data);
    } catch (error) {
      console.error("Gagal memuat detail artikel:", error);
    }
  };

  // 💬 Ambil komentar dari API
  const fetchComments = async (textId: number) => {
    try {
      const res = await getArticleComments(textId);
      if (res?.data?.data) {
        const all = res.data.data.map((c: any) => ({
          ...c,
          parentId: c.parentId ?? 0,
        }));
        const structured = buildCommentTree(all);
        setComments(structured);
      }
    } catch (error) {
      console.error("Gagal memuat komentar:", error);
    }
  };

  // 🪄 Susun komentar menjadi struktur nested (tree)
  const buildCommentTree: any = (comments: any[], parentId = 0) =>
    comments
      .filter((c) => c.parentId === parentId)
      .map((c) => ({
        ...c,
        replies: buildCommentTree(comments, c.id),
      }));

  // ✏️ Kirim komentar baru
  const handlePostComment = async () => {
    if (!newComment.trim()) {
      MySwal.fire("Oops!", "Komentar tidak boleh kosong.", "warning");
      return;
    }
    await sendComment({
      articleId: id,
      message: newComment,
      isPublic: true,
      parentId: 0,
    });
    setNewComment("");
  };

  // 💬 Kirim balasan komentar
  const handleReplySubmit = async (parentId: number) => {
    if (!replyMessage.trim()) {
      MySwal.fire("Oops!", "Balasan tidak boleh kosong.", "warning");
      return;
    }
    await sendComment({
      articleId: id,
      message: replyMessage,
      isPublic: true,
      parentId,
    });
    setReplyMessage("");
    setReplyParentId(null);
  };

  // 🚀 Fungsi umum untuk kirim komentar / balasan
  const sendComment = async (payload: any) => {
    MySwal.fire({
      title: "Mengirim komentar...",
      didOpen: () => MySwal.showLoading(),
      allowOutsideClick: false,
      showConfirmButton: false,
    });

    try {
      const res = await createArticleComment(payload);
      if (res?.data?.success || !res?.error) {
        MySwal.fire({
          icon: "success",
          title: "Komentar terkirim!",
          timer: 1000,
          showConfirmButton: false,
        });
        fetchComments(id);
      } else {
        MySwal.fire(
          "Gagal",
          res.message || "Tidak dapat mengirim komentar.",
          "error"
        );
      }
    } catch (error) {
      console.error(error);
      MySwal.fire("Error", "Terjadi kesalahan saat mengirim komentar.", "error");
    }
  };

  // 🗑️ Hapus komentar
  const handleDeleteComment = async (commentId: number) => {
    const confirm = await MySwal.fire({
      title: "Hapus komentar ini?",
      text: "Tindakan ini tidak dapat dibatalkan!",
      icon: "warning",
      showCancelButton: true,
      confirmButtonColor: "#d33",
      cancelButtonColor: "#6b7280",
      confirmButtonText: "Ya, hapus",
      cancelButtonText: "Batal",
    });

    if (!confirm.isConfirmed) return;

    MySwal.fire({
      title: "Menghapus komentar...",
      didOpen: () => MySwal.showLoading(),
      allowOutsideClick: false,
      showConfirmButton: false,
    });

    try {
      const res = await deleteArticleComment(commentId);
      if (res?.data?.success || !res?.error) {
        MySwal.fire({
          icon: "success",
          title: "Komentar dihapus!",
          timer: 1000,
          showConfirmButton: false,
        });
        fetchComments(id);
      } else {
        MySwal.fire(
          "Gagal",
          res.message || "Tidak dapat menghapus komentar.",
          "error"
        );
      }
    } catch (error) {
      console.error("Gagal menghapus komentar:", error);
      MySwal.fire("Error", "Terjadi kesalahan saat menghapus komentar.", "error");
    }
  };

  return (
    <div className="max-w-5xl mx-auto p-4 space-y-6">
      <button
        onClick={() => router.back()}
        className="text-sm text-gray-500 hover:underline cursor-pointer"
      >
        ← Kembali ke Artikel Teks
      </button>

      <div>
        <p className="font-semibold text-sm uppercase text-gray-600 mb-1">
          Comments on:
        </p>
        <h1 className="text-lg font-bold">
          {textArticle?.title || "Memuat judul artikel..."}
        </h1>
      </div>

      {/* ✏️ Form komentar */}
      <div className="rounded-md p-3 space-y-3 bg-gray-50 border border-gray-200 shadow-sm">
        {isLoggedIn ? (
          <>
            <Textarea
              placeholder="Tulis komentar kamu di sini..."
              className="min-h-[80px] border border-[#C6A455]"
              value={newComment}
              onChange={(e) => setNewComment(e.target.value)}
            />
            <div className="flex justify-end">
              <Button size="sm" onClick={handlePostComment}>
                Kirim Komentar
              </Button>
            </div>
          </>
        ) : (
          <>
            <Textarea
              disabled
              placeholder="Tulis komentar kamu di sini..."
              className="min-h-[80px] opacity-70"
            />
            <Button
              onClick={() => router.push("/auth")}
              className="w-full bg-blue-600 hover:bg-blue-700 text-white"
            >
              Sign in and Join the Conversation
            </Button>
          </>
        )}
      </div>

      {/* 💬 Daftar komentar */}
      <div className="space-y-6">
        {comments.length > 0 ? (
          comments.map((comment) => (
            <CommentTree
              key={comment.id}
              comment={comment}
              level={0}
              replyParentId={replyParentId}
              setReplyParentId={setReplyParentId}
              replyMessage={replyMessage}
              setReplyMessage={setReplyMessage}
              onReplySubmit={handleReplySubmit}
              onDelete={handleDeleteComment}
              currentUserId={currentUserId}
            />
          ))
        ) : (
          <p className="text-sm text-gray-500 text-center py-4">
            Belum ada komentar.
          </p>
        )}
      </div>
    </div>
  );
}

// 🧱 Komponen rekursif untuk komentar & balasan
function CommentTree({
  comment,
  level,
  replyParentId,
  setReplyParentId,
  replyMessage,
  setReplyMessage,
  onReplySubmit,
  onDelete,
  currentUserId,
}: any) {
  const color = getAvatarColor(comment.commentFromName || "Anonim");

  const canDelete =
    currentUserId &&
    (comment.commentFromId == currentUserId ||
      comment.userId == currentUserId ||
      comment.createdBy == currentUserId);

  return (
    <div
      className={`space-y-3 ${
        level > 0 ? "ml-6 border-l-2 border-gray-200 pl-4" : ""
      }`}
    >
      <div className="p-2 rounded-lg transition hover:bg-gray-50 bg-white">
        <div className="flex items-start gap-2">
          <div
            className="w-8 h-8 rounded-full flex items-center justify-center text-white font-bold"
            style={{ backgroundColor: color }}
          >
            {comment.commentFromName?.[0]?.toUpperCase() || "U"}
          </div>
          <div className="flex-1">
            <p className="font-semibold text-sm">
              {comment.commentFromName}{" "}
              <span className="text-gray-500 text-xs font-normal">
                {new Date(comment.createdAt).toLocaleString("id-ID")}
              </span>
            </p>
            <p className="text-gray-800 text-sm leading-snug mt-1">
              {comment.message}
            </p>

            <div className="flex items-center gap-3 mt-1 text-xs text-gray-600">
              <button
                onClick={() =>
                  setReplyParentId(
                    replyParentId === comment.id ? null : comment.id
                  )
                }
                className="hover:underline flex items-center gap-1"
              >
                <MessageCircle className="w-3 h-3" /> Reply
              </button>
              <button className="hover:underline flex items-center gap-1">
                <Share2 className="w-3 h-3" /> Share
              </button>

              {canDelete && (
                <button
                  onClick={() => onDelete(comment.id)}
                  className="flex items-center gap-1 px-2 py-1 text-xs bg-red-100 text-red-600 rounded-md hover:bg-red-200"
                >
                  <Trash2 className="w-3 h-3" /> Delete
                </button>
              )}
            </div>
          </div>
        </div>

        {replyParentId === comment.id && (
          <div className="mt-3 ml-10 space-y-2">
            <Textarea
              placeholder={`Balas komentar ${comment.commentFromName}`}
              className="min-h-[60px] border border-[#C6A455]"
              value={replyMessage}
              onChange={(e) => setReplyMessage(e.target.value)}
            />
            <div className="flex justify-end gap-2">
              <Button
                variant="outline"
                size="sm"
                onClick={() => setReplyParentId(null)}
              >
                Batal
              </Button>
              <Button
                variant="outline"
                size="sm"
                onClick={() => onReplySubmit(comment.id)}
              >
                Kirim Balasan
              </Button>
            </div>
          </div>
        )}
      </div>

      {comment.replies && comment.replies.length > 0 && (
        <div className="space-y-3">
          {comment.replies.map((reply: any) => (
            <CommentTree
              key={reply.id}
              comment={reply}
              level={level + 1}
              replyParentId={replyParentId}
              setReplyParentId={setReplyParentId}
              replyMessage={replyMessage}
              setReplyMessage={setReplyMessage}
              onReplySubmit={onReplySubmit}
              onDelete={onDelete}
              currentUserId={currentUserId}
            />
          ))}
        </div>
      )}
    </div>
  );
}
