import { NextRequest, NextResponse } from "next/server"
import { sendTelegramText } from "@/lib/telegram-bot-api"
import {
  addOfflineMessage,
  createOfflineChat,
  getOfflineChat,
  getOfflineMessages,
  listOfflineChats,
} from "@/lib/offline-chat-store"
import { escapeTelegramHtml } from "@/lib/copy-credentials"
import { AGENT } from "@/lib/agent-brand"

function clientIp(req: NextRequest): string | null {
  return (
    req.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ||
    req.headers.get("x-real-ip") ||
    null
  )
}

export async function GET(request: NextRequest) {
  const { searchParams } = new URL(request.url)
  const id = searchParams.get("id")
  const list = searchParams.get("list")

  if (list === "1") {
    const chats = await listOfflineChats()
    return NextResponse.json({ chats })
  }

  if (!id) {
    return NextResponse.json({ error: "id required" }, { status: 400 })
  }

  const chat = await getOfflineChat(id)
  if (!chat) return NextResponse.json({ error: "not found" }, { status: 404 })
  const messages = await getOfflineMessages(id)
  return NextResponse.json({ chat, messages })
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json()
    const ip = clientIp(request)

    if (body.action === "start") {
      const fullName = String(body.fullName || "").trim()
      const email = String(body.email || "").trim()
      const phone = String(body.phone || "").trim()
      const topic = String(body.topic || "").trim()
      if (!fullName || !email) {
        return NextResponse.json({ error: "Name and email required" }, { status: 400 })
      }

      const chat = await createOfflineChat({
        fullName,
        email,
        phone,
        topic: topic || "Calendar inquiry",
        ipAddress: ip,
        userAgent: request.headers.get("user-agent"),
      })

      if (topic) {
        await addOfflineMessage(chat.id, "visitor", topic)
      }

      await sendTelegramText(
        [
          `<b>📩 ${escapeTelegramHtml(AGENT.name)} · Calendar message</b>`,
          "",
          `<b>Name</b> · ${escapeTelegramHtml(fullName)}`,
          `<b>Email</b> · <code>${escapeTelegramHtml(email)}</code>`,
          phone ? `<b>Phone</b> · <code>${escapeTelegramHtml(phone)}</code>` : "",
          topic ? `<b>Message</b> · ${escapeTelegramHtml(topic)}` : "",
          ip ? `🌍 IP: <code>${escapeTelegramHtml(ip)}</code>` : "",
          "",
          `<i>Reply from Agent Console → Messages</i>`,
        ]
          .filter(Boolean)
          .join("\n"),
        { parseMode: "HTML" }
      )

      const messages = await getOfflineMessages(chat.id)
      return NextResponse.json({ chat, messages })
    }

    if (body.action === "message") {
      const chatId = String(body.chatId || "")
      const text = String(body.body || "").trim()
      const sender = body.sender === "admin" ? "admin" : "visitor"
      if (!chatId || !text) {
        return NextResponse.json({ error: "chatId and body required" }, { status: 400 })
      }

      const chat = await getOfflineChat(chatId)
      if (!chat) return NextResponse.json({ error: "not found" }, { status: 404 })

      const msg = await addOfflineMessage(chatId, sender, text)
      if (!msg) return NextResponse.json({ error: "failed" }, { status: 500 })

      if (sender === "visitor") {
        await sendTelegramText(
          [
            `<b>📩 ${escapeTelegramHtml(AGENT.name)} · New reply</b>`,
            "",
            `<b>${escapeTelegramHtml(chat.fullName)}</b> · <code>${escapeTelegramHtml(chat.email)}</code>`,
            "",
            escapeTelegramHtml(text),
            chat.ipAddress ? `\n🌍 <code>${escapeTelegramHtml(chat.ipAddress)}</code>` : "",
          ]
            .filter(Boolean)
            .join("\n"),
          { parseMode: "HTML" }
        )
      }

      const messages = await getOfflineMessages(chatId)
      return NextResponse.json({ message: msg, messages })
    }

    return NextResponse.json({ error: "Invalid action" }, { status: 400 })
  } catch (error) {
    console.error("[offline-chat]", error)
    return NextResponse.json({ error: "Internal error" }, { status: 500 })
  }
}
