"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Badge } from "@/components/ui/badge";
import { cn } from "@/lib/utils";

type ConversationSummary = {
  id: string;
  otherUser: { id: string; name: string; username: string | null; avatarUrl: string | null } | null;
  lastMessage: string | null;
  lastMessageAt: string;
  unreadCount: number;
};

export function ConversationsList() {
  const pathname = usePathname();
  const [conversations, setConversations] = useState<ConversationSummary[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    let cancelled = false;
    async function load() {
      const res = await fetch("/api/v1/conversations");
      if (res.ok && !cancelled) {
        const data = (await res.json()) as { conversations: ConversationSummary[] };
        setConversations(data.conversations);
      }
      if (!cancelled) setLoading(false);
    }
    void load();
    const interval = setInterval(load, 10000);
    return () => { cancelled = true; clearInterval(interval); };
  }, []);

  if (loading) return <p className="text-sm text-muted-foreground p-4">Loading…</p>;
  if (conversations.length === 0) {
    return <p className="text-sm text-muted-foreground p-4">No conversations yet. Visit a profile to say hi.</p>;
  }

  return (
    <div className="divide-y">
      {conversations.map((c) => (
        <Link
          key={c.id}
          href={`/messages/${c.id}`}
          className={cn(
            "flex items-center gap-3 p-3 hover:bg-accent transition-colors",
            pathname === `/messages/${c.id}` && "bg-accent"
          )}
        >
          <Avatar className="h-10 w-10 shrink-0">
            {c.otherUser?.avatarUrl && <AvatarImage src={c.otherUser.avatarUrl} />}
            <AvatarFallback>{(c.otherUser?.name ?? "?").slice(0, 2).toUpperCase()}</AvatarFallback>
          </Avatar>
          <div className="flex-1 min-w-0">
            <div className="flex items-center justify-between gap-2">
              <p className={cn("text-sm truncate", c.unreadCount > 0 && "font-semibold")}>
                {c.otherUser?.name ?? "Unknown"}
              </p>
              {c.unreadCount > 0 && (
                <Badge variant="destructive" className="h-4 min-w-4 px-1 text-[10px] shrink-0">
                  {c.unreadCount > 9 ? "9+" : c.unreadCount}
                </Badge>
              )}
            </div>
            <p className={cn("text-xs truncate", c.unreadCount > 0 ? "text-foreground" : "text-muted-foreground")}>
              {c.lastMessage ?? "No messages yet"}
            </p>
          </div>
        </Link>
      ))}
    </div>
  );
}
