"use client";
import { useEffect, useState, useCallback } from "react";
import { createClient } from "@/utils/supabase/client";
import { useParams, useRouter } from "next/navigation";
import { 
  ChevronLeft, Send, Trash2, MessageSquare, 
  Clock, Image as ImageIcon, ExternalLink 
} from "lucide-react";

export default function PostDetailPage() {
  const { postId } = useParams();
  const router = useRouter();
  const supabase = createClient();
  
  const [post, setPost] = useState<any>(null);
  const [comments, setComments] = useState<any[]>([]);
  const [newComment, setNewComment] = useState("");
  const [sending, setSending] = useState(false);
  const [loading, setLoading] = useState(true);

  const fetchPostDetails = useCallback(async () => {
    setLoading(true);
    
    // 1. Fetch Post with Author Profile (Table: community_posts)
    const { data: postData } = await supabase
      .from('community_posts')
      .select('*, profiles:user_id(*)')
      .eq('id', postId)
      .single();
    
    setPost(postData);

    // 2. Fetch Comments with Author Profile (Table: community_comments)
    const { data: commentsData } = await supabase
      .from('community_comments')
      .select('*, profiles:user_id(*)')
      .eq('post_id', postId)
      .order('created_at', { ascending: true });
    
    setComments(commentsData || []);
    setLoading(false);
  }, [postId, supabase]);

  useEffect(() => {
    fetchPostDetails();
  }, [fetchPostDetails]);

  const handleSendComment = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!newComment.trim()) return;
    
    setSending(true);
    const { data: { user } } = await supabase.auth.getUser();

    if (!user) return alert("You must be logged in");

    const { error } = await supabase.from('community_comments').insert({
      post_id: postId,
      user_id: user.id, // References public.profiles.id in your schema
      content: newComment.trim()
    });

    if (!error) {
      setNewComment("");
      fetchPostDetails();
    } else {
      alert(error.message);
    }
    setSending(false);
  };

  const handleDeleteComment = async (commentId: string) => {
    if (!confirm("Are you sure you want to delete this comment?")) return;
    
    const { error } = await supabase
      .from('community_comments')
      .delete()
      .eq('id', commentId);
      
    if (!error) {
      setComments(prev => prev.filter(c => c.id !== commentId));
    }
  };

  if (loading) return (
    <div className="flex flex-col items-center justify-center min-h-[400px] space-y-4">
      <div className="w-12 h-12 border-4 border-[#D4FB51] border-t-transparent rounded-full animate-spin"></div>
      <p className="text-[10px] font-black uppercase tracking-[0.3em] text-slate-400">Loading Discussion</p>
    </div>
  );

  if (!post) return <div className="p-20 text-center font-bold">Post not found.</div>;

  return (
    <div className="max-w-4xl mx-auto space-y-8 pb-20 animate-in fade-in slide-in-from-bottom-2 duration-500">
      <button 
        onClick={() => router.back()} 
        className="flex items-center gap-2 text-[10px] font-black uppercase tracking-widest text-slate-400 hover:text-black transition-colors"
      >
        <ChevronLeft size={14} /> Back to Community Feed
      </button>

      {/* --- THE POST --- */}
      <div className="bg-white rounded-[40px] shadow-sm border border-slate-100 overflow-hidden">
        {/* Post Media (If exists in your schema) */}
        {post.media_url && (
          <div className="w-full bg-slate-100 border-b border-slate-50 overflow-hidden max-h-[400px] flex items-center justify-center">
            {post.media_type === 'video' ? (
              <video src={post.media_url} controls className="w-full" />
            ) : (
              <img src={post.media_url} alt="Post media" className="w-full h-full object-cover" />
            )}
          </div>
        )}

        <div className="p-10">
          <div className="flex items-center gap-4 mb-8">
              <div className="w-12 h-12 rounded-2xl bg-[#1C1C1C] flex items-center justify-center font-black text-sm text-[#D4FB51]">
                  {post.profiles?.full_name?.substring(0,1) || "P"}
              </div>
              <div>
                  <p className="text-lg font-black text-[#1C1C1C]">{post.profiles?.full_name || "Community Member"}</p>
                  <p className="text-[10px] text-slate-400 font-bold uppercase tracking-widest flex items-center gap-2">
                    <Clock size={12} /> {new Date(post.created_at).toLocaleString()}
                  </p>
              </div>
          </div>
          <p className="text-xl font-bold text-slate-700 leading-relaxed italic">
            "{post.content}"
          </p>
        </div>
      </div>

      {/* --- COMMENTS SECTION --- */}
      <div className="space-y-6">
        <div className="flex items-center justify-between px-6">
          <h3 className="text-[11px] font-black text-slate-400 uppercase tracking-[0.2em] flex items-center gap-2">
              <MessageSquare size={14} className="text-[#D4FB51]" /> {comments.length} Responses
          </h3>
        </div>

        <div className="space-y-4">
          {comments.length === 0 ? (
            <div className="ml-10 p-10 border-2 border-dashed border-slate-100 rounded-[32px] text-center">
              <p className="text-[10px] font-black uppercase text-slate-300 tracking-widest">No comments yet. Be the first to moderate.</p>
            </div>
          ) : comments.map((comment) => (
            <div key={comment.id} className="bg-white p-6 rounded-[24px] border border-slate-50 shadow-sm ml-10 flex justify-between items-start group hover:border-[#D4FB51]/30 transition-all">
              <div className="flex gap-4">
                <div className="w-8 h-8 rounded-lg bg-slate-100 flex items-center justify-center font-black text-[10px] text-slate-400">
                  {comment.profiles?.full_name?.substring(0,1) || "U"}
                </div>
                <div>
                  <p className="text-xs font-black text-[#1C1C1C] mb-1">{comment.profiles?.full_name || "User"}</p>
                  <p className="text-sm font-medium text-slate-500 leading-snug">{comment.content}</p>
                  <p className="text-[8px] font-bold text-slate-300 uppercase mt-2">{new Date(comment.created_at).toLocaleTimeString()}</p>
                </div>
              </div>
              <button 
                onClick={() => handleDeleteComment(comment.id)} 
                className="opacity-0 group-hover:opacity-100 p-2 text-slate-300 hover:text-rose-500 transition-all"
              >
                  <Trash2 size={14} />
              </button>
            </div>
          ))}
        </div>

        {/* --- ADD COMMENT BOX --- */}
        <form onSubmit={handleSendComment} className="ml-10 relative mt-10">
          <textarea 
            className="w-full bg-white border border-slate-200 rounded-[32px] p-8 pr-24 h-40 font-bold text-[#1C1C1C] outline-none focus:ring-8 focus:ring-[#D4FB51]/10 transition-all placeholder:text-slate-300 resize-none shadow-xl shadow-slate-200/50"
            placeholder="Add a moderating comment or helpful response..."
            value={newComment}
            onChange={(e) => setNewComment(e.target.value)}
            required
          />
          <button 
            type="submit"
            disabled={sending || !newComment.trim()}
            className="absolute bottom-8 right-8 bg-[#1C1C1C] text-[#D4FB51] p-4 rounded-2xl hover:scale-110 active:scale-95 transition-all shadow-xl shadow-[#D4FB51]/10 disabled:opacity-50 disabled:grayscale"
          >
            {sending ? <div className="w-5 h-5 border-2 border-[#D4FB51] border-t-transparent rounded-full animate-spin"></div> : <Send size={20} />}
          </button>
        </form>
      </div>
    </div>
  );
}