"use client";
import { useState, useEffect } from "react";
import { formatDistanceToNow } from "date-fns";
import { MessageCircle, Send, ChevronDown } from "lucide-react";

const API = (process.env.NEXT_PUBLIC_API_URL ?? "http://127.0.0.1:8000") + "/api/v1";

interface Comment {
  id:          number;
  author_name: string;
  content:     string;
  created_at:  string;
  replies:     Comment[];
}

export default function CommentSection({ slug, postId }: { slug: string; postId: number }) {
  const [comments, setComments]   = useState<Comment[]>([]);
  const [total, setTotal]         = useState(0);
  const [loading, setLoading]     = useState(true);
  const [name, setName]           = useState("");
  const [text, setText]           = useState("");
  const [submitting, setSubmitting] = useState(false);
  const [message, setMessage]     = useState<{ text: string; ok: boolean } | null>(null);
  const [showForm, setShowForm]   = useState(false);

  useEffect(() => {
    fetch(`${API}/posts/${slug}/comments`)
      .then(r => r.json())
      .then(d => { setComments(d.data ?? []); setTotal(d.total ?? 0); })
      .catch(() => {})
      .finally(() => setLoading(false));

    // Track view
    fetch(`${API}/analytics/view`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ post_id: postId, referrer: document.referrer }),
    }).catch(() => {});
  }, [slug, postId]);

  async function submit(e: React.FormEvent) {
    e.preventDefault();
    if (!name.trim() || !text.trim()) return;
    setSubmitting(true);
    setMessage(null);

    try {
      const res = await fetch(`${API}/posts/${slug}/comments`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ name: name.trim(), comment: text.trim() }),
      });
      const data = await res.json();

      if (res.ok) {
        setMessage({ text: data.message, ok: true });
        setName(""); setText("");
        if (data.comment) {
          setComments(prev => [data.comment, ...prev]);
          setTotal(t => t + 1);
        }
      } else {
        setMessage({ text: data.message ?? "Something went wrong.", ok: false });
      }
    } catch {
      setMessage({ text: "Network error. Please try again.", ok: false });
    } finally {
      setSubmitting(false);
    }
  }

  return (
    <section className="mt-12 pt-8 border-t border-white/10">

      {/* Header */}
      <div className="flex items-center justify-between mb-6">
        <h2 className="text-xl font-bold text-white flex items-center gap-2">
          <MessageCircle className="w-5 h-5 text-brand-500" />
          Comments {total > 0 && <span className="text-gray-500 font-normal text-base">({total})</span>}
        </h2>
        <button onClick={() => setShowForm(f => !f)}
          className="flex items-center gap-1.5 text-sm text-brand-500 hover:text-blue-400 transition-colors border border-brand-500/40 hover:border-blue-400/60 px-3 py-1.5 rounded-xl">
          {showForm ? "Cancel" : "Write a comment"}
          <ChevronDown className={`w-4 h-4 transition-transform ${showForm ? "rotate-180" : ""}`} />
        </button>
      </div>

      {/* Comment form */}
      {showForm && (
        <form onSubmit={submit} className="bg-white/5 border border-white/10 rounded-2xl p-5 mb-8 space-y-4">
          <input
            type="text"
            placeholder="Your name"
            value={name}
            onChange={e => setName(e.target.value)}
            maxLength={100}
            required
            className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-2.5 text-white text-sm placeholder-gray-500 focus:outline-none focus:border-brand-500 transition-colors"
          />
          <textarea
            placeholder="Share your thoughts… (min 8 characters)"
            value={text}
            onChange={e => setText(e.target.value)}
            rows={4}
            minLength={8}
            maxLength={2000}
            required
            className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-2.5 text-white text-sm placeholder-gray-500 focus:outline-none focus:border-brand-500 transition-colors resize-none"
          />
          {message && (
            <div className={`text-sm px-4 py-3 rounded-xl ${
              message.ok
                ? "bg-green-500/10 border border-green-500/30 text-green-400"
                : "bg-red-500/10 border border-red-500/30 text-red-400"
            }`}>
              {message.text}
            </div>
          )}
          <div className="flex items-center justify-between">
            <p className="text-xs text-gray-600">Comments are reviewed before publishing.</p>
            <button type="submit" disabled={submitting}
              className="flex items-center gap-2 bg-brand-500 hover:bg-blue-600 disabled:opacity-50 text-white text-sm font-semibold px-5 py-2.5 rounded-xl transition-colors">
              <Send className="w-4 h-4" />
              {submitting ? "Posting…" : "Post Comment"}
            </button>
          </div>
        </form>
      )}

      {/* Comments list */}
      {loading ? (
        <div className="space-y-4">
          {[1,2,3].map(i => (
            <div key={i} className="animate-pulse flex gap-3">
              <div className="w-9 h-9 rounded-full bg-white/10 shrink-0" />
              <div className="flex-1 space-y-2">
                <div className="h-3 bg-white/10 rounded w-24" />
                <div className="h-3 bg-white/5 rounded w-full" />
                <div className="h-3 bg-white/5 rounded w-3/4" />
              </div>
            </div>
          ))}
        </div>
      ) : comments.length === 0 ? (
        <div className="text-center py-12 text-gray-500">
          <MessageCircle className="w-10 h-10 mx-auto mb-3 opacity-30" />
          <p>No comments yet. Be the first to share your thoughts!</p>
          {!showForm && (
            <button onClick={() => setShowForm(true)}
              className="mt-4 text-sm text-brand-500 hover:underline">
              Write a comment →
            </button>
          )}
        </div>
      ) : (
        <div className="space-y-6">
          {comments.map(comment => (
            <CommentItem key={comment.id} comment={comment} />
          ))}
        </div>
      )}
    </section>
  );
}

function CommentItem({ comment, isReply = false }: { comment: Comment; isReply?: boolean }) {
  const initials = comment.author_name.slice(0, 2).toUpperCase();
  const colors   = ["bg-blue-600", "bg-purple-600", "bg-green-600", "bg-orange-600", "bg-red-600", "bg-pink-600"];
  const color    = colors[comment.author_name.charCodeAt(0) % colors.length];

  return (
    <div className={`flex gap-3 ${isReply ? "ml-10 mt-4" : ""}`}>
      <div className={`w-9 h-9 rounded-full ${color} flex items-center justify-center text-xs font-bold text-white shrink-0`}>
        {initials}
      </div>
      <div className="flex-1">
        <div className="bg-white/5 border border-white/8 rounded-2xl px-4 py-3">
          <div className="flex items-center gap-2 mb-2">
            <span className="text-sm font-semibold text-white">{comment.author_name}</span>
            <span className="text-xs text-gray-500">
              {formatDistanceToNow(new Date(comment.created_at), { addSuffix: true })}
            </span>
          </div>
          <p className="text-gray-300 text-sm leading-relaxed">{comment.content}</p>
        </div>
        {comment.replies?.length > 0 && (
          <div className="mt-2 space-y-2">
            {comment.replies.map(reply => (
              <CommentItem key={reply.id} comment={reply} isReply />
            ))}
          </div>
        )}
      </div>
    </div>
  );
}
