"use client";
import { useState } from "react";
import { useSession } from "next-auth/react";
import Comments from "@/components/Comments";
import { Trash2 } from "lucide-react";

type Post = {
  id: string;
  content: string;
  createdAt: string;
  prayedCount: number;
  heartCount: number;
  sparkleCount: number;
  likeCount: number;
};

function timeAgo(iso: string) {
  const diff = Date.now() - new Date(iso).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`;
  return `${Math.floor(hrs / 24)}d ago`;
}

export default function ProfilePostsClient({ posts: initialPosts, authorName, profileUserId }: { posts: Post[]; authorName: string; profileUserId?: string }) {
  const { data: session } = useSession();
  const [posts, setPosts] = useState(initialPosts);
  const isOwnProfile = profileUserId && (session?.user as any)?.id === profileUserId;

  async function deletePost(postId: string) {
    if (!confirm("Delete this post? This can't be undone.")) return;
    const res = await fetch(`/api/posts/${postId}`, { method: "DELETE" });
    if (res.ok) {
      setPosts((prev) => prev.filter((p) => p.id !== postId));
    } else {
      const data = await res.json();
      alert(data.error || "Failed to delete post.");
    }
  }

  return (
    <div>
      <h3 className="font-bold mb-3">Recent Prayer Requests</h3>
      {posts.length === 0 ? (
        <div className="card p-5">
          <p className="text-neutral-500 text-sm">Nothing shared yet.</p>
        </div>
      ) : (
        <div className="space-y-4">
          {posts.map((p) => (
            <div key={p.id} className="card p-4">
              <div className="flex items-start justify-between gap-2 mb-1">
                <p className="text-xs text-neutral-500">{timeAgo(p.createdAt)}</p>
                {isOwnProfile && (
                  <button
                    onClick={() => deletePost(p.id)}
                    title="Delete this post"
                    className="text-neutral-600 hover:text-red-500 shrink-0 p-1"
                  >
                    <Trash2 size={16} />
                  </button>
                )}
              </div>
              <p className="text-sm text-neutral-200 whitespace-pre-wrap break-words mb-3">{p.content}</p>
              <div className="flex gap-3 text-xs text-neutral-400 mb-3">
                <span title="People who prayed">🙏 {p.prayedCount}</span>
                <span title="Love reactions">❤️ {p.heartCount}</span>
                <span title="Bless reactions">✨ {p.sparkleCount}</span>
                <span title="Support reactions">👍 {p.likeCount}</span>
              </div>
              <Comments postId={p.id} />
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
