import { useEffect, useLayoutEffect, useRef, useState, type FormEvent, type KeyboardEvent } from 'react'
import { Check, CheckCheck, Loader2, SendHorizontal } from 'lucide-react'
import { toast } from 'sonner'
import { Button } from '@/components/ui/button'
import { Textarea } from '@/components/ui/textarea'
import { CHAT_MAX_LENGTH, CHAT_POLL_MS } from '@/lib/chat'
import { cn } from '@/lib/utils'

export type ChatMessage = {
  id: number
  sender: 'customer' | 'admin'
  body: string
  adminEmail: string | null
  readAt: string | null
  createdAt: string
}

type Side = ChatMessage['sender']

const timeFormat = new Intl.DateTimeFormat('en-GH', { hour: 'numeric', minute: '2-digit' })
const dayFormat = new Intl.DateTimeFormat('en-GH', { weekday: 'long', day: 'numeric', month: 'long' })

function dayLabel(iso: string) {
  const date = new Date(iso)
  const today = new Date()
  const yesterday = new Date(today)
  yesterday.setDate(today.getDate() - 1)
  if (date.toDateString() === today.toDateString()) return 'Today'
  if (date.toDateString() === yesterday.toDateString()) return 'Yesterday'
  return dayFormat.format(date)
}

// Keeps a thread fresh: polls `fetchNewer(lastId)` while the tab is visible and
// merges whatever comes back. Read receipts on your own messages are refreshed
// by `fetchAll`, which runs less often.
export function useChatThread(
  initial: ChatMessage[],
  fetchNewer: (afterId: number) => Promise<ChatMessage[] | null>,
  fetchAll: () => Promise<ChatMessage[] | null>,
) {
  const [messages, setMessages] = useState(initial)
  const latest = useRef({ fetchNewer, fetchAll, lastId: initial.at(-1)?.id ?? 0 })

  useEffect(() => {
    latest.current = { fetchNewer, fetchAll, lastId: messages.at(-1)?.id ?? 0 }
  })

  useEffect(() => {
    let tick = 0
    let busy = false
    const timer = window.setInterval(async () => {
      if (busy || document.visibilityState !== 'visible') return
      busy = true
      tick++
      try {
        if (tick % 6 === 0) {
          const all = await latest.current.fetchAll()
          if (all) setMessages(all)
        } else {
          const newer = await latest.current.fetchNewer(latest.current.lastId)
          if (newer?.length) setMessages((list) => merge(list, newer))
        }
      } catch {
        // Network hiccup: try again on the next tick.
      } finally {
        busy = false
      }
    }, CHAT_POLL_MS)
    return () => window.clearInterval(timer)
  }, [])

  return {
    messages,
    add: (message: ChatMessage) => setMessages((list) => merge(list, [message])),
    replace: setMessages,
  }
}

function merge(list: ChatMessage[], incoming: ChatMessage[]) {
  const byId = new Map(list.map((m) => [m.id, m]))
  for (const m of incoming) byId.set(m.id, m)
  return [...byId.values()].sort((a, b) => a.id - b.id)
}

export function ChatThread({
  messages,
  me,
  otherName,
  emptyText,
  onSend,
  placeholder = 'Write a message…',
  className,
}: {
  messages: ChatMessage[]
  me: Side
  otherName: string
  emptyText: string
  onSend: (body: string) => Promise<void>
  placeholder?: string
  className?: string
}) {
  const [draft, setDraft] = useState('')
  const [sending, setSending] = useState(false)
  const scroller = useRef<HTMLDivElement>(null)
  const lastId = messages.at(-1)?.id

  useLayoutEffect(() => {
    const el = scroller.current
    if (el) el.scrollTop = el.scrollHeight
  }, [lastId])

  async function submit(event?: FormEvent) {
    event?.preventDefault()
    const body = draft.trim()
    if (!body || sending) return
    setSending(true)
    try {
      await onSend(body)
      setDraft('')
    } catch (error) {
      toast.error(error instanceof Error ? error.message : 'Your message was not sent. Please try again.')
    } finally {
      setSending(false)
    }
  }

  function onKeyDown(event: KeyboardEvent<HTMLTextAreaElement>) {
    if (event.key === 'Enter' && !event.shiftKey && !event.nativeEvent.isComposing) {
      event.preventDefault()
      void submit()
    }
  }

  return (
    <div className={cn('flex min-h-0 flex-col', className)}>
      <div
        ref={scroller}
        role="log"
        aria-live="polite"
        aria-label={`Conversation with ${otherName}`}
        className="dot-grid min-h-0 flex-1 overflow-y-auto px-4 py-5 sm:px-6"
      >
        {messages.length === 0 ? (
          <p className="mx-auto mt-10 max-w-xs text-center text-sm text-muted-foreground">{emptyText}</p>
        ) : (
          <ol className="grid gap-1.5">
            {messages.map((m, i) => {
              const mine = m.sender === me
              const prev = messages[i - 1]
              const newDay = !prev || new Date(prev.createdAt).toDateString() !== new Date(m.createdAt).toDateString()
              const grouped = !newDay && prev?.sender === m.sender
              return (
                <li key={m.id} className="grid">
                  {newDay && (
                    <p className="my-3 justify-self-center rounded-full bg-background/90 px-3 py-1 text-[11px] font-semibold tracking-wider text-muted-foreground uppercase shadow-sm ring-1 ring-border" suppressHydrationWarning>
                      {dayLabel(m.createdAt)}
                    </p>
                  )}
                  <div className={cn('flex max-w-[85%] flex-col sm:max-w-[70%]', mine ? 'items-end justify-self-end' : 'items-start justify-self-start', !grouped && 'mt-2')}>
                    {!grouped && !mine && (
                      <span className="mb-1 px-1 text-xs font-medium text-muted-foreground">
                        {m.sender === 'admin' ? (m.adminEmail ?? otherName) : otherName}
                      </span>
                    )}
                    {!grouped && mine && me === 'admin' && m.adminEmail && (
                      <span className="mb-1 px-1 text-xs font-medium text-muted-foreground">{m.adminEmail}</span>
                    )}
                    <div
                      className={cn(
                        'rounded-2xl px-4 py-2.5 text-[0.95rem] leading-relaxed break-words whitespace-pre-wrap shadow-sm',
                        mine
                          ? 'rounded-br-md bg-primary text-primary-foreground'
                          : 'rounded-bl-md border bg-card text-card-foreground',
                      )}
                    >
                      {m.body}
                    </div>
                    <span className="mt-1 flex items-center gap-1 px-1 text-[11px] text-muted-foreground" suppressHydrationWarning>
                      <time dateTime={m.createdAt}>{timeFormat.format(new Date(m.createdAt))}</time>
                      {mine &&
                        (m.readAt ? (
                          <CheckCheck className="size-3.5 text-primary" aria-label="Seen" />
                        ) : (
                          <Check className="size-3.5" aria-label="Sent" />
                        ))}
                    </span>
                  </div>
                </li>
              )
            })}
          </ol>
        )}
      </div>

      <form onSubmit={submit} className="flex items-end gap-2 border-t bg-card p-3 sm:p-4">
        <label htmlFor={`chat-input-${me}`} className="sr-only">
          Message
        </label>
        <Textarea
          id={`chat-input-${me}`}
          value={draft}
          onChange={(e) => setDraft(e.target.value)}
          onKeyDown={onKeyDown}
          placeholder={placeholder}
          maxLength={CHAT_MAX_LENGTH}
          rows={1}
          className="max-h-40 min-h-11 flex-1 resize-none rounded-2xl"
        />
        <Button type="submit" size="icon" className="size-11 shrink-0 rounded-full" disabled={!draft.trim() || sending}>
          {sending ? <Loader2 className="animate-spin" /> : <SendHorizontal />}
          <span className="sr-only">Send</span>
        </Button>
      </form>
    </div>
  )
}
