"use client";
import { useState, useEffect, useCallback } from "react";
import type { Conversation, Message } from "@/types/marketplace";

const BASE_URL = process.env.NEXT_PUBLIC_API_BASE_URL ?? "";

export function useMessages() {
  const [conversations, setConversations] = useState<Conversation[]>([]);
  const [activeConversation, setActiveConversation] = useState<Conversation | null>(null);
  const [messages, setMessages] = useState<Message[]>([]);
  const [loading, setLoading] = useState(true);
  const [sending, setSending] = useState(false);

  const totalUnread = conversations.reduce((sum, c) => sum + c.unreadCount, 0);

  useEffect(() => {
    fetch(`${BASE_URL}/api/marketplace/messages`)
      .then((r) => r.json())
      .then(setConversations)
      .catch(() => setConversations([]))
      .finally(() => setLoading(false));
  }, []);

  const openConversation = useCallback(async (conversation: Conversation) => {
    setActiveConversation(conversation);
    try {
      const res = await fetch(
        `${BASE_URL}/api/marketplace/messages/${conversation.id}`
      );
      const data: Message[] = await res.json();
      setMessages(data);
      setConversations((prev) =>
        prev.map((c) => (c.id === conversation.id ? { ...c, unreadCount: 0 } : c))
      );
    } catch {
      setMessages([]);
    }
  }, []);

  const sendMessage = useCallback(
    async (text: string, images?: string[]) => {
      if (!activeConversation) return;
      setSending(true);
      try {
        const res = await fetch(
          `${BASE_URL}/api/marketplace/messages/${activeConversation.id}`,
          {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ text, images }),
          }
        );
        const msg: Message = await res.json();
        setMessages((prev) => [...prev, msg]);
        setConversations((prev) =>
          prev.map((c) =>
            c.id === activeConversation.id
              ? { ...c, lastMessage: text, lastMessageAt: msg.createdAt }
              : c
          )
        );
      } finally {
        setSending(false);
      }
    },
    [activeConversation]
  );

  return {
    conversations,
    activeConversation,
    messages,
    loading,
    sending,
    totalUnread,
    openConversation,
    sendMessage,
  };
}
