"use client";
import { useEffect, useRef, useState } from "react";
import { useSession } from "next-auth/react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import Comments from "@/components/Comments";
import ShareModal from "@/components/ShareModal";
import { TopChoicesSection, LatestVideosSection, MembershipUpsellSection } from "@/components/CommunityVideoSections";
import PartnersInMission from "@/components/PartnersInMission";
import { Image as ImageIcon, Video as VideoIcon, Link2, FileText, ChevronDown, Trash2 } from "lucide-react";
import { timeAgo } from "@/lib/timeAgo";

type Post = {
  id: string;
  userId: string;
  authorName: string;
  authorAvatarUrl?: string | null;
  content: string;
  attachmentUrl?: string | null;
  attachmentType?: "image" | "video" | "link" | "pdf" | null;
  prayedCount: number;
  heartCount: number;
  sparkleCount: number;
  likeCount: number;
  createdAt: string;
  badges?: { isFirstPost: boolean; isPrayerWarrior: boolean; isCommunityHelper: boolean };
};

const ATTACH_TYPES = [
  { type: "image" as const, icon: ImageIcon, accept: "image/*" },
  { type: "video" as const, icon: VideoIcon, accept: "video/*" },
  { type: "link" as const, icon: Link2, accept: undefined },
  { type: "pdf" as const, icon: FileText, accept: "application/pdf" },
];

const PAGE_SIZE = 10;

function AuthorAvatar({ name, avatarUrl }: { name: string; avatarUrl?: string | null }) {
  if (avatarUrl) {
    return <img src={avatarUrl} className="w-8 h-8 rounded-full object-cover shrink-0" />;
  }
  return (
    <div className="w-8 h-8 rounded-full bg-neutral-700 flex items-center justify-center text-xs font-bold shrink-0">
      {name[0]?.toUpperCase() || "?"}
    </div>
  );
}

function AuthorBadges({ badges }: { badges?: Post["badges"] }) {
  if (!badges) return null;
  const items: string[] = [];
  if (badges.isPrayerWarrior) items.push("Prayer Warrior");
  if (badges.isCommunityHelper) items.push("Community Helper");
  if (badges.isFirstPost) items.push("First Post");
  if (items.length === 0) return null;

  const colors: Record<string, string> = {
    "Prayer Warrior": "bg-amber-900/40 text-amber-400",
    "Community Helper": "bg-blue-900/40 text-blue-400",
    "First Post": "bg-purple-900/40 text-purple-400",
  };

  return (
    <div className="flex items-center gap-1.5 flex-wrap min-w-0">
      {items.map((label) => (
        <span key={label} className={`text-[10px] px-2 py-0.5 rounded-full whitespace-nowrap shrink-0 ${colors[label]}`}>
          {label}
        </span>
      ))}
    </div>
  );
}

function ReactBtn({ onClick, label, count, title }: { onClick: () => void; label: string; count: number; title?: string }) {
  return (
    <button onClick={onClick} title={title} className="btn-secondary px-2.5 py-1.5 text-xs shrink-0">
      {label} {count}
    </button>
  );
}

function PostCard({ post, onReact, onShare, onDelete, currentUserId }: { post: Post; onReact: (id: string, r: string) => void; onShare: (id: string) => void; onDelete: (id: string) => void; currentUserId?: string }) {
  const p = post;
  const isOwnPost = currentUserId && currentUserId === p.userId;
  return (
    <div className="card p-4 min-w-0 w-full max-w-full overflow-hidden">
      <div className="flex items-start gap-2 mb-2 min-w-0">
        <Link href={`/profile/${p.userId}`} className="shrink-0">
          <AuthorAvatar name={p.authorName} avatarUrl={p.authorAvatarUrl} />
        </Link>
        <div className="min-w-0 flex-1">
          <div className="flex items-center gap-2 flex-wrap min-w-0">
            <Link href={`/profile/${p.userId}`} className="font-semibold text-sm hover:text-red-400 truncate max-w-[200px]">
              {p.authorName}
            </Link>
            <span className="text-neutral-500 text-xs shrink-0">{timeAgo(p.createdAt)}</span>
          </div>
          <div className="mt-1 min-w-0">
            <AuthorBadges badges={p.badges} />
          </div>
        </div>
        {isOwnPost && (
          <button
            onClick={() => onDelete(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 mb-3 whitespace-pre-wrap break-words min-w-0">{p.content}</p>

      {p.attachmentType === "image" && p.attachmentUrl && (
        <img src={p.attachmentUrl} className="rounded-lg max-h-80 w-full max-w-full object-cover mb-3" />
      )}
      {p.attachmentType === "video" && p.attachmentUrl && (
        <video src={p.attachmentUrl} controls className="rounded-lg max-h-80 w-full max-w-full mb-3" />
      )}
      {p.attachmentType === "link" && p.attachmentUrl && (
        <a href={p.attachmentUrl} target="_blank" rel="noopener noreferrer" className="flex items-start gap-2 text-xs text-red-400 underline mb-3 break-all min-w-0">
          <Link2 size={12} className="shrink-0 mt-0.5" /> <span className="min-w-0 break-all">{p.attachmentUrl}</span>
        </a>
      )}
      {p.attachmentType === "pdf" && p.attachmentUrl && (
        <a href={p.attachmentUrl} target="_blank" rel="noopener noreferrer" className="inline-flex items-center gap-2 text-xs bg-neutral-800 px-3 py-2 rounded-lg mb-3 hover:bg-neutral-700 max-w-full">
          <FileText size={14} className="shrink-0" /> <span className="truncate">View PDF attachment</span>
        </a>
      )}

      <div className="flex gap-2 text-xs flex-wrap min-w-0">
        <ReactBtn onClick={() => onReact(p.id, "prayed")} label="I prayed" count={p.prayedCount} title="Let them know you prayed for this" />
        <ReactBtn onClick={() => onReact(p.id, "heart")} label="❤️" count={p.heartCount} title="Send love" />
        <ReactBtn onClick={() => onReact(p.id, "sparkle")} label="✨" count={p.sparkleCount} title="Bless this" />
        <ReactBtn onClick={() => onReact(p.id, "like")} label="👍" count={p.likeCount} title="Show support" />
        <button onClick={() => onShare(p.id)} className="btn-secondary px-2.5 py-1.5 text-xs shrink-0">
          Share
        </button>
      </div>

      <div className="min-w-0 w-full max-w-full">
        <Comments postId={p.id} />
      </div>
    </div>
  );
}

export default function CommunityFeed() {
  const { data: session } = useSession();
  const router = useRouter();
  const [posts, setPosts] = useState<Post[]>([]);
  const [hasMore, setHasMore] = useState(true);
  const [loadingMore, setLoadingMore] = useState(false);
  const [content, setContent] = useState("");
  const [attachType, setAttachType] = useState<"image" | "video" | "link" | "pdf" | null>(null);
  const [attachmentUrl, setAttachmentUrl] = useState("");
  const [uploading, setUploading] = useState(false);
  const [posting, setPosting] = useState(false);
  const [rulesOpen, setRulesOpen] = useState(false);
  const [sharingPostId, setSharingPostId] = useState<string | null>(null);
  const [supporterAlert, setSupporterAlert] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const sentinelRef = useRef<HTMLDivElement>(null);

  async function loadFirstPage() {
    const res = await fetch(`/api/posts?limit=${PAGE_SIZE}&offset=0`);
    const data = await res.json();
    setPosts(data.posts || []);
    setHasMore(!!data.hasMore);
  }

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

  useEffect(() => {
    const el = sentinelRef.current;
    if (!el) return;
    const observer = new IntersectionObserver(
      (entries) => {
        if (entries[0].isIntersecting && hasMore && !loadingMore) {
          fetchNextPage();
        }
      },
      { rootMargin: "200px" }
    );
    observer.observe(el);
    return () => observer.disconnect();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [hasMore, loadingMore, posts.length]);

  async function fetchNextPage() {
    setLoadingMore(true);
    const res = await fetch(`/api/posts?limit=${PAGE_SIZE}&offset=${posts.length}`);
    const data = await res.json();
    setPosts((prev) => [...prev, ...(data.posts || [])]);
    setHasMore(!!data.hasMore);
    setLoadingMore(false);
  }

  function pickAttachment(type: "image" | "video" | "link" | "pdf") {
    if (attachType === type) {
      setAttachType(null);
      setAttachmentUrl("");
      return;
    }
    setAttachType(type);
    setAttachmentUrl("");
    if (type === "link") return;
    fileInputRef.current?.click();
  }

  async function handleFileChosen(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0];
    if (!file || !attachType) return;
    setUploading(true);
    const formData = new FormData();
    formData.append("file", file);
    const res = await fetch("/api/upload", { method: "POST", body: formData });
    const data = await res.json();
    setUploading(false);
    if (res.ok) setAttachmentUrl(data.url);
    e.target.value = "";
  }

  async function submitPost() {
    if (!session?.user) {
      router.push("/login");
      return;
    }
    if (!content.trim()) return;
    setPosting(true);
    const res = await fetch("/api/posts", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ content, attachmentUrl: attachmentUrl || null, attachmentType: attachmentUrl ? attachType : null }),
    });
    const data = await res.json();
    setContent("");
    setAttachmentUrl("");
    setAttachType(null);
    setPosting(false);
    if (res.ok && data.post) {
      // Prepend immediately — no full reload, no scroll jump.
      setPosts((prev) => [data.post, ...prev]);
    }
  }

  async function react(postId: string, reaction: string) {
    if (!session?.user) {
      router.push("/login");
      return;
    }
    const res = await fetch(`/api/posts/${postId}/react`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ reaction }),
    });
    const data = await res.json();
    if (!res.ok) {
      if (data.error === "not_a_supporter") {
        setSupporterAlert(true);
      }
      return;
    }

    const field = { prayed: "prayedCount", heart: "heartCount", sparkle: "sparkleCount", like: "likeCount" }[reaction] as keyof Post;
    const delta = data.reacted ? 1 : -1;
    setPosts((prev) =>
      prev.map((p) => (p.id === postId ? { ...p, [field]: Math.max(0, (p[field] as number) + delta) } : p))
    );
  }

  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.");
    }
  }

  const SupportCard = (
    <div className="card p-5 border-red-900/40 bg-gradient-to-br from-red-950/40 to-transparent min-w-0 w-full max-w-full overflow-hidden">
      <div className="flex items-center gap-2 mb-2 min-w-0">
        <span className="w-9 h-9 rounded-full bg-red-900/50 flex items-center justify-center text-red-400 shrink-0">
          ❤️
        </span>
        <h3 className="font-bold text-sm truncate">Support the Creators</h3>
      </div>
      <p className="text-xs text-neutral-400 mb-3">
        We create daily devotionals and a safe space for prayer and encouragement. Join as a member or
        give once — your optional tips help us produce new content and grow this community.
      </p>
      <ul className="text-xs text-neutral-400 space-y-1.5 mb-4">
        <li className="flex gap-2 min-w-0"><span className="text-green-500 shrink-0">✓</span> <span className="min-w-0">Membership plans and one-time support fund our work</span></li>
        <li className="flex gap-2 min-w-0"><span className="text-green-500 shrink-0">✓</span> <span className="min-w-0">A prayerful community built on respect and care</span></li>
        <li className="flex gap-2 min-w-0"><span className="text-green-500 shrink-0">✓</span> <span className="min-w-0">Devotionals and resources to help you grow in faith</span></li>
      </ul>
      <Link href="/tips" className="btn-primary mx-auto flex items-center justify-center py-3 px-6 text-sm leading-snug text-center w-fit whitespace-nowrap">
        Support the Creators
      </Link>
    </div>
  );

  return (
    <div className="max-w-2xl mx-auto min-w-0 w-full max-w-full">
      {supporterAlert && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 px-4">
          <div className="bg-neutral-900 border border-neutral-700 rounded-2xl p-6 max-w-sm w-full shadow-2xl text-center">
            <div className="text-5xl mb-3">🙏</div>
            <h3 className="font-bold text-lg mb-2">Supporters Only</h3>
            <p className="text-sm text-neutral-400 mb-5 leading-relaxed">
              Reactions are a special way to show love — available to those who support the creators.
              Join our community of supporters to unlock reactions and show your care.
            </p>
            <div className="space-y-2">
              <a href="/tips" className="btn-primary w-full py-3 flex items-center justify-center">
                💝 Support the Creators
              </a>
              <button type="button" onClick={() => setSupporterAlert(false)} className="btn-secondary w-full py-3">
                Maybe later
              </button>
            </div>
          </div>
        </div>
      )}
      <h1 className="text-2xl font-bold text-center mb-1">Pray &amp; Encourage</h1>
      <p className="text-neutral-400 text-center text-sm mb-6">Share prayers, devotions and kind reactions with this community.</p>

      {session?.user ? (
        <div className="card p-4 mb-6 min-w-0 w-full max-w-full overflow-hidden">
          <textarea
            value={content}
            onChange={(e) => setContent(e.target.value)}
            placeholder="Share a prayer request with the community..."
            rows={3}
            className="w-full max-w-full bg-neutral-900 border border-neutral-800 rounded-md px-3 py-2 text-sm outline-none focus:border-red-600 resize-none"
          />

          <input ref={fileInputRef} type="file" className="hidden" onChange={handleFileChosen} accept={ATTACH_TYPES.find((a) => a.type === attachType)?.accept} />

          <div className="flex items-center justify-between mt-2 flex-wrap gap-2 min-w-0">
            <div className="flex items-center gap-1 text-neutral-500 text-xs flex-wrap min-w-0">
              <span className="mr-1 shrink-0">Attach:</span>
              {ATTACH_TYPES.map(({ type, icon: Icon }) => (
                <button
                  key={type}
                  type="button"
                  onClick={() => pickAttachment(type)}
                  title={`Attach ${type}`}
                  className={`w-8 h-8 rounded-full flex items-center justify-center hover:bg-neutral-800 shrink-0 ${
                    attachType === type ? "bg-neutral-800 ring-1 ring-red-600 text-red-400" : "text-neutral-400"
                  }`}
                >
                  <Icon size={16} />
                </button>
              ))}
            </div>
          </div>

          <div className="flex items-center justify-between mt-2 gap-3 flex-wrap min-w-0">
            <button
              type="button"
              onClick={() => setRulesOpen((o) => !o)}
              className="flex items-center gap-1 text-xs text-neutral-500 hover:text-neutral-300 min-w-0"
            >
              <span className="truncate">Community rules</span>
              <ChevronDown size={12} className={`shrink-0 transition-transform ${rulesOpen ? "rotate-180" : ""}`} />
            </button>
            <button onClick={submitPost} disabled={posting || uploading} className="btn-primary px-5 py-2 shrink-0">
              {posting ? "Posting..." : uploading ? "Uploading..." : "Post"}
            </button>
          </div>

          {rulesOpen && (
            <ul className="text-xs text-neutral-400 space-y-1.5 mt-3 bg-neutral-900 rounded-lg p-3 min-w-0">
              <li>• Post only content related to faith, prayer, encouragement, and this community's purpose.</li>
              <li>• Be respectful and kind; no harassment, hate speech, or personal attacks.</li>
              <li>• No spam, ads, or off-topic promotions.</li>
              <li>• Respect privacy — don't share others' personal details without consent.</li>
              <li>• Keep content appropriate; no graphic or offensive material.</li>
            </ul>
          )}

          {attachType === "link" && (
            <input
              value={attachmentUrl}
              onChange={(e) => setAttachmentUrl(e.target.value)}
              placeholder="Paste a link URL here..."
              className="w-full max-w-full bg-neutral-900 border border-neutral-800 rounded-md px-3 py-2 text-xs outline-none focus:border-red-600 mt-2"
            />
          )}
          {attachType && attachType !== "link" && attachmentUrl && (
            <p className="text-xs text-green-500 mt-2">✓ File attached — ready to post</p>
          )}
        </div>
      ) : (
        <div className="card p-5 mb-6 text-center min-w-0 w-full max-w-full">
          <p className="text-sm text-neutral-300 mb-3">Log in to share a prayer request with the community.</p>
          <div className="flex items-center justify-center gap-3 flex-wrap">
            <Link href="/login" className="text-red-500 font-semibold text-sm hover:text-red-400">
              Log in
            </Link>
            <span className="text-neutral-600">or</span>
            <Link href="/register" className="text-red-500 font-semibold text-sm hover:text-red-400">
              Sign up
            </Link>
          </div>
        </div>
      )}

      <div className="space-y-4 min-w-0 w-full max-w-full">
        {posts.length === 0 && <p className="text-neutral-500 text-center">No posts yet. Be the first to share.</p>}
        {posts.map((p, i) => (
          <div key={p.id} className="min-w-0 w-full max-w-full">
            <PostCard post={p} onReact={react} onShare={setSharingPostId} onDelete={deletePost} currentUserId={(session?.user as any)?.id} />
            {(i + 1) % 3 === 0 && (() => {
              const section = ((i + 1) / 3 - 1) % 5;
              if (section === 0) return <div className="mt-4 min-w-0 w-full max-w-full">{SupportCard}</div>;
              if (section === 1) return <div className="lg:hidden mt-4 min-w-0 w-full max-w-full"><PartnersInMission /></div>;
              if (section === 2) return <div className="min-w-0 w-full max-w-full"><TopChoicesSection /></div>;
              if (section === 3) return <div className="min-w-0 w-full max-w-full"><LatestVideosSection /></div>;
              return <div className="min-w-0 w-full max-w-full"><MembershipUpsellSection /></div>;
            })()}
          </div>
        ))}

        <div ref={sentinelRef} className="h-4" />
        {loadingMore && <p className="text-neutral-500 text-center text-sm py-4">Loading more posts...</p>}
        {!hasMore && posts.length > 0 && (
          <p className="text-neutral-600 text-center text-xs py-4">You've reached the beginning of the community feed.</p>
        )}
      </div>

      {sharingPostId && <ShareModal postId={sharingPostId} onClose={() => setSharingPostId(null)} />}
    </div>
  );
}
