import { Link } from "@tanstack/react-router";
import { Heart, MessageCircle } from "lucide-react";
import { useState } from "react";
import { toast } from "sonner";
import { BaseballCard } from "@/components/cards/baseball-card";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { addComment, listComments, toggleLike } from "@/lib/server/api";
import type { CommentItem, PostItem } from "@/lib/types";
import { formatRelativeTime, cn } from "@/lib/utils";

export function PostCard({
  post: initial,
  signedIn,
}: {
  post: PostItem;
  signedIn: boolean;
}) {
  const [post, setPost] = useState(initial);
  const [comments, setComments] = useState<CommentItem[] | null>(null);
  const [showComments, setShowComments] = useState(false);
  const [draft, setDraft] = useState("");
  const [busy, setBusy] = useState(false);

  async function onLike() {
    if (!signedIn) {
      toast.message("Sign in to like posts");
      return;
    }
    try {
      const res = await toggleLike({ data: post.id });
      setPost((p) => ({ ...p, likedByMe: res.liked, likeCount: res.likeCount }));
    } catch (err) {
      toast.error(err instanceof Error ? err.message : "Could not like");
    }
  }

  async function openComments() {
    setShowComments((v) => !v);
    if (comments) return;
    try {
      const list = await listComments({ data: post.id });
      setComments(list);
    } catch {
      setComments([]);
    }
  }

  async function sendComment(e: React.FormEvent) {
    e.preventDefault();
    if (!signedIn) {
      toast.message("Sign in to comment");
      return;
    }
    if (!draft.trim()) return;
    setBusy(true);
    try {
      const c = await addComment({ data: { postId: post.id, content: draft.trim() } });
      setComments((prev) => [...(prev ?? []), c]);
      setPost((p) => ({ ...p, commentCount: p.commentCount + 1 }));
      setDraft("");
    } catch (err) {
      toast.error(err instanceof Error ? err.message : "Could not comment");
    } finally {
      setBusy(false);
    }
  }

  return (
    <Card>
      <CardContent className="pt-5 space-y-4">
        <div className="flex items-start gap-3">
          <Link to="/u/$handle" params={{ handle: post.authorHandle }}>
            <Avatar className="h-10 w-10">
              {post.authorAvatarUrl ? <AvatarImage src={post.authorAvatarUrl} /> : null}
              <AvatarFallback>{post.authorDisplayName.charAt(0)}</AvatarFallback>
            </Avatar>
          </Link>
          <div className="min-w-0 flex-1">
            <div className="flex flex-wrap items-baseline gap-x-2 gap-y-0.5">
              <Link
                to="/u/$handle"
                params={{ handle: post.authorHandle }}
                className="font-semibold text-sm hover:underline"
              >
                {post.authorDisplayName}
              </Link>
              <span className="text-xs text-subtle">@{post.authorHandle}</span>
              <span className="text-xs text-subtle">· {formatRelativeTime(post.createdAt)}</span>
            </div>
            <p className="mt-1.5 text-sm leading-relaxed whitespace-pre-wrap">{post.content}</p>
          </div>
        </div>

        {post.card && (
          <div className="flex justify-center sm:justify-start pl-0 sm:pl-13">
            <BaseballCard card={post.card} size="sm" />
          </div>
        )}

        <div className="flex items-center gap-2 border-t border-border pt-3">
          <Button
            type="button"
            variant="ghost"
            size="sm"
            onClick={() => void onLike()}
            className={cn(post.likedByMe && "text-danger")}
          >
            <Heart className={cn("h-4 w-4", post.likedByMe && "fill-current")} />
            {post.likeCount}
          </Button>
          <Button type="button" variant="ghost" size="sm" onClick={() => void openComments()}>
            <MessageCircle className="h-4 w-4" />
            {post.commentCount}
          </Button>
        </div>

        {showComments && (
          <div className="space-y-3 border-t border-border pt-3">
            {comments === null ? (
              <p className="text-xs text-muted">Loading comments…</p>
            ) : comments.length === 0 ? (
              <p className="text-xs text-muted">No comments yet.</p>
            ) : (
              <ul className="space-y-2">
                {comments.map((c) => (
                  <li key={c.id} className="flex gap-2 text-sm">
                    <Avatar className="h-7 w-7 shrink-0">
                      {c.authorAvatarUrl ? <AvatarImage src={c.authorAvatarUrl} /> : null}
                      <AvatarFallback className="text-xs">
                        {c.authorDisplayName.charAt(0)}
                      </AvatarFallback>
                    </Avatar>
                    <div>
                      <p>
                        <Link
                          to="/u/$handle"
                          params={{ handle: c.authorHandle }}
                          className="font-medium hover:underline"
                        >
                          {c.authorDisplayName}
                        </Link>{" "}
                        <span className="text-fg/90">{c.content}</span>
                      </p>
                      <p className="text-[11px] text-subtle">{formatRelativeTime(c.createdAt)}</p>
                    </div>
                  </li>
                ))}
              </ul>
            )}
            {signedIn && (
              <form onSubmit={sendComment} className="flex gap-2">
                <Input
                  value={draft}
                  onChange={(e) => setDraft(e.target.value)}
                  placeholder="Write a comment…"
                  maxLength={280}
                />
                <Button type="submit" size="sm" disabled={busy || !draft.trim()}>
                  Send
                </Button>
              </form>
            )}
          </div>
        )}
      </CardContent>
    </Card>
  );
}
