"use client";
import { useEffect, useState, useCallback } from "react";
import { createClient } from "@/utils/supabase/client";
import Link from "next/link";
import { 
  Search, Trash2, Plus, Clock, MessageCircle, Heart, Loader2 
} from "lucide-react";

interface Post {
  id: string;
  content: string;
  media_url: string | null;
  media_type: 'image' | 'video' | 'none';
  created_at: string;
  profiles: {
    full_name: string | null;
    avatar_url: string | null;
  };
  community_comments: { count: number }[];
  community_likes: { count: number }[];
}

export default function PostsPage() {
  const supabase = createClient();
  const [posts, setPosts] = useState<Post[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState("");

  const fetchPosts = useCallback(async () => {
    setLoading(true);
    const { data, error } = await supabase
      .from('community_posts')
      .select(`
        *,
        profiles:user_id (full_name, avatar_url),
        community_comments(count),
        community_likes(count)
      `)
      .order('created_at', { ascending: false });

    if (!error) {
      setPosts(data as any[] || []);
    }
    setLoading(false);
  }, [supabase]);

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

  const handleDelete = async (postId: string) => {
    if (!confirm("Are you sure? This action cannot be undone.")) return;
    const { error } = await supabase.from('community_posts').delete().eq('id', postId);
    if (!error) setPosts(prev => prev.filter(p => p.id !== postId));
  };

  const filteredPosts = posts.filter(p => 
    p.content?.toLowerCase().includes(searchTerm.toLowerCase()) ||
    p.profiles?.full_name?.toLowerCase().includes(searchTerm.toLowerCase())
  );

  return (
    <div className="space-y-6 animate-in fade-in duration-700 pb-10 px-4 md:px-0">
      {/* --- HEADER --- */}
      <div className="flex flex-col lg:flex-row lg:items-end justify-between gap-6">
        <div>
          <h1 className="text-2xl md:text-3xl font-black text-[#1C1C1C] tracking-tighter uppercase">
            Community Feed
          </h1>
          <p className="text-[10px] md:text-[11px] text-slate-500 font-black uppercase tracking-[0.2em] mt-1">
            Moderating {posts.length} Community Posts
          </p>
        </div>
        
        <div className="flex items-center gap-3 w-full lg:w-auto">
          <div className="relative flex-1 lg:w-80 bg-white rounded-2xl shadow-sm border border-slate-200 px-4 py-3 flex items-center focus-within:ring-2 focus-within:ring-[#D4FB51]/50 transition-all">
            <Search className="text-slate-400 mr-2 shrink-0" size={18} />
            <input 
              type="text" 
              placeholder="Search by content or author..." 
              className="bg-transparent border-none outline-none text-sm font-bold text-[#1C1C1C] w-full"
              onChange={(e) => setSearchTerm(e.target.value)}
            />
          </div>
          <Link 
            href="/dashboard/posts/new" 
            className="bg-[#1C1C1C] text-[#D4FB51] p-3.5 rounded-2xl shadow-xl hover:scale-105 active:scale-95 transition-all shrink-0"
          >
            <Plus size={20} />
          </Link>
        </div>
      </div>

      {/* --- POSTS GRID --- */}
      <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 gap-4 md:gap-6">
        {loading ? (
           <div className="col-span-full py-20 flex flex-col items-center justify-center gap-4">
             <Loader2 className="w-8 h-8 text-[#D4FB51] animate-spin" />
             <p className="text-[10px] font-black uppercase tracking-widest text-slate-400">Loading Posts...</p>
           </div>
        ) : filteredPosts.length === 0 ? (
          <div className="col-span-full py-20 text-center bg-white rounded-[32px] border border-dashed border-slate-200">
            <p className="text-sm font-bold text-slate-400">No posts found matching your search.</p>
          </div>
        ) : filteredPosts.map((post) => (
          <div key={post.id} className="bg-white rounded-[24px] md:rounded-[32px] p-5 md:p-6 shadow-sm border border-slate-100 flex flex-col justify-between hover:shadow-md transition-all group">
            <div>
              {/* User Header */}
              <div className="flex items-center gap-3 mb-4">
                {post.profiles?.avatar_url ? (
                  <img src={post.profiles.avatar_url} className="w-9 h-9 md:w-10 md:h-10 rounded-xl object-cover shrink-0" alt="avatar" />
                ) : (
                  <div className="w-9 h-9 md:w-10 md:h-10 rounded-xl bg-slate-100 flex items-center justify-center font-black text-xs text-slate-400 shrink-0">
                    {post.profiles?.full_name?.substring(0,1) || "U"}
                  </div>
                )}
                <div className="min-w-0">
                  <p className="text-sm font-black text-[#1C1C1C] truncate">
                    {post.profiles?.full_name || "Anonymous Parent"}
                  </p>
                  <p className="text-[9px] md:text-[10px] text-slate-400 font-bold uppercase tracking-tight flex items-center gap-1">
                    <Clock size={10} /> {new Date(post.created_at).toLocaleDateString()}
                  </p>
                </div>
              </div>

              {/* Media Preview */}
              {post.media_url && post.media_type === 'image' && (
                <div className="mb-4 rounded-2xl overflow-hidden aspect-video bg-slate-100 border border-slate-50">
                  <img src={post.media_url} alt="Post content" className="w-full h-full object-cover" />
                </div>
              )}

              <p className="text-xs md:text-sm font-medium text-slate-600 leading-relaxed mb-6 line-clamp-3">
                {post.content}
              </p>
            </div>

            {/* Footer Actions */}
            <div className="pt-4 border-t border-slate-50">
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-3 md:gap-4">
                  <div className="flex items-center gap-1 text-slate-400">
                    <Heart size={14} className={post.community_likes?.[0]?.count > 0 ? "fill-rose-500 text-rose-500" : ""} />
                    <span className="text-[10px] font-black">{post.community_likes?.[0]?.count || 0}</span>
                  </div>
                  <div className="flex items-center gap-1 text-slate-400">
                    <MessageCircle size={14} />
                    <span className="text-[10px] font-black">{post.community_comments?.[0]?.count || 0}</span>
                  </div>
                </div>

                <div className="flex items-center gap-2">
                  <Link 
                    href={`/dashboard/posts/${post.id}`}
                    className="px-3 py-2 text-[10px] font-black uppercase bg-[#D4FB51] text-black rounded-lg hover:scale-105 transition-transform"
                  >
                    View
                  </Link>
                  <button 
                    onClick={() => handleDelete(post.id)}
                    className="p-2 text-slate-300 hover:text-rose-500 transition-colors"
                  >
                    <Trash2 size={16} />
                  </button>
                </div>
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}