﻿"use client";
import { useState, useEffect } from "react";
import { useSession } from "next-auth/react";
import { Send, User as UserIcon, BadgeCheck } from "lucide-react";
import { toast } from "@/components/ui/Toaster";
import Link from "next/link";
import { formatDate } from "@/lib/utils";

export function CommentSection({ mediaId }: { mediaId: string }) {
  const { data: session } = useSession();
  const [comments, setComments] = useState<any[]>([]);
  const [content, setContent] = useState("");
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    fetch(`/api/media/${mediaId}/comments`)
      .then(r => r.json())
      .then(setComments)
      .catch(() => {});
  }, [mediaId]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!session) return toast("Connectez-vous pour commenter.", "error");
    if (!content.trim()) return;

    setLoading(true);
    const res = await fetch(`/api/media/${mediaId}/comments`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ content })
    });

    if (res.ok) {
      const newComment = await res.json();
      setComments([newComment, ...comments]);
      setContent("");
    } else {
      toast("Erreur lors de l'ajout du commentaire.", "error");
    }
    setLoading(false);
  };

  return (
    <div className="mt-8">
      <h3 className="font-bold text-xl mb-6">Commentaires ({comments.length})</h3>

      <form onSubmit={handleSubmit} className="flex gap-4 mb-8">
        <div className="w-10 h-10 rounded-full overflow-hidden shrink-0 border border-[#333333] bg-[#1a1a1a]">
          {session?.user?.image ? (
            <img src={session.user.image} alt="avatar" className="w-full h-full object-cover" />
          ) : (
            <div className="w-full h-full flex items-center justify-center text-white"><UserIcon size={20} /></div>
          )}
        </div>
        <div className="flex-1 relative">
          <input
            type="text"
            placeholder={session ? "Ajouter un commentaire..." : "Connectez-vous pour commenter..."}
            value={content}
            onChange={e => setContent(e.target.value)}
            disabled={!session || loading}
            className="w-full bg-[#0f0f0f] border border-[#333333] rounded-lg px-4 py-2 text-sm text-white focus:outline-none focus:border-[#e05a68] focus:ring-1 focus:ring-[#e05a68] transition-colors"
          />
          <button
            type="submit"
            disabled={!session || loading || !content.trim()}
            className="absolute right-2 top-1.5 p-1 rounded hover:bg-[#333333] disabled:opacity-50 text-[#e05a68] transition-colors"
          >
            <Send size={16} />
          </button>
        </div>
      </form>

      <div className="space-y-6">
        {comments.map((comment) => (
          <div key={comment.id} className="flex gap-4">
            <Link href={`/channel/${comment.user.id}`} className="w-10 h-10 rounded-full overflow-hidden shrink-0 border border-[#333333] bg-[#1a1a1a]">
              {comment.user.image ? (
                <img src={comment.user.image} alt="avatar" className="w-full h-full object-cover" />
              ) : (
                <div className="w-full h-full flex items-center justify-center font-bold text-white">
                  {comment.user.name?.[0]?.toUpperCase() || "U"}
                </div>
              )}
            </Link>
            <div className="flex-1">
              <div className="flex items-center gap-2 mb-1">
                <Link href={`/channel/${comment.user.id}`} className="font-bold text-sm hover:text-[#e05a68] transition-colors flex items-center gap-1">
                  {comment.user.name || "Utilisateur"}
                  {comment.user.isVerified && <BadgeCheck size={12} className="text-[#e05a68]" fill="currentColor" />}
                </Link>
                <span className="text-xs text-[#737373]">{formatDate(comment.createdAt)}</span>
              </div>
              <p className="text-sm text-[#e5e5e5] break-words">{comment.content}</p>
            </div>
          </div>
        ))}
        {comments.length === 0 && (
          <p className="text-center text-[#aaaaaa] text-sm py-4">Aucun commentaire pour l'instant. Soyez le premier !</p>
        )}
      </div>
    </div>
  );
}

