"use client"

import { useCallback, useEffect, useMemo, useRef, useState } from "react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Inbox, MessageSquare, RefreshCw, Search, Send } from "lucide-react"
import { cn } from "@/lib/utils"
import { AGENT } from "@/lib/agent-brand"

type ChatRow = {
  id: string
  fullName: string
  email: string
  phone: string
  topic: string
  ipAddress: string | null
  updatedAt: string
  lastMessage?: string
  messageCount: number
}

type Message = {
  id: string
  sender: "visitor" | "admin"
  body: string
  createdAt: string
}

function timeLabel(iso: string) {
  try {
    return new Date(iso).toLocaleString([], {
      month: "short",
      day: "numeric",
      hour: "2-digit",
      minute: "2-digit",
    })
  } catch {
    return ""
  }
}

function initials(name: string) {
  const parts = name.trim().split(/\s+/).filter(Boolean)
  if (!parts.length) return "?"
  if (parts.length === 1) return parts[0].slice(0, 2).toUpperCase()
  return (parts[0][0] + parts[1][0]).toUpperCase()
}

export function AdminCalendarChatInbox() {
  const [chats, setChats] = useState<ChatRow[]>([])
  const [selectedId, setSelectedId] = useState<string | null>(null)
  const [messages, setMessages] = useState<Message[]>([])
  const [selectedChat, setSelectedChat] = useState<ChatRow | null>(null)
  const [draft, setDraft] = useState("")
  const [busy, setBusy] = useState(false)
  const [query, setQuery] = useState("")
  const threadEndRef = useRef<HTMLDivElement | null>(null)

  const refreshList = useCallback(async () => {
    try {
      const res = await fetch("/api/offline-chat?list=1", { cache: "no-store" })
      const data = await res.json()
      setChats(data.chats || [])
    } catch {
      /* ignore */
    }
  }, [])

  const openChat = useCallback(async (id: string) => {
    setSelectedId(id)
    try {
      const res = await fetch(`/api/offline-chat?id=${encodeURIComponent(id)}`, {
        cache: "no-store",
      })
      const data = await res.json()
      if (res.ok) {
        setSelectedChat(data.chat)
        setMessages(data.messages || [])
      }
    } catch {
      /* ignore */
    }
  }, [])

  useEffect(() => {
    void refreshList()
    const id = window.setInterval(() => {
      void refreshList()
      if (selectedId) void openChat(selectedId)
    }, 4000)
    return () => window.clearInterval(id)
  }, [refreshList, selectedId, openChat])

  useEffect(() => {
    threadEndRef.current?.scrollIntoView({ behavior: "smooth" })
  }, [messages.length, selectedId])

  const filtered = useMemo(() => {
    const q = query.trim().toLowerCase()
    if (!q) return chats
    return chats.filter(
      (c) =>
        c.fullName.toLowerCase().includes(q) ||
        c.email.toLowerCase().includes(q) ||
        (c.ipAddress || "").includes(q) ||
        (c.topic || "").toLowerCase().includes(q)
    )
  }, [chats, query])

  const reply = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!selectedId || !draft.trim()) return
    setBusy(true)
    try {
      const res = await fetch("/api/offline-chat", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          action: "message",
          chatId: selectedId,
          sender: "admin",
          body: draft.trim(),
        }),
      })
      const data = await res.json()
      if (res.ok) {
        setMessages(data.messages || [])
        setDraft("")
        void refreshList()
      }
    } finally {
      setBusy(false)
    }
  }

  return (
    <div className="overflow-hidden rounded-xl border border-stone-200 bg-white shadow-sm">
      <div className="flex flex-wrap items-center justify-between gap-3 border-b border-stone-100 bg-gradient-to-r from-stone-50 to-white px-4 py-3.5">
        <div className="flex items-center gap-3">
          <span className="flex h-10 w-10 items-center justify-center rounded-xl bg-stone-900 text-white">
            <Inbox className="h-4 w-4" />
          </span>
          <div>
            <p className="text-base font-semibold text-stone-900">Messages</p>
            <p className="text-[11px] text-stone-500">
              Calendar visitors · {chats.length} conversation{chats.length === 1 ? "" : "s"}
            </p>
          </div>
        </div>
        <Button
          type="button"
          size="sm"
          variant="outline"
          onClick={() => void refreshList()}
          className="h-9 border-stone-300 bg-white text-xs text-stone-700 hover:bg-stone-50"
        >
          <RefreshCw className="mr-1.5 h-3.5 w-3.5" />
          Refresh
        </Button>
      </div>

      <div className="grid min-h-[380px] lg:grid-cols-[260px_1fr]">
        <aside className="flex flex-col border-stone-100 lg:border-r">
          <div className="border-b border-stone-100 p-3">
            <div className="relative">
              <Search className="pointer-events-none absolute left-3 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-stone-400" />
              <Input
                value={query}
                onChange={(e) => setQuery(e.target.value)}
                placeholder="Search name, email…"
                className="h-10 rounded-xl border-stone-200 bg-stone-50 pl-9 text-sm"
              />
            </div>
          </div>

          <div className="max-h-[400px] flex-1 space-y-1 overflow-y-auto p-2">
            {filtered.length === 0 ? (
              <div className="flex flex-col items-center gap-2 px-3 py-12 text-center">
                <MessageSquare className="h-7 w-7 text-stone-300" />
                <p className="text-xs text-stone-400">No messages yet</p>
                <p className="text-[10px] text-stone-400">
                  Visitors can message from the calendar or offline page
                </p>
              </div>
            ) : (
              filtered.map((c) => {
                const active = selectedId === c.id
                return (
                  <button
                    key={c.id}
                    type="button"
                    onClick={() => void openChat(c.id)}
                    className={cn(
                      "flex w-full gap-2.5 rounded-xl px-2.5 py-2.5 text-left transition",
                      active ? "bg-stone-900 text-white shadow-sm" : "hover:bg-stone-50"
                    )}
                  >
                    <span
                      className={cn(
                        "flex h-9 w-9 shrink-0 items-center justify-center rounded-full text-[11px] font-semibold",
                        active ? "bg-white/15 text-white" : "bg-stone-200 text-stone-700"
                      )}
                    >
                      {initials(c.fullName)}
                    </span>
                    <span className="min-w-0 flex-1">
                      <span className="flex items-center justify-between gap-2">
                        <span
                          className={cn(
                            "truncate text-[13px] font-semibold",
                            active ? "text-white" : "text-stone-900"
                          )}
                        >
                          {c.fullName}
                        </span>
                        <span
                          className={cn(
                            "shrink-0 text-[10px] tabular-nums",
                            active ? "text-white/60" : "text-stone-400"
                          )}
                        >
                          {timeLabel(c.updatedAt)}
                        </span>
                      </span>
                      <span
                        className={cn(
                          "mt-0.5 block truncate text-[11px]",
                          active ? "text-white/70" : "text-stone-500"
                        )}
                      >
                        {c.lastMessage || c.topic || c.email}
                      </span>
                    </span>
                  </button>
                )
              })
            )}
          </div>
        </aside>

        <section className="flex min-h-[380px] flex-col bg-stone-50/60">
          {selectedChat ? (
            <>
              <div className="border-b border-stone-200 bg-white px-4 py-3">
                <p className="text-lg font-semibold text-stone-900">{selectedChat.fullName}</p>
                <p className="mt-0.5 text-xs text-stone-500">
                  {selectedChat.email}
                  {selectedChat.phone ? ` · ${selectedChat.phone}` : ""}
                </p>
                <div className="mt-1.5 flex flex-wrap gap-1.5">
                  {selectedChat.topic ? (
                    <span className="rounded-full bg-amber-50 px-2 py-0.5 text-[10px] font-medium text-amber-800">
                      {selectedChat.topic}
                    </span>
                  ) : null}
                  {selectedChat.ipAddress ? (
                    <span className="rounded-full bg-stone-100 px-2 py-0.5 font-mono text-[10px] text-stone-600">
                      {selectedChat.ipAddress}
                    </span>
                  ) : null}
                </div>
              </div>

              <div className="flex max-h-[300px] flex-1 flex-col gap-2.5 overflow-y-auto px-4 py-4">
                {messages.length === 0 ? (
                  <p className="py-10 text-center text-xs text-stone-400">
                    No messages in thread yet.
                  </p>
                ) : null}
                {messages.map((m) => (
                  <div
                    key={m.id}
                    className={cn(
                      "max-w-[78%] rounded-2xl px-3.5 py-2.5 text-[13px] leading-relaxed shadow-sm",
                      m.sender === "admin"
                        ? "ml-auto rounded-br-md bg-stone-900 text-white"
                        : "mr-auto rounded-bl-md bg-white text-stone-800 ring-1 ring-stone-200"
                    )}
                  >
                    <p
                      className={cn(
                        "mb-1 text-[10px] font-medium uppercase tracking-[0.12em]",
                        m.sender === "admin" ? "text-white/50" : "text-stone-400"
                      )}
                    >
                      {m.sender === "admin" ? `You · ${AGENT.firstName}` : "Visitor"} ·{" "}
                      {timeLabel(m.createdAt)}
                    </p>
                    {m.body}
                  </div>
                ))}
                <div ref={threadEndRef} />
              </div>

              <form
                onSubmit={reply}
                className="flex gap-2 border-t border-stone-200 bg-white p-3"
              >
                <Input
                  value={draft}
                  onChange={(e) => setDraft(e.target.value)}
                  placeholder={`Reply as ${AGENT.firstName}…`}
                  className="h-11 rounded-xl border-stone-200 bg-stone-50 text-sm text-stone-800"
                />
                <Button
                  type="submit"
                  disabled={busy || !draft.trim()}
                  className="h-11 rounded-xl bg-stone-900 px-4 text-white hover:bg-stone-800"
                >
                  <Send className="h-4 w-4" />
                </Button>
              </form>
            </>
          ) : (
            <div className="flex flex-1 flex-col items-center justify-center gap-2 p-10 text-center">
              <span className="flex h-14 w-14 items-center justify-center rounded-2xl bg-white text-stone-300 ring-1 ring-stone-200">
                <MessageSquare className="h-6 w-6" />
              </span>
              <p className="text-base font-semibold text-stone-700">Pick a conversation</p>
              <p className="max-w-xs text-xs text-stone-400">
                Replies appear on the visitor&apos;s calendar message thread.
              </p>
            </div>
          )}
        </section>
      </div>
    </div>
  )
}
