"use client";
import React, { useState, useEffect, useCallback } from "react";
import Link from "next/link";
import { createClient } from "@/lib/supabase/client";

interface Comment {
  id: string;
  content: string;
  created_at: string;
  user_id: string;
  user_profiles: {
    full_name: string;
    avatar_url: string | null;
    email: string;
  } | null;
}

interface CommentsSectionProps {
  articleSlug: string;
}

function getInitials(name: string): string {
  return name
    .split(" ")
    .map((n) => n[0])
    .join("")
    .toUpperCase()
    .slice(0, 2);
}

function timeAgo(dateStr: string): string {
  const diff = Date.now() - new Date(dateStr).getTime();
  const mins = Math.floor(diff / 60000);
  if (mins < 1) return "just now";
  if (mins < 60) return `${mins}m ago`;
  const hrs = Math.floor(mins / 60);
  if (hrs < 24) return `${hrs}h ago`;
  const days = Math.floor(hrs / 24);
  if (days < 30) return `${days}d ago`;
  return new Date(dateStr).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" });
}

export default function CommentsSection({ articleSlug }: CommentsSectionProps) {
  const supabase = createClient();
  const [comments, setComments] = useState<Comment[]>([]);
  const [loading, setLoading] = useState(true);
  const [user, setUser] = useState<any>(null);
  const [newComment, setNewComment] = useState("");
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [deletingId, setDeletingId] = useState<string | null>(null);

  const fetchComments = useCallback(async () => {
    try {
      const { data, error: fetchError } = await supabase
        .from("article_comments")
        .select(`
          id,
          content,
          created_at,
          user_id,
          user_profiles (
            full_name,
            avatar_url,
            email
          )
        `)
        .eq("article_slug", articleSlug)
        .order("created_at", { ascending: false });

      if (fetchError) throw fetchError;
      setComments((data as unknown as Comment[]) || []);
    } catch {
      // Silent fail
    } finally {
      setLoading(false);
    }
  }, [articleSlug]);

  useEffect(() => {
    fetchComments();
    supabase.auth.getUser().then(({ data }) => {
      setUser(data?.user ?? null);
    });
  }, [fetchComments]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!user || !newComment.trim()) return;
    setSubmitting(true);
    setError(null);
    try {
      const { error: insertError } = await supabase.from("article_comments").insert({
        article_slug: articleSlug,
        user_id: user.id,
        content: newComment.trim(),
      });
      if (insertError) throw insertError;
      setNewComment("");
      await fetchComments();
    } catch (err: any) {
      setError(err?.message || "Failed to post comment. Please try again.");
    } finally {
      setSubmitting(false);
    }
  };

  const handleDelete = async (commentId: string) => {
    setDeletingId(commentId);
    try {
      await supabase.from("article_comments").delete().eq("id", commentId);
      setComments((prev) => prev.filter((c) => c.id !== commentId));
    } catch {
      // Silent fail
    } finally {
      setDeletingId(null);
    }
  };

  return (
    <section className="mt-10 pt-8 border-t border-[#DCE6F2]">
      {/* Section Header */}
      <div className="flex items-center gap-3 mb-6">
        <span className="section-label">Comments</span>
        {!loading && (
          <span className="font-body text-xs text-[#555]">
            {comments.length} {comments.length === 1 ? "comment" : "comments"}
          </span>
        )}
        <div className="flex-1 h-px bg-[#DCE6F2]" />
      </div>

      {/* Comment Form */}
      {user ? (
        <form onSubmit={handleSubmit} className="mb-8">
          <div className="flex gap-3">
            <div className="w-8 h-8 rounded-full bg-[#DCE6F2] border border-[#2a3a50] flex items-center justify-center flex-shrink-0 mt-0.5">
              <span className="font-body text-[10px] font-bold text-[#1D4ED8]">
                {getInitials(user.user_metadata?.full_name || user.email || "U")}
              </span>
            </div>
            <div className="flex-1">
              <textarea
                value={newComment}
                onChange={(e) => setNewComment(e.target.value)}
                placeholder="Share your thoughts on this article..."
                rows={3}
                maxLength={1000}
                className="w-full bg-[#FFFFFF] border border-[#DCE6F2] text-[#e0e0e0] font-body text-sm px-3 py-2.5 rounded-sm focus:outline-none focus:border-[#1D4ED8] focus:ring-1 focus:ring-[#1D4ED8] transition-colors placeholder-[#444] resize-none"
              />
              {error && (
                <p className="font-body text-xs text-[#1D4ED8] mt-1.5">{error}</p>
              )}
              <div className="flex items-center justify-between mt-2">
                <span className="font-body text-[11px] text-[#555]">
                  {newComment.length}/1000
                </span>
                <button
                  type="submit"
                  disabled={submitting || !newComment.trim()}
                  className="bg-[#1D4ED8] hover:bg-[#1E3A8A] text-white font-body text-xs font-bold uppercase tracking-wide px-5 py-2 rounded-sm transition-colors disabled:opacity-50 focus:outline-none focus-visible:ring-2 focus-visible:ring-[#1D4ED8]">
                  {submitting ? "Posting..." : "Post Comment"}
                </button>
              </div>
            </div>
          </div>
        </form>
      ) : (
        <div className="mb-8 bg-[#0d1520] border border-[#DCE6F2] rounded-sm p-5 flex items-center justify-between gap-4">
          <div>
            <p className="font-body text-sm font-bold text-[#e0e0e0] mb-0.5">Join the conversation</p>
            <p className="font-body text-xs text-[#666]">Sign in to post a comment on this article.</p>
          </div>
          <Link
            href="/login"
            className="flex-shrink-0 bg-[#1D4ED8] hover:bg-[#1E3A8A] text-white font-body text-xs font-bold uppercase tracking-wide px-5 py-2 rounded-sm transition-colors">
            Sign In
          </Link>
        </div>
      )}

      {/* Comments List */}
      {loading ? (
        <div className="space-y-4">
          {[...Array(3)].map((_, i) => (
            <div key={i} className="flex gap-3">
              <div className="skeleton w-8 h-8 rounded-full flex-shrink-0" />
              <div className="flex-1 space-y-2">
                <div className="skeleton h-3 w-32 rounded-sm" />
                <div className="skeleton h-4 w-full rounded-sm" />
                <div className="skeleton h-4 w-3/4 rounded-sm" />
              </div>
            </div>
          ))}
        </div>
      ) : comments.length === 0 ? (
        <div className="empty-state py-10">
          <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" className="empty-state-icon" aria-hidden="true">
            <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" />
          </svg>
          <p className="empty-state-title">No comments yet</p>
          <p className="empty-state-desc">Be the first to share your thoughts on this article.</p>
        </div>
      ) : (
        <div className="space-y-5">
          {comments.map((comment) => {
            const name = comment.user_profiles?.full_name || comment.user_profiles?.email?.split("@")[0] || "Anonymous";
            const isOwn = user?.id === comment.user_id;
            return (
              <div key={comment.id} className="flex gap-3 group">
                <div className="w-8 h-8 rounded-full bg-[#FFFFFF] border border-[#2a3a50] flex items-center justify-center flex-shrink-0 mt-0.5 overflow-hidden">
                  {comment.user_profiles?.avatar_url ? (
                    <img
                      src={comment.user_profiles.avatar_url}
                      alt={`${name} avatar`}
                      className="w-full h-full object-cover"
                    />
                  ) : (
                    <span className="font-body text-[10px] font-bold text-[#1D4ED8]">
                      {getInitials(name)}
                    </span>
                  )}
                </div>
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-2 mb-1">
                    <span className="font-body text-xs font-bold text-[#e0e0e0]">{name}</span>
                    <span className="font-body text-[11px] text-[#555]">{timeAgo(comment.created_at)}</span>
                    {isOwn && (
                      <button
                        onClick={() => handleDelete(comment.id)}
                        disabled={deletingId === comment.id}
                        aria-label="Delete comment"
                        className="ml-auto opacity-0 group-hover:opacity-100 font-body text-[11px] text-[#555] hover:text-[#1D4ED8] transition-all disabled:opacity-30">
                        {deletingId === comment.id ? "Deleting..." : "Delete"}
                      </button>
                    )}
                  </div>
                  <p className="font-body text-sm text-[#cccccc] leading-relaxed whitespace-pre-wrap break-words">
                    {comment.content}
                  </p>
                </div>
              </div>
            );
          })}
        </div>
      )}
    </section>
  );
}
