"use client";

import React, { useState } from "react";
import Image from "next/image";
import { ChevronDown, MessageSquare } from "lucide-react";

export interface CommentData {
  id: number;
  author: string;
  avatar: string;
  date: string;
  content: string;
  likes: number;
  replies?: CommentData[];
}

export interface CommentsProps {
  comments: CommentData[];
  totalCount: number;
  hasMore: boolean;
  isFetching: boolean;
  isSubmitting: boolean;
  canPost?: boolean;
  userAvatar?: string;
  userName: string;
  onPost: (text: string) => Promise<void>;
  onReply: (text: string, parentId: number) => Promise<void>;
  onLoadMore: () => Promise<void>;
  onSubscribeClick?: () => void;
  defaultOpen?: boolean;
}

// ── Shared helpers ───────────────────────────────────────────────

const AVATAR_COLORS = [
  "bg-[#3b82f6]", "bg-[#10b981]", "bg-[#f59e0b]", "bg-[#ef4444]",
  "bg-[#8b5cf6]", "bg-[#0ea5e9]", "bg-[#ec4899]", "bg-[#6366f1]",
];

const getAvatarColor = (name: string) =>
  AVATAR_COLORS[name.charCodeAt(0) % AVATAR_COLORS.length];

const getInitials = (name: string) => {
  const parts = name.trim().split(/\s+/);
  return (
    (parts[0]?.[0] ?? "") +
    (parts.length > 1 ? (parts[parts.length - 1]?.[0] ?? "") : "")
  ).toUpperCase() || "U";
};

// ── Avatar ───────────────────────────────────────────────────────

const Avatar: React.FC<{ src?: string; name: string; size: "sm" | "md" }> = ({
  src,
  name,
  size,
}) => {
  const sizeClass = size === "sm" ? "w-6 h-6 text-[9px]" : "w-7 h-7 text-[10px]";
  if (src) {
    return (
      <div className={`relative rounded-full overflow-hidden shrink-0 border border-[#e5e7eb] ${sizeClass}`}>
        <Image src={src} alt={name} fill className="object-cover" />
      </div>
    );
  }
  return (
    <div className={`rounded-full shrink-0 flex items-center justify-center text-white font-bold ${sizeClass} ${getAvatarColor(name)}`}>
      {getInitials(name)}
    </div>
  );
};

// ── Reply form ───────────────────────────────────────────────────

const ReplyForm: React.FC<{
  userAvatar?: string;
  userName: string;
  isLoading: boolean;
  onSubmit: (text: string) => Promise<void>;
  onCancel: () => void;
}> = ({ userAvatar, userName, isLoading, onSubmit, onCancel }) => {
  const [text, setText] = useState("");

  return (
    <div className="flex gap-2 items-start ml-9">
      <Avatar src={userAvatar} name={userName} size="sm" />
      <div className="flex-1">
        <textarea
          value={text}
          onChange={(e) => setText(e.target.value)}
          placeholder="Write a reply…"
          rows={2}
          className="w-full resize-none outline-none text-[12px] border border-[#e5e7eb] rounded-lg px-2.5 py-1.5 bg-white font-['Arial',sans-serif]"
        />
        <div className="flex gap-1.5 mt-1.5">
          <button
            onClick={onCancel}
            className="px-2.5 py-1 text-[10px] font-medium rounded-md border border-[#e5e7eb] text-[#4b5563] bg-white cursor-pointer hover:bg-[#f9fafb] transition-colors font-['Arial',sans-serif]"
          >
            Cancel
          </button>
          <button
            onClick={() => text.trim() && onSubmit(text)}
            disabled={isLoading || !text.trim()}
            className="px-2.5 py-1 text-[10px] font-semibold rounded-md bg-[#2563eb] text-white cursor-pointer hover:opacity-90 transition-opacity disabled:opacity-50 disabled:cursor-not-allowed font-['Arial',sans-serif]"
          >
            {isLoading ? "Posting..." : "Reply"}
          </button>
        </div>
      </div>
    </div>
  );
};

// ── Comment item ─────────────────────────────────────────────────

const CommentItem: React.FC<{
  comment: CommentData;
  isReply?: boolean;
  canPost: boolean;
  userAvatar?: string;
  userName: string;
  onReply: (text: string, parentId: number) => Promise<void>;
  onSubscribeClick?: () => void;
  isAuthenticated: boolean;
}> = ({
  comment,
  isReply = false,
  canPost,
  userAvatar,
  userName,
  onReply,
  onSubscribeClick,
  isAuthenticated,
}) => {
  const [isReplying, setIsReplying] = useState(false);
  const [isSubmittingReply, setIsSubmittingReply] = useState(false);

  const replyLabel = !isAuthenticated
    ? "Login to Reply"
    : !canPost
      ? "Subscribe to Reply"
      : "Reply";

  const handleReplySubmit = async (text: string) => {
    setIsSubmittingReply(true);
    try {
      await onReply(text, comment.id);
      setIsReplying(false);
    } finally {
      setIsSubmittingReply(false);
    }
  };

  return (
    <div className="flex flex-col gap-2">
      <div className="flex gap-2.5">
        <Avatar src={comment.avatar} name={comment.author} size={isReply ? "sm" : "md"} />
        <div className="flex-1 min-w-0">
          <div className="flex items-baseline gap-2 flex-wrap">
            <span className="text-[12px] font-semibold text-[#111827]">
              {comment.author}
            </span>
            <span className="text-[10px] text-[#9ca3af]">{comment.date}</span>
          </div>
          <p className="text-[12px] text-[#374151] leading-relaxed mt-0.5">
            {comment.content}
          </p>
          <button
            onClick={() => {
              if (!isAuthenticated) return;
              if (!canPost) { onSubscribeClick?.(); return; }
              setIsReplying((v) => !v);
            }}
            className="mt-1 text-[10px] font-semibold text-[#3b82f6] bg-transparent border-none p-0 cursor-pointer hover:opacity-80 transition-opacity font-['Arial',sans-serif]"
          >
            {replyLabel}
          </button>
        </div>
      </div>

      {/* Nested replies */}
      {!isReply && comment.replies && comment.replies.length > 0 && (
        <div className="ml-9 flex flex-col gap-2.5 border-l border-[#e5e7eb] pl-3">
          {comment.replies.map((reply) => (
            <CommentItem
              key={reply.id}
              comment={reply}
              isReply
              canPost={canPost}
              userAvatar={userAvatar}
              userName={userName}
              onReply={onReply}
              onSubscribeClick={onSubscribeClick}
              isAuthenticated={isAuthenticated}
            />
          ))}
        </div>
      )}

      {/* Reply form */}
      {isReplying && canPost && (
        <ReplyForm
          userAvatar={userAvatar}
          userName={userName}
          isLoading={isSubmittingReply}
          onSubmit={handleReplySubmit}
          onCancel={() => setIsReplying(false)}
        />
      )}
    </div>
  );
};

// ── Comments (reusable) ──────────────────────────────────────────

export const Comments: React.FC<CommentsProps & { isAuthenticated: boolean }> = ({
  comments,
  totalCount,
  hasMore,
  isFetching,
  isSubmitting,
  canPost = true,
  userAvatar,
  userName,
  onPost,
  onReply,
  onLoadMore,
  onSubscribeClick,
  defaultOpen,
  isAuthenticated,
}) => {
  const [isOpen, setIsOpen] = useState(defaultOpen ?? totalCount === 0);
  const [text, setText] = useState("");

  const handleSubmit = async () => {
    const trimmed = text.trim();
    if (!trimmed || isSubmitting) return;
    await onPost(trimmed);
    setText("");
  };

  return (
    <section id="comments" className="scroll-mt-24 mt-4">
      {/* Toggle row */}
      <button
        type="button"
        onClick={() => setIsOpen((v) => !v)}
        className="flex items-center gap-1.5 text-[12px] text-[#6b7280] font-medium bg-transparent border-none p-0 cursor-pointer font-['Arial',sans-serif]"
      >
        <MessageSquare size={14} />
        <span>{totalCount} Comment{totalCount !== 1 ? "s" : ""}</span>
        <ChevronDown
          size={12}
          className={`transition-transform duration-200 ${isOpen ? "rotate-180" : "rotate-0"}`}
        />
      </button>

      {/* Collapsible content */}
      {isOpen && (
        <div className="mt-3 border-l-2 border-[#e5e7eb] pl-4 flex flex-col gap-4">
          {/* Comments list */}
          {comments.map((comment) => (
            <CommentItem
              key={comment.id}
              comment={comment}
              canPost={canPost}
              userAvatar={userAvatar}
              userName={userName}
              onReply={onReply}
              onSubscribeClick={onSubscribeClick}
              isAuthenticated={isAuthenticated}
            />
          ))}

          {/* Load more */}
          {hasMore && (
            <button
              onClick={onLoadMore}
              disabled={isFetching}
              className="self-start text-[11px] font-semibold text-[#3b82f6] bg-transparent border-none p-0 cursor-pointer hover:opacity-80 transition-opacity disabled:opacity-50 disabled:cursor-not-allowed font-['Arial',sans-serif]"
            >
              {isFetching ? "Loading..." : "See more comments"}
            </button>
          )}

          {/* Always-visible compose */}
          <div className="flex gap-2 items-start pt-1">
            <Avatar src={userAvatar} name={userName} size="md" />
            <div className="flex-1">
              <textarea
                value={text}
                onChange={(e) => setText(e.target.value)}
                placeholder={
                  !isAuthenticated
                    ? "Log in to comment…"
                    : !canPost
                      ? "Subscribe to comment…"
                      : "Write a comment…"
                }
                rows={2}
                disabled={!isAuthenticated || !canPost}
                onClick={() => {
                  if (!isAuthenticated) return;
                  if (!canPost) onSubscribeClick?.();
                }}
                className="w-full resize-none outline-none text-[12px] border border-[#e5e7eb] rounded-xl px-3 py-2 bg-white disabled:cursor-not-allowed font-['Arial',sans-serif]"
              />
              {text.trim() && (
                <div className="flex justify-end mt-1.5">
                  <button
                    onClick={handleSubmit}
                    disabled={isSubmitting}
                    className="px-3 py-1 text-[10px] font-semibold rounded-md bg-[#2563eb] text-white border-none cursor-pointer hover:opacity-90 transition-opacity disabled:opacity-50 disabled:cursor-not-allowed font-['Arial',sans-serif]"
                  >
                    {isSubmitting ? "Posting..." : "Post Comment"}
                  </button>
                </div>
              )}
            </div>
          </div>
        </div>
      )}
    </section>
  );
};
