"use client"

import { useCallback, useEffect, useRef, useState } from "react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Badge } from "@/components/ui/badge"
import { Card, CardContent } from "@/components/ui/card"
import { ScrollArea } from "@/components/ui/scroll-area"
import { useToast } from "@/hooks/use-toast"
import {
  MessageSquare, Search, Loader2, Trash2, Ban, ShieldCheck, RefreshCw, Users,
} from "lucide-react"

interface ChatUser {
  id: string
  fullName: string
  email: string
  profileImage: string | null
  lastActiveAt: string | null
}

interface ConversationSummary {
  id: string
  lastMessage: string | null
  lastMessageAt: string
  createdAt: string
  userA: ChatUser
  userB: ChatUser
  _count: { messages: number }
}

interface ChatMessage {
  id: string
  content: string
  createdAt: string
  senderId: string
  isRead: boolean
  sender: { id: string; fullName: string; profileImage: string | null }
}

interface ConversationDetail {
  id: string
  userAId: string
  userBId: string
  userA: ChatUser
  userB: ChatUser
  messages: ChatMessage[]
}

function formatTime(value: string | Date | null | undefined): string {
  if (!value) return "—"
  const d = new Date(value)
  const today = new Date()
  const sameDay = d.toDateString() === today.toDateString()
  const time = d.toLocaleTimeString("en-GB", { hour: "2-digit", minute: "2-digit" })
  if (sameDay) return time
  return `${d.toLocaleDateString("en-GB", { day: "2-digit", month: "short" })} ${time}`
}

export function ChatModerationPanel() {
  const { toast } = useToast()
  const [conversations, setConversations] = useState<ConversationSummary[]>([])
  const [selectedId, setSelectedId] = useState<string | null>(null)
  const [detail, setDetail] = useState<ConversationDetail | null>(null)
  const [isBlocked, setIsBlocked] = useState(false)
  const [search, setSearch] = useState("")
  const [loading, setLoading] = useState(true)
  const [actionLoading, setActionLoading] = useState<string | null>(null)
  const detailRef = useRef<ConversationDetail | null>(null)
  detailRef.current = detail

  const loadConversations = useCallback(async () => {
    try {
      const res = await fetch("/api/admin/chat/conversations")
      if (res.ok) setConversations(await res.json())
    } catch (e) {
      console.error("Failed to load conversations", e)
    } finally {
      setLoading(false)
    }
  }, [])

  const loadDetail = useCallback(async (id: string, silent = false) => {
    if (!silent) setActionLoading("load")
    try {
      const res = await fetch(`/api/admin/chat/conversations/${id}`)
      if (res.ok) {
        const data = await res.json()
        setDetail(data.conversation)
        setIsBlocked(!!data.isBlocked)
      }
    } catch (e) {
      console.error("Failed to load conversation", e)
    } finally {
      if (!silent) setActionLoading(null)
    }
  }, [])

  // Real-time: poll the conversation list every 5s
  useEffect(() => {
    loadConversations()
    const listTimer = setInterval(loadConversations, 5000)
    return () => clearInterval(listTimer)
  }, [loadConversations])

  // Real-time: poll the selected thread every 3s
  useEffect(() => {
    if (!selectedId) return
    loadDetail(selectedId)
    const detailTimer = setInterval(() => loadDetail(selectedId, true), 3000)
    return () => clearInterval(detailTimer)
  }, [selectedId, loadDetail])

  const filtered = conversations.filter(c => {
    if (!search.trim()) return true
    const q = search.toLowerCase()
    return (
      c.userA.fullName?.toLowerCase().includes(q) ||
      c.userA.email?.toLowerCase().includes(q) ||
      c.userB.fullName?.toLowerCase().includes(q) ||
      c.userB.email?.toLowerCase().includes(q) ||
      c.lastMessage?.toLowerCase().includes(q)
    )
  })

  const deleteMessage = async (messageId: string) => {
    setActionLoading(messageId)
    try {
      const res = await fetch(`/api/admin/chat/messages/${messageId}`, { method: "DELETE" })
      const data = await res.json()
      if (res.ok) {
        toast({ title: "Deleted", description: "Message removed." })
        if (selectedId) loadDetail(selectedId, true)
        loadConversations()
      } else {
        toast({ title: "Error", description: data.error, variant: "destructive" })
      }
    } catch (e: any) {
      toast({ title: "Error", description: e.message, variant: "destructive" })
    } finally {
      setActionLoading(null)
    }
  }

  const clearThread = async () => {
    if (!selectedId) return
    setActionLoading("clear")
    try {
      const res = await fetch(`/api/admin/chat/conversations/${selectedId}/messages`, { method: "DELETE" })
      const data = await res.json()
      if (res.ok) {
        toast({ title: "Cleared", description: "All messages in this thread were removed." })
        loadDetail(selectedId, true)
        loadConversations()
      } else {
        toast({ title: "Error", description: data.error, variant: "destructive" })
      }
    } catch (e: any) {
      toast({ title: "Error", description: e.message, variant: "destructive" })
    } finally {
      setActionLoading(null)
    }
  }

  const deleteConversation = async () => {
    if (!selectedId) return
    setActionLoading("delete")
    try {
      const res = await fetch(`/api/admin/chat/conversations/${selectedId}`, { method: "DELETE" })
      const data = await res.json()
      if (res.ok) {
        toast({ title: "Deleted", description: "Conversation removed." })
        setSelectedId(null)
        setDetail(null)
        loadConversations()
      } else {
        toast({ title: "Error", description: data.error, variant: "destructive" })
      }
    } catch (e: any) {
      toast({ title: "Error", description: e.message, variant: "destructive" })
    } finally {
      setActionLoading(null)
    }
  }

  const toggleBlock = async () => {
    if (!selectedId) return
    setActionLoading("block")
    try {
      const res = await fetch(`/api/admin/chat/conversations/${selectedId}/block`, { method: "POST" })
      const data = await res.json()
      if (res.ok) {
        setIsBlocked(data.blocked)
        toast({ title: data.blocked ? "Blocked" : "Unblocked", description: data.message })
      } else {
        toast({ title: "Error", description: data.error, variant: "destructive" })
      }
    } catch (e: any) {
      toast({ title: "Error", description: e.message, variant: "destructive" })
    } finally {
      setActionLoading(null)
    }
  }

  const otherUserLabel = (c: { userA: ChatUser; userB: ChatUser }) =>
    `${c.userA.fullName || c.userA.email} ↔ ${c.userB.fullName || c.userB.email}`

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2">
          <span className="relative flex h-2.5 w-2.5">
            <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-green-400 opacity-75" />
            <span className="relative inline-flex rounded-full h-2.5 w-2.5 bg-green-500" />
          </span>
          <span className="text-sm font-medium text-gray-600">Live — updates every few seconds</span>
        </div>
        <Button variant="outline" size="sm" onClick={() => { loadConversations(); if (selectedId) loadDetail(selectedId) }}>
          <RefreshCw className="h-4 w-4 mr-2" /> Refresh
        </Button>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
        {/* Conversation list */}
        <Card className="lg:col-span-1">
          <CardContent className="p-3">
            <div className="relative mb-3">
              <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-gray-400" />
              <Input
                value={search}
                onChange={e => setSearch(e.target.value)}
                placeholder="Search users or messages..."
                className="pl-8"
              />
            </div>

            <ScrollArea className="h-[520px] pr-1">
              {loading ? (
                <div className="flex items-center justify-center h-40">
                  <Loader2 className="h-6 w-6 animate-spin text-gray-400" />
                </div>
              ) : filtered.length === 0 ? (
                <div className="text-center text-sm text-gray-500 py-16">
                  <MessageSquare className="h-8 w-8 mx-auto mb-2 text-gray-300" />
                  No conversations yet.
                </div>
              ) : (
                <div className="space-y-2">
                  {filtered.map(c => (
                    <button
                      key={c.id}
                      onClick={() => setSelectedId(c.id)}
                      className={`w-full text-left rounded-xl border p-3 transition-colors ${
                        selectedId === c.id ? "border-purple-400 bg-purple-50" : "border-gray-200 hover:bg-gray-50"
                      }`}
                    >
                      <div className="flex items-center justify-between gap-2">
                        <span className="text-sm font-semibold text-gray-800 truncate">
                          {c.userA.fullName || c.userA.email} ↔ {c.userB.fullName || c.userB.email}
                        </span>
                        <Badge variant="secondary" className="shrink-0">{c._count.messages}</Badge>
                      </div>
                      <p className="text-xs text-gray-500 truncate mt-1">{c.lastMessage || "No messages"}</p>
                      <p className="text-[10px] text-gray-400 mt-1">{formatTime(c.lastMessageAt)}</p>
                    </button>
                  ))}
                </div>
              )}
            </ScrollArea>
          </CardContent>
        </Card>

        {/* Thread */}
        <Card className="lg:col-span-2">
          <CardContent className="p-3">
            {!selectedId || !detail ? (
              <div className="flex flex-col items-center justify-center h-[520px] text-gray-400">
                <Users className="h-10 w-10 mb-3" />
                <p className="text-sm">Select a conversation to view messages and moderate.</p>
              </div>
            ) : (
              <>
                <div className="flex flex-wrap items-center justify-between gap-2 border-b pb-3 mb-3">
                  <div>
                    <p className="text-sm font-bold text-gray-900">{otherUserLabel(detail)}</p>
                    <p className="text-xs text-gray-500">
                      {detail.userA.email} · {detail.userB.email}
                    </p>
                  </div>
                  <div className="flex items-center gap-2">
                    <Button variant="outline" size="sm" onClick={toggleBlock} disabled={actionLoading === "block"}>
                      {actionLoading === "block" ? <Loader2 className="h-4 w-4 animate-spin mr-2" /> : isBlocked ? <ShieldCheck className="h-4 w-4 mr-2" /> : <Ban className="h-4 w-4 mr-2" />}
                      {isBlocked ? "Unblock Users" : "Block Users"}
                    </Button>
                    <Button variant="outline" size="sm" onClick={clearThread} disabled={actionLoading === "clear"}>
                      {actionLoading === "clear" ? <Loader2 className="h-4 w-4 animate-spin mr-2" /> : <Trash2 className="h-4 w-4 mr-2" />}
                      Clear Thread
                    </Button>
                    <Button variant="destructive" size="sm" onClick={deleteConversation} disabled={actionLoading === "delete"}>
                      {actionLoading === "delete" ? <Loader2 className="h-4 w-4 animate-spin mr-2" /> : <Trash2 className="h-4 w-4 mr-2" />}
                      Delete
                    </Button>
                  </div>
                </div>

                <ScrollArea className="h-[450px] pr-2">
                  {detail.messages.length === 0 ? (
                    <div className="flex items-center justify-center h-40 text-sm text-gray-400">
                      No messages in this thread.
                    </div>
                  ) : (
                    <div className="space-y-3">
                      {detail.messages.map(m => (
                        <div
                          key={m.id}
                          className={`flex gap-2 ${m.senderId === detail.userAId ? "justify-start" : "justify-end"}`}
                        >
                          <div className={`max-w-[75%] rounded-2xl px-3 py-2 text-sm ${
                            m.senderId === detail.userAId
                              ? "bg-gray-100 text-gray-900"
                              : "bg-purple-600 text-white"
                          }`}>
                            <div className="flex items-center gap-2 mb-0.5">
                              <span className={`text-[10px] font-semibold ${m.senderId === detail.userAId ? "text-gray-500" : "text-purple-200"}`}>
                                {m.sender.fullName || "User"}
                              </span>
                              <span className={`text-[9px] ${m.senderId === detail.userAId ? "text-gray-400" : "text-purple-300"}`}>
                                {formatTime(m.createdAt)}
                              </span>
                            </div>
                            <p className="whitespace-pre-wrap break-words">{m.content}</p>
                          </div>
                          <Button
                            variant="ghost"
                            size="icon"
                            className="h-7 w-7 self-center text-gray-400 hover:text-red-500"
                            onClick={() => deleteMessage(m.id)}
                            disabled={actionLoading === m.id}
                          >
                            {actionLoading === m.id ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Trash2 className="h-3.5 w-3.5" />}
                          </Button>
                        </div>
                      ))}
                    </div>
                  )}
                </ScrollArea>
              </>
            )}
          </CardContent>
        </Card>
      </div>
    </div>
  )
}
