"use client"

import { useCallback, useEffect, useState } from "react"
import { MessagesSquare } from "lucide-react"

import Loading from "@/components/common/loading.component"
import ErrorBox from "@/components/common/error-box.component"
import EmptyState from "@/components/common/empty-state.component"
import Link from "@/components/common/versioned-link"
import CoachAvatar from "@/components/catalogue/coach-avatar.component"
import { Button } from "@/components/ui/button"

import { CHATS_CHANGED_EVENT } from "@/hooks/use-chat-unread"
import { ChatListItemDto } from "@/lib/dto/chat.dto"
import { PaginationMetaDto } from "@/lib/dto/pagination-meta.dto"
import { chatListTime, unreadLabel } from "@/lib/helpers/chat.helper"
import { ApiEndpoint } from "@/lib/services/api.service"
import { getApiErrorMessage, useApi } from "@/lib/services/axios.service"
import { cn } from "@/lib/utils"

const REFRESH_MS = 30_000

export default function ChatsView() {
  const [items, setItems] = useState<ChatListItemDto[]>([])
  const [meta, setMeta] = useState<PaginationMetaDto | null>(null)
  const [loadError, setLoadError] = useState<string | null>(null)
  const [loaded, setLoaded] = useState(false)
  const [{ loading }, fetchList] = useApi<ChatListItemDto[]>({ url: ApiEndpoint("chat", "list"), method: "GET" })

  const load = useCallback((page: number) => {
    return fetchList({ params: { page } }).then(
      (response) => {
        const data = response?.body?.data ?? []
        setItems((previous) => (page === 1 ? data : [...previous, ...data]))
        setMeta(response?.body?.meta ?? null)
        setLoadError(null)
        setLoaded(true)
      },
      (err: unknown) => {
        setLoadError(getApiErrorMessage(err))
        setLoaded(true)
      },
    )
  }, [fetchList])

  // First page now, then quietly again while the list is open and when coming back to it.
  useEffect(() => {
    load(1)
    const refresh = () => {
      if (document.visibilityState === "visible") load(1)
    }
    const timer = setInterval(refresh, REFRESH_MS)
    document.addEventListener("visibilitychange", refresh)
    window.addEventListener(CHATS_CHANGED_EVENT, refresh)
    return () => {
      clearInterval(timer)
      document.removeEventListener("visibilitychange", refresh)
      window.removeEventListener(CHATS_CHANGED_EVENT, refresh)
    }
  }, [load])

  return (
    <div className="flex-1 overflow-y-auto bg-background">
      <Loading loading={!loaded}>
        <ErrorBox active={!!loadError} title="خطا در بارگذاری" description={loadError} showRetry onRetry={() => load(1)}>
          {items.length === 0 ? (
            <div className="pt-10">
              <EmptyState
                icon={<MessagesSquare className="w-8 h-8" />}
                title="هنوز گفتگویی نداری"
                description="از صفحه‌ی هر دوره‌ای که داری، «پیام به مربی» را بزن تا سؤالت را مستقیم از مربی بپرسی."
              />
            </div>
          ) : (
            <ul className="divide-y divide-line" aria-label="گفتگوها">
              {items.map((chat) => (
                <li key={chat.id}>
                  <Link href={`/chats/view?id=${chat.id}`} className="flex items-center gap-3 px-4 py-3 active:bg-paper-2">
                    <span className="relative">
                      <CoachAvatar src={chat.coach.avatar} name={chat.coach.name} className="w-12 h-12 text-title-3" />
                    </span>
                    <span className="flex-1 min-w-0">
                      <span className="flex items-center justify-between gap-2">
                        <span className="font-bold text-body truncate">{chat.coach.name ?? "مربی"}</span>
                        <span className={cn("text-micro shrink-0", chat.unread_count > 0 ? "text-sienna font-bold" : "text-ink-soft")}>
                          {chatListTime(chat.last_message?.at ?? null)}
                        </span>
                      </span>
                      <span className="flex items-center justify-between gap-2 mt-0.5">
                        <span className={cn("text-body-sm truncate", chat.unread_count > 0 ? "text-ink font-semibold" : "text-ink-soft")}>
                          {chat.last_message?.mine && <span className="text-ink-soft">تو: </span>}
                          {chat.last_message?.role === "admin" && <span className="text-ochre-ink">رنگوک: </span>}
                          {chat.last_message?.preview ?? ""}
                        </span>
                        {chat.unread_count > 0 && (
                          <span className="min-w-5 h-5 px-1.5 rounded-full bg-sienna text-canvas text-micro font-bold grid place-items-center shrink-0 tabular-nums"
                                aria-label={`${chat.unread_count} پیام خوانده‌نشده`}>
                            {unreadLabel(chat.unread_count)}
                          </span>
                        )}
                      </span>
                      {chat.read_only && <span className="text-micro text-ink-soft">فقط خواندنی</span>}
                    </span>
                  </Link>
                </li>
              ))}
            </ul>
          )}

          {meta && meta.current_page < meta.last_page && (
            <div className="p-4 flex justify-center">
              <Button variant="outline" disabled={loading} onClick={() => load(meta.current_page + 1)}>بیشتر</Button>
            </div>
          )}
        </ErrorBox>
      </Loading>
    </div>
  )
}
