"use client";

import Image from "next/image";
import { useState, useEffect, useRef } from "react";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import {
  fetchComments,
  fetchReplies,
  addComment,
  editComment,
  deleteComment,
  makeKey,
  selectComments,
  selectCommentsLoaded,
  selectCommentsLoading,
  selectCommentsSubmitting,
  type CommentItem,
  type ContentKey,
} from "@/store/slices/commentSlice";
import { getStoredUser } from "@/lib/utils/persistAuth";
import { useToast } from "@/lib/toast";

function isValidImg(url?: string) {
  return !!url && !url.includes("no_img");
}
function fmtRelTime(d: string) {
  const diff = Date.now() - new Date(d).getTime();
  const m = Math.floor(diff / 60_000);
  const h = Math.floor(m / 60);
  if (m < 1) return "just now";
  if (m < 60) return `${m}m ago`;
  if (h < 24) return `${h}h ago`;
  return `${Math.floor(h / 24)}d ago`;
}

// ── Single comment row ────────────────────────────────────────────────────────
function CommentRow({
  comment,
  userId,
  contentKey,
  type,
  contentId,
  videoId,
  depth = 0,
}: {
  comment: CommentItem;
  userId: number;
  contentKey: ContentKey;
  type: number;
  contentId: number;
  videoId: number;
  depth?: number;
}) {
  const dispatch = useAppDispatch();
  const { success, error: showError } = useToast();
  const [editing, setEditing] = useState(false);
  const [editText, setEditText] = useState(comment.comment);
  const [replyOpen, setReplyOpen] = useState(false);
  const [replyText, setReplyText] = useState("");
  const [repliesVisible, setRepliesVisible] = useState(false);
  const submitting = useAppSelector(selectCommentsSubmitting);
  const isOwn = comment.user_id === userId;

  async function handleEdit() {
    if (!editText.trim()) return;
    const res = await dispatch(
      editComment({
        commentId: comment.id,
        comment: editText.trim(),
        contentKey,
      }),
    );
    if (editComment.fulfilled.match(res)) {
      setEditing(false);
      success("Comment updated");
    } else {
      showError("Failed to update");
    }
  }

  async function handleDelete() {
    const res = await dispatch(
      deleteComment({ commentId: comment.id, contentKey }),
    );
    if (deleteComment.fulfilled.match(res)) success("Comment deleted");
    else showError("Failed to delete");
  }

  async function handleReply() {
    if (!replyText.trim() || !userId) return;
    const user = getStoredUser();
    const res = await dispatch(
      addComment({
        userId,
        contentId,
        type,
        comment: replyText.trim(),
        commentId: comment.id,
        videoId,
        contentKey,
        userName: user?.full_name ?? "You",
        userImage: user?.image ?? "",
      }),
    );
    if (addComment.fulfilled.match(res)) {
      setReplyText("");
      setReplyOpen(false);
      success("Reply posted");
    } else {
      showError("Failed to post reply");
    }
  }

  async function loadReplies() {
    if (!repliesVisible) {
      await dispatch(fetchReplies({ commentId: comment.id, contentKey }));
    }
    setRepliesVisible((v) => !v);
  }

  const replies = comment.replies ?? [];

  return (
    <div style={{ paddingLeft: depth * 36, position: "relative" }}>
      {depth > 0 && (
        <div
          style={{
            position: "absolute",
            left: depth * 36 - 12,
            top: 0,
            bottom: 0,
            width: 1.5,
            background: "var(--border)",
          }}
        />
      )}

      <div
        style={{
          display: "flex",
          gap: "0.625rem",
          padding: "0.75rem 0",
          borderBottom: depth === 0 ? "1px solid var(--border)" : "none",
        }}
      >
        {/* Avatar */}
        <div
          style={{
            flexShrink: 0,
            width: 34,
            height: 34,
            borderRadius: "50%",
            overflow: "hidden",
            position: "relative",
            background: "var(--brand-08, rgba(193,39,45,0.08))",
          }}
        >
          {isValidImg(comment.user_image) ? (
            <Image
              src={comment.user_image}
              alt=""
              fill
              style={{ objectFit: "cover" }}
              unoptimized
            />
          ) : (
            <span
              style={{
                position: "absolute",
                inset: 0,
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
                fontSize: 13,
                fontWeight: 800,
                color: "var(--brand)",
              }}
            >
              {comment.user_name?.charAt(0)?.toUpperCase() ?? "?"}
            </span>
          )}
        </div>

        <div style={{ flex: 1, minWidth: 0 }}>
          {/* Name + time + actions */}
          <div
            style={{
              display: "flex",
              alignItems: "center",
              gap: "0.5rem",
              marginBottom: "0.25rem",
            }}
          >
            <span
              style={{
                fontWeight: 700,
                fontSize: "0.8125rem",
                color: "var(--ink)",
              }}
            >
              {comment.user_name}
            </span>
            <span
              style={{
                fontSize: "0.688rem",
                fontFamily: "var(--mono)",
                color: "var(--text-3, #9ca3af)",
              }}
            >
              {fmtRelTime(comment.created_at)}
            </span>
            {isOwn && !editing && (
              <div
                style={{ marginLeft: "auto", display: "flex", gap: "0.5rem" }}
              >
                <button
                  onClick={() => {
                    setEditing(true);
                    setEditText(comment.comment);
                  }}
                  style={{
                    background: "none",
                    border: "none",
                    fontSize: "0.7rem",
                    color: "var(--text-3, #9ca3af)",
                    cursor: "pointer",
                    fontWeight: 600,
                    padding: "1px 4px",
                    borderRadius: 4,
                    transition: "color 0.12s",
                  }}
                  onMouseEnter={(e) =>
                    (e.currentTarget.style.color = "var(--ink)")
                  }
                  onMouseLeave={(e) =>
                    (e.currentTarget.style.color = "var(--text-3, #9ca3af)")
                  }
                >
                  Edit
                </button>
                <button
                  onClick={handleDelete}
                  style={{
                    background: "none",
                    border: "none",
                    fontSize: "0.7rem",
                    color: "var(--text-3, #9ca3af)",
                    cursor: "pointer",
                    fontWeight: 600,
                    padding: "1px 4px",
                    borderRadius: 4,
                    transition: "color 0.12s",
                  }}
                  onMouseEnter={(e) =>
                    (e.currentTarget.style.color = "var(--brand)")
                  }
                  onMouseLeave={(e) =>
                    (e.currentTarget.style.color = "var(--text-3, #9ca3af)")
                  }
                >
                  Delete
                </button>
              </div>
            )}
          </div>

          {/* Text or edit */}
          {editing ? (
            <div
              style={{
                display: "flex",
                gap: "0.375rem",
                marginBottom: "0.375rem",
              }}
            >
              <input
                value={editText}
                onChange={(e) => setEditText(e.target.value)}
                onKeyDown={(e) => {
                  if (e.key === "Enter") handleEdit();
                  if (e.key === "Escape") setEditing(false);
                }}
                autoFocus
                style={{
                  flex: 1,
                  padding: "0.375rem 0.625rem",
                  border: "1.5px solid var(--brand)",
                  borderRadius: 7,
                  fontSize: "0.8125rem",
                  outline: "none",
                  color: "var(--ink)",
                  background: "var(--bg, #f8f9fb)",
                }}
              />
              <button
                onClick={handleEdit}
                disabled={submitting}
                style={{
                  padding: "0.375rem 0.75rem",
                  background: "var(--brand)",
                  color: "#fff",
                  border: "none",
                  borderRadius: 7,
                  fontWeight: 700,
                  fontSize: "0.75rem",
                  cursor: "pointer",
                }}
              >
                Save
              </button>
              <button
                onClick={() => setEditing(false)}
                style={{
                  padding: "0.375rem 0.625rem",
                  background: "none",
                  border: "1px solid var(--border)",
                  borderRadius: 7,
                  fontWeight: 500,
                  fontSize: "0.75rem",
                  cursor: "pointer",
                  color: "var(--ink)",
                }}
              >
                ✕
              </button>
            </div>
          ) : (
            <p
              style={{
                fontSize: "0.875rem",
                color: "var(--ink)",
                lineHeight: 1.55,
                margin: "0 0 0.375rem",
                wordBreak: "break-word",
              }}
            >
              {comment.comment}
            </p>
          )}

          {/* Reply / load-replies links */}
          {!editing && depth === 0 && (
            <div style={{ display: "flex", gap: "0.875rem" }}>
              {userId > 0 && (
                <button
                  onClick={() => setReplyOpen((v) => !v)}
                  style={{
                    background: "none",
                    border: "none",
                    fontSize: "0.75rem",
                    color: "var(--text-3, #9ca3af)",
                    cursor: "pointer",
                    fontWeight: 600,
                    padding: 0,
                  }}
                >
                  {replyOpen ? "Cancel" : "Reply"}
                </button>
              )}
              <button
                onClick={loadReplies}
                style={{
                  background: "none",
                  border: "none",
                  fontSize: "0.75rem",
                  color: "var(--brand)",
                  cursor: "pointer",
                  fontWeight: 600,
                  padding: 0,
                }}
              >
                {repliesVisible
                  ? "Hide replies"
                  : replies.length > 0
                    ? `${replies.length} replies`
                    : "View replies"}
              </button>
            </div>
          )}

          {/* Reply input */}
          {replyOpen && (
            <div
              style={{ display: "flex", gap: "0.5rem", marginTop: "0.5rem" }}
            >
              <input
                value={replyText}
                onChange={(e) => setReplyText(e.target.value)}
                onKeyDown={(e) => e.key === "Enter" && handleReply()}
                placeholder="Write a reply…"
                autoFocus
                style={{
                  flex: 1,
                  padding: "0.375rem 0.75rem",
                  border: "1.5px solid var(--border)",
                  borderRadius: 99,
                  fontSize: "0.8125rem",
                  outline: "none",
                  color: "var(--ink)",
                  background: "var(--bg, #f8f9fb)",
                  transition: "border-color 0.15s",
                }}
                onFocus={(e) => (e.target.style.borderColor = "var(--brand)")}
                onBlur={(e) => (e.target.style.borderColor = "var(--border)")}
              />
              <button
                onClick={handleReply}
                disabled={!replyText.trim() || submitting}
                style={{
                  flexShrink: 0,
                  padding: "0.375rem 0.875rem",
                  background: replyText.trim() ? "var(--brand)" : "#e5e7eb",
                  color: replyText.trim() ? "#fff" : "var(--text-3, #9ca3af)",
                  border: "none",
                  borderRadius: 99,
                  fontWeight: 700,
                  fontSize: "0.75rem",
                  cursor: replyText.trim() ? "pointer" : "default",
                  transition: "background 0.15s",
                }}
              >
                Reply
              </button>
            </div>
          )}

          {/* Nested replies */}
          {repliesVisible && replies.length > 0 && (
            <div style={{ marginTop: "0.5rem" }}>
              {replies.map((r, ri) => (
                <CommentRow
                  key={`reply-${r.id}-${ri}`}
                  comment={r}
                  userId={userId}
                  contentKey={contentKey}
                  type={type}
                  contentId={contentId}
                  videoId={videoId}
                  depth={1}
                />
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

// ── Modal ─────────────────────────────────────────────────────────────────────
interface CommentDrawerProps {
  open: boolean;
  onClose: () => void;
  type: number;
  contentId: number;
  videoId?: number;
  title?: string;
}

export default function CommentDrawer({
  open,
  onClose,
  type,
  contentId,
  videoId = 0,
  title,
}: CommentDrawerProps) {
  const dispatch = useAppDispatch();
  const { success, error: showError } = useToast();
  const [userId, setUserId] = useState(0);
  useEffect(() => {
    setUserId(getStoredUser()?.id ?? 0);
  }, []);
  const contentKey = makeKey(type, contentId, videoId);
  const comments = useAppSelector(selectComments(contentKey));
  const isLoaded = useAppSelector(selectCommentsLoaded(contentKey));
  const isLoading = useAppSelector(selectCommentsLoading);
  const submitting = useAppSelector(selectCommentsSubmitting);
  const [newComment, setNewComment] = useState("");
  const [visible, setVisible] = useState(false);
  const inputRef = useRef<HTMLInputElement>(null);

  // Animate in on open
  useEffect(() => {
    if (open) {
      // small delay so CSS transition fires
      requestAnimationFrame(() => setVisible(true));
      if (!isLoaded) dispatch(fetchComments({ type, contentId, videoId }));
      setTimeout(() => inputRef.current?.focus(), 300);
    } else {
      setVisible(false);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [open]);

  // Lock body scroll
  useEffect(() => {
    if (open) {
      document.body.style.overflow = "hidden";
    } else {
      document.body.style.overflow = "";
    }
    return () => {
      document.body.style.overflow = "";
    };
  }, [open]);

  async function handlePost() {
    if (!newComment.trim() || !userId) return;
    const user = getStoredUser();
    const res = await dispatch(
      addComment({
        userId,
        contentId,
        type,
        comment: newComment.trim(),
        videoId,
        contentKey,
        userName: user?.full_name ?? "You",
        userImage: user?.image ?? "",
      }),
    );
    if (addComment.fulfilled.match(res)) {
      setNewComment("");
      success("Comment posted");
    } else {
      showError("Failed to post comment");
    }
  }

  if (!open && !visible) return null;

  return (
    <>
      {/* Backdrop */}
      <div
        onClick={onClose}
        style={{
          position: "fixed",
          inset: 0,
          background: "rgba(14,14,17,0.6)",
          backdropFilter: "blur(4px)",
          zIndex: 900,
          opacity: visible ? 1 : 0,
          transition: "opacity 0.22s ease",
        }}
      />

      {/* Centered modal */}
      <div
        role="dialog"
        aria-modal="true"
        aria-label="Comments"
        style={{
          position: "fixed",
          top: "50%",
          left: "50%",
          transform: visible
            ? "translate(-50%, -50%) scale(1)"
            : "translate(-50%, -46%) scale(0.96)",
          opacity: visible ? 1 : 0,
          transition:
            "transform 0.28s cubic-bezier(0.22,1,0.36,1), opacity 0.22s ease",
          zIndex: 901,
          width: "min(580px, 94vw)",
          maxHeight: "82vh",
          background: "var(--surf, #ffffff)",
          borderRadius: 16,
          boxShadow: "0 32px 80px rgba(0,0,0,0.22), 0 0 0 1px rgba(0,0,0,0.06)",
          display: "flex",
          flexDirection: "column",
          overflow: "hidden",
        }}
      >
        {/* ── Header ── */}
        <div
          style={{
            padding: "1.125rem 1.375rem",
            display: "flex",
            alignItems: "center",
            justifyContent: "space-between",
            borderBottom: "1px solid var(--border)",
            flexShrink: 0,
          }}
        >
          <div>
            <h3
              style={{
                margin: 0,
                fontSize: "1rem",
                fontWeight: 800,
                color: "var(--ink)",
                letterSpacing: "-0.01em",
              }}
            >
              Comments
              {comments.length > 0 && (
                <span
                  style={{
                    marginLeft: "0.5rem",
                    fontFamily: "var(--mono)",
                    fontWeight: 500,
                    fontSize: "0.8125rem",
                    color: "var(--text-3, #9ca3af)",
                  }}
                >
                  {comments.length}
                </span>
              )}
            </h3>
            {title && (
              <p
                style={{
                  margin: "2px 0 0",
                  fontSize: "0.75rem",
                  color: "var(--text-2, #6b7280)",
                  maxWidth: 360,
                  overflow: "hidden",
                  textOverflow: "ellipsis",
                  whiteSpace: "nowrap",
                }}
              >
                {title}
              </p>
            )}
          </div>
          <button
            onClick={onClose}
            aria-label="Close comments"
            style={{
              width: 32,
              height: 32,
              borderRadius: "50%",
              background: "var(--bg, #f8f9fb)",
              border: "1px solid var(--border)",
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
              cursor: "pointer",
              color: "var(--text-2, #6b7280)",
              fontSize: 14,
              transition: "background 0.12s",
            }}
            onMouseEnter={(e) =>
              (e.currentTarget.style.background = "var(--brand-08, rgba(193,39,45,0.08))")
            }
            onMouseLeave={(e) =>
              (e.currentTarget.style.background = "var(--bg, #f8f9fb)")
            }
          >
            ✕
          </button>
        </div>

        {/* ── Comment list ── */}
        <div style={{ flex: 1, overflowY: "auto", padding: "0 1.375rem" }}>
          {isLoading && comments.length === 0 ? (
            // Skeleton
            <div style={{ padding: "0.75rem 0" }}>
              {Array.from({ length: 4 }).map((_, i) => (
                <div
                  key={`skel-${i}`}
                  style={{
                    display: "flex",
                    gap: "0.625rem",
                    padding: "0.75rem 0",
                    borderBottom: "1px solid var(--border)",
                  }}
                >
                  <div
                    style={{
                      flexShrink: 0,
                      width: 34,
                      height: 34,
                      borderRadius: "50%",
                      background: "#e5e7eb",
                    }}
                  />
                  <div style={{ flex: 1 }}>
                    <div
                      style={{
                        height: 11,
                        width: "28%",
                        background: "#e5e7eb",
                        borderRadius: 4,
                        marginBottom: 7,
                      }}
                    />
                    <div
                      style={{
                        height: 13,
                        background: "#e5e7eb",
                        borderRadius: 4,
                        marginBottom: 5,
                      }}
                    />
                    <div
                      style={{
                        height: 13,
                        width: "65%",
                        background: "#e5e7eb",
                        borderRadius: 4,
                      }}
                    />
                  </div>
                </div>
              ))}
            </div>
          ) : comments.length === 0 ? (
            <div
              style={{
                textAlign: "center",
                padding: "3rem 0",
                color: "var(--text-2, #6b7280)",
              }}
            >
              <div
                style={{
                  width: 48,
                  height: 48,
                  borderRadius: "50%",
                  background: "var(--bg, #f8f9fb)",
                  border: "1px solid var(--border)",
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "center",
                  margin: "0 auto 0.875rem",
                }}
              >
                <svg
                  width="22"
                  height="22"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="var(--text-3, #9ca3af)"
                  strokeWidth="1.5"
                >
                  <path d="M21 11.5a8.4 8.4 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.4 8.4 0 0 1-3.8-.9L3 21l1.9-5.7a8.4 8.4 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.4 8.4 0 0 1 3.8-.9h.5a8.5 8.5 0 0 1 8 8z" />
                </svg>
              </div>
              <p
                style={{
                  fontWeight: 700,
                  fontSize: "0.9375rem",
                  margin: "0 0 0.25rem",
                  color: "var(--ink)",
                }}
              >
                No comments yet
              </p>
              <p style={{ fontSize: "0.8125rem" }}>Start the conversation</p>
            </div>
          ) : (
            comments.map((c, idx) => (
              <CommentRow
                key={`comment-${c.id}-${idx}`}
                comment={c}
                userId={userId}
                contentKey={contentKey}
                type={type}
                contentId={contentId}
                videoId={videoId}
              />
            ))
          )}
        </div>

        {/* ── Input bar ── */}
        <div
          style={{
            padding: "0.875rem 1.375rem",
            borderTop: "1px solid var(--border)",
            display: "flex",
            gap: "0.625rem",
            alignItems: "center",
            flexShrink: 0,
            background: "var(--surf, #ffffff)",
          }}
        >
          {/* User avatar */}
          <div
            style={{
              flexShrink: 0,
              width: 30,
              height: 30,
              borderRadius: "50%",
              background: userId ? "var(--brand)" : "var(--bg, #f8f9fb)",
              border: userId ? "none" : "1px solid var(--border)",
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
            }}
          >
            <svg
              width="14"
              height="14"
              viewBox="0 0 24 24"
              fill="none"
              stroke={userId ? "#fff" : "var(--text-3, #9ca3af)"}
              strokeWidth="2"
            >
              <circle cx="12" cy="8" r="4" />
              <path d="M4 21a8 8 0 0 1 16 0" />
            </svg>
          </div>

          <input
            ref={inputRef}
            value={newComment}
            onChange={(e) => setNewComment(e.target.value)}
            onKeyDown={(e) => e.key === "Enter" && !e.shiftKey && handlePost()}
            placeholder={userId ? "Add a comment…" : "Sign in to comment"}
            disabled={!userId}
            style={{
              flex: 1,
              padding: "0.5625rem 0.875rem",
              border: "1.5px solid var(--border)",
              borderRadius: 99,
              fontSize: "0.875rem",
              outline: "none",
              color: "var(--ink)",
              background: "var(--bg, #f8f9fb)",
              transition: "border-color 0.15s",
              fontFamily: "inherit",
            }}
            onFocus={(e) => (e.target.style.borderColor = "var(--brand)")}
            onBlur={(e) => (e.target.style.borderColor = "var(--border)")}
          />

          <button
            onClick={handlePost}
            disabled={!newComment.trim() || !userId || submitting}
            aria-label="Post comment"
            style={{
              flexShrink: 0,
              width: 38,
              height: 38,
              borderRadius: "50%",
              background:
                newComment.trim() && userId ? "var(--brand)" : "#e5e7eb",
              border: "none",
              cursor: newComment.trim() && userId ? "pointer" : "default",
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
              transition: "background 0.15s, transform 0.12s",
            }}
            onMouseEnter={(e) => {
              if (newComment.trim() && userId)
                e.currentTarget.style.transform = "scale(1.08)";
            }}
            onMouseLeave={(e) => {
              e.currentTarget.style.transform = "scale(1)";
            }}
          >
            <svg
              width="15"
              height="15"
              viewBox="0 0 24 24"
              fill="none"
              stroke={
                newComment.trim() && userId ? "#fff" : "var(--text-3, #9ca3af)"
              }
              strokeWidth="2.2"
              strokeLinecap="round"
              strokeLinejoin="round"
            >
              <line x1="22" y1="2" x2="11" y2="13" />
              <polygon points="22 2 15 22 11 13 2 9 22 2" />
            </svg>
          </button>
        </div>
      </div>
    </>
  );
}
