"use client"

import { FC, PropsWithChildren, useEffect, useState } from "react"
import { CloudOff, Info, Loader2, RotateCw, WifiOff } from "lucide-react"
import Link from "@/components/common/versioned-link"
import { useOnline } from "@/hooks/use-online"
import { useAuth } from "@/lib/provider/auth.provider"
import { cn } from "@/lib/utils"

interface ErrorBoxProps {
  title: string
  description?: string | null
  showRetry?: boolean
  onRetry?: () => unknown
  active?: boolean
}

type Tone = "offline" | "error" | "notice"

const TONES: Record<Tone, { soft: string; ink: string; Icon: typeof Info }> = {
  offline: { soft: "bg-ochre-soft", ink: "text-ochre-ink", Icon: WifiOff },
  error: { soft: "bg-rose-soft", ink: "text-rose", Icon: CloudOff },
  notice: { soft: "bg-paper-2", ink: "text-ink-soft", Icon: Info },
}

const ErrorBox: FC<PropsWithChildren<ErrorBoxProps>> = ({
  title,
  description,
  showRetry = false,
  onRetry,
  active = false,
  children,
}) => {
  const online = useOnline()
  const { state: signedIn } = useAuth()
  const [retrying, setRetrying] = useState(false)
  const canRetry = showRetry && !!onRetry

  const retry = () => {
    if (!onRetry || retrying) return
    setRetrying(true)
    // Keep the spinner long enough to be seen, and until the load settles.
    Promise.all([Promise.resolve(onRetry()), new Promise((r) => setTimeout(r, 600))])
      .catch(() => undefined)
      .finally(() => setRetrying(false))
  }

  // Back online: retry without waiting for a tap.
  useEffect(() => {
    if (!active || !canRetry) return
    const again = () => onRetry?.()
    window.addEventListener("online", again)
    return () => window.removeEventListener("online", again)
  }, [active, canRetry, onRetry])

  if (!active) return <>{children}</>

  const tone: Tone = !canRetry ? "notice" : online ? "error" : "offline"
  const { soft, ink, Icon } = TONES[tone]
  const heading = tone === "offline" ? "اینترنت وصل نیست" : title
  const text = tone === "offline" ? "اتصالت که برگردد، خودمان دوباره تلاش می‌کنیم." : description

  return (
    <div role="alert" className="w-full max-w-sm mx-auto flex flex-col items-center text-center px-6 py-10 select-text">
      <span className="relative w-24 h-24 grid place-items-center" aria-hidden="true">
        <span className={cn("absolute inset-0 rounded-full opacity-50", soft)} />
        <span className={cn("absolute inset-3 rounded-full", soft)} />
        <span className={cn("relative w-12 h-12 rounded-2xl bg-canvas shadow-card grid place-items-center", ink)}>
          <Icon className="w-6 h-6" strokeWidth={2} />
        </span>
      </span>

      <h2 className="mt-4 text-title-3 font-extrabold text-ink">{heading}</h2>
      {text && <p className="mt-1.5 max-w-[270px] text-body-sm text-ink-soft">{text}</p>}

      {canRetry && (
        <button
          type="button"
          onClick={retry}
          disabled={retrying}
          className="mt-6 h-11 min-w-[168px] px-6 rounded-2xl bg-sienna text-canvas text-body font-bold flex items-center justify-center gap-2 shadow-card active:scale-[.98] transition disabled:opacity-80"
        >
          {retrying ? (
            <Loader2 className="w-4 h-4 animate-spin" aria-hidden="true" />
          ) : (
            <RotateCw className="w-4 h-4" aria-hidden="true" />
          )}
          {retrying ? "در حال تلاش…" : "تلاش دوباره"}
        </button>
      )}

      {tone === "error" && signedIn && (
        <Link href="/ticket" className="mt-3 text-caption text-ink-soft">
          مشکل ادامه دارد؟ <span className="font-bold text-sienna">به پشتیبانی بگو</span>
        </Link>
      )}
    </div>
  )
}

export default ErrorBox
