"use client"

import { useEffect, useState } from "react"
import { useSearchParams } from "next/navigation"
import { BadgeCheck, BookOpen, Brush, LogIn, UserX } from "lucide-react"

import Loading from "@/components/common/loading.component"
import ErrorBox from "@/components/common/error-box.component"
import CoachAvatar from "@/components/catalogue/coach-avatar.component"
import SafeImage from "@/components/common/safe-img"
import { Button } from "@/components/ui/button"

import { useVersionedRouter } from "@/hooks/use-versioned-router"
import { useAuth } from "@/lib/provider/auth.provider"
import { ApiEndpoint } from "@/lib/services/api.service"
import { getApiErrorMessage, isConnectionError, useApi } from "@/lib/services/axios.service"
import { CoachProfileDto } from "@/lib/dto/catalogue.dto"
import { faNumber, toman } from "@/lib/helpers/format.helper"

/** A visit counts once per browser session per invite: invite → the coach's slug it named. */
const VISITED_KEY = "rangook-invite-visited"

function visitedSlug(ref: string): string | null {
  try {
    const seen: Record<string, string> = JSON.parse(window.sessionStorage.getItem(VISITED_KEY) ?? "{}")
    return typeof seen[ref] === "string" ? seen[ref] : null
  } catch {
    return null
  }
}

function rememberVisit(ref: string, slug: string): void {
  try {
    const seen: Record<string, string> = JSON.parse(window.sessionStorage.getItem(VISITED_KEY) ?? "{}")
    window.sessionStorage.setItem(VISITED_KEY, JSON.stringify({ ...seen, [ref]: slug }))
  } catch {
    // Storage off: the next visit counts again.
  }
}

/** The coach's invite landing (technical-plan 4.7, §7): rangook.ir/marjan → /c/?slug=marjan. */
export default function InviteView() {
  const ref = (useSearchParams().get("slug") ?? "").trim()

  return ref ? <InviteLanding key={ref} inviteRef={ref} /> : <InvalidInvite />
}

function InviteLanding({ inviteRef }: { inviteRef: string }) {
  const router = useVersionedRouter()
  const { state: signedIn } = useAuth()
  const [coach, setCoach] = useState<CoachProfileDto | null>(null)
  const [invalid, setInvalid] = useState(false)
  // No answer (offline, timeout) is not an invalid invite: offer a retry instead.
  const [loadError, setLoadError] = useState<string | null>(null)
  const [attempt, setAttempt] = useState(0)

  const [, postVisit] = useApi<{ coach_slug: string }>({
    url: ApiEndpoint("referral", "visit", { ref: encodeURIComponent(inviteRef) }),
    method: "POST",
  })
  const [, fetchCoach] = useApi<CoachProfileDto>({ method: "GET" })

  useEffect(() => {
    // The visit names the coach (the invite may be their code, e.g.
    const known = visitedSlug(inviteRef)
    const visit = known
      ? Promise.resolve(known)
      : postVisit().then((response) => {
        const slug = response?.body?.data?.coach_slug ?? null
        if (slug) rememberVisit(inviteRef, slug)
        return slug
      })

    visit
      .then((slug) => {
        if (!slug) throw new Error("no coach")
        return fetchCoach({ url: ApiEndpoint("catalogue", "coach", { slug: encodeURIComponent(slug) }) })
      })
      .then(
        (response) => {
          if (response?.body?.ok) setCoach(response.body.data)
          else setInvalid(true)
        },
        (err: unknown) => {
          if (isConnectionError(err)) setLoadError(getApiErrorMessage(err))
          else setInvalid(true)
        },
      )
  }, [inviteRef, postVisit, fetchCoach, attempt])

  const retry = () => {
    setLoadError(null)
    setAttempt((n) => n + 1)
  }

  if (invalid) return <InvalidInvite />

  const firstName = coach?.name.split(" ")[0] ?? ""

  return (
    <div className="flex flex-col flex-1 min-h-0 bg-background">
      <div className="flex-1 overflow-y-auto px-5 pt-6 pb-8 text-center">
        <p className="font-brand text-display text-ink leading-[1.8]">رنگوک</p>
        <p className="text-caption text-ink-soft -mt-1">باشگاه تمرین هنر</p>

        <ErrorBox active={!!loadError} title="خطا در بارگذاری" description={loadError} showRetry onRetry={retry}>
        <Loading loading={!coach}>
          {coach && (
            <>
              <div className="relative mt-5 rounded-hero overflow-hidden bg-canvas border border-line shadow-card pb-5">
                <div className="relative h-28 bg-sienna-soft">
                  <SafeImage src={coach.cover} />
                </div>
                <CoachAvatar src={coach.avatar} name={coach.name} className="w-24 h-24 mx-auto -mt-12 relative ring-4 ring-canvas text-display" />
                <h1 className="text-title-1 font-extrabold mt-2 flex items-center justify-center gap-1 px-4">
                  {coach.name}
                  {coach.verified && <BadgeCheck className="w-5 h-5 text-ultra" aria-label="تأییدشده" />}
                </h1>
                {coach.field && <p className="text-body text-ink-soft">{coach.field}</p>}
                <p className="text-title-3 font-extrabold text-sienna mt-3 px-4">{firstName} تو را به رنگوک دعوت کرده</p>
                {coach.bio && <p className="text-body-sm leading-6 text-ink/85 mt-2 px-5 line-clamp-4">{coach.bio}</p>}
              </div>

              <div className="grid grid-cols-3 gap-2 mt-4">
                {[
                  [<BookOpen key="b" className="w-4 h-4 text-sienna" />, "دوره‌های ویدیویی"],
                  [<Brush key="r" className="w-4 h-4 text-sienna" />, "نقد کارت روی خود نقاشی"],
                  [<LogIn key="l" className="w-4 h-4 text-sienna" />, "ورود با شماره موبایل"],
                ].map(([icon, label], i) => (
                  <div key={i} className="bg-canvas border border-line rounded-2xl py-3 px-1 flex flex-col items-center">
                    {icon}
                    <span className="text-micro font-bold mt-1.5 leading-4">{label}</span>
                  </div>
                ))}
              </div>

              {coach.courses.length > 0 && (
                <div className="mt-5 text-right">
                  <h2 className="text-title-3 font-extrabold mb-2.5">دوره‌های {firstName}</h2>
                  <div className="flex flex-col [&>*:not(:last-child)]:mb-2">
                    {coach.courses.map((course) => (
                      <div key={course.id} className="flex items-center bg-canvas border border-line rounded-2xl p-2.5">
                        <span className="relative w-16 h-14 rounded-xl overflow-hidden bg-paper-2 shrink-0">
                          <SafeImage src={course.cover} />
                        </span>
                        <span className="flex-1 min-w-0 mr-3">
                          <span className="block text-body font-bold truncate">{course.title}</span>
                          <span className="block text-caption text-ink-soft">
                            {course.lessons_count ? `${faNumber(course.lessons_count)} درس · ` : ""}{toman(course.price)}
                          </span>
                        </span>
                      </div>
                    ))}
                  </div>
                </div>
              )}
            </>
          )}
        </Loading>
        </ErrorBox>
      </div>

      {coach && (
        <div className="border-t border-line bg-canvas p-4 pb-[max(16px,env(safe-area-inset-bottom))]">
          {signedIn ? (
            <Button size="lg" className="w-full h-[52px] rounded-2xl" onClick={() => router.push(`/coach/view?slug=${encodeURIComponent(coach.slug)}`)}>
              دیدن دوره‌های {firstName}
            </Button>
          ) : (
            <Button size="lg" className="w-full h-[52px] rounded-2xl" onClick={() => router.push("/auth/login")}>
              <LogIn className="w-4 h-4" />
              ورود و شروع تمرین
            </Button>
          )}
        </div>
      )}
    </div>
  )
}

function InvalidInvite() {
  const router = useVersionedRouter()

  return (
    <div className="flex flex-col flex-1 items-center justify-center text-center px-6 bg-background">
      <span className="w-14 h-14 rounded-full bg-paper-2 grid place-items-center text-ink-soft">
        <UserX className="w-7 h-7" aria-hidden="true" />
      </span>
      <p className="text-title-3 font-extrabold mt-3">این لینک دعوت معتبر نیست</p>
      <p className="text-body text-ink-soft mt-1">می‌توانی بدون دعوت هم وارد رنگوک شوی.</p>
      <Button className="mt-5 h-11 rounded-2xl px-6" onClick={() => router.push("/")}>رفتن به رنگوک</Button>
    </div>
  )
}
