"use client"

import { useCallback, useEffect, useRef, useState } from "react"
import { useSearchParams } from "next/navigation"
import { Search, SearchX } from "lucide-react"

import ErrorBox from "@/components/common/error-box.component"
import Loading from "@/components/common/loading.component"
import EmptyState from "@/components/common/empty-state.component"
import SectionHeader from "@/components/common/section-header.component"
import CourseRow from "@/components/catalogue/course-row.component"
import CoachCard from "@/components/catalogue/coach-card.component"
import PaginationControl from "@/components/common/pagination-control.component"

import { ApiEndpoint } from "@/lib/services/api.service"
import { getApiErrorMessage, useApi } from "@/lib/services/axios.service"
import { CategoryDto, CoachCardDto, CourseCardDto } from "@/lib/dto/catalogue.dto"
import { PaginationMetaDto } from "@/lib/dto/pagination-meta.dto"
import { cn } from "@/lib/utils"
import { faNumber } from "@/lib/helpers/format.helper"

const SEARCH_DELAY_MS = 350
/** Courses per page (the API caps it at 30). */
const PER_PAGE = 10

/** Explore (DESIGN.md §17): search, category chips, the matching coaches and courses. */
export default function ExploreView() {
  const initialCategory = useSearchParams().get("category")

  const [categories, setCategories] = useState<CategoryDto[]>([])
  const [category, setCategory] = useState<string | null>(initialCategory)
  const [query, setQuery] = useState("")
  const [search, setSearch] = useState("")

  const [coaches, setCoaches] = useState<CoachCardDto[]>([])
  const [courses, setCourses] = useState<CourseCardDto[]>([])
  const [meta, setMeta] = useState<PaginationMetaDto | null>(null)
  const [loadError, setLoadError] = useState<string | null>(null)
  const [loaded, setLoaded] = useState(false)
  const [page, setPage] = useState(1)
  const coursesRef = useRef<HTMLElement | null>(null)

  const [, fetchCategories] = useApi<CategoryDto[]>({ url: ApiEndpoint("catalogue", "categories"), method: "GET", useCache: true, cacheTTL: 60000 })
  const [, fetchCoaches] = useApi<CoachCardDto[]>({ url: ApiEndpoint("catalogue", "coaches"), method: "GET" })
  const [, fetchCourses] = useApi<CourseCardDto[]>({ url: ApiEndpoint("catalogue", "courses"), method: "GET" })

  // Only the newest request may update the lists (an older filter can answer last).
  const latestRequest = useRef(0)

  // Typing settles before searching.
  useEffect(() => {
    const timer = setTimeout(() => {
      setSearch(query.trim())
      setPage(1)
    }, SEARCH_DELAY_MS)
    return () => clearTimeout(timer)
  }, [query])

  const loadCategories = useCallback(() => {
    fetchCategories().then(
      (response) => {
        const list = response?.body?.data ?? []
        setCategories(list)
        // A link to a category that no longer exists (an old shared link) shows everything.
        setCategory((current) => (current && list.length > 0 && !list.some((c) => c.key === current) ? null : current))
      },
      () => setCategories([]),
    )
  }, [fetchCategories])

  useEffect(() => {
    loadCategories()
  }, [loadCategories])

  const load = useCallback((pageNumber: number) => {
    const params = { category: category ?? undefined, q: search || undefined }
    const requestId = ++latestRequest.current
    const current = () => requestId === latestRequest.current

    // Coaches only change with the filters, not with the page.
    const coachesRequest = pageNumber === 1
      ? fetchCoaches({ params }).then((response) => {
        if (current()) setCoaches(response?.body?.data ?? [])
      })
      : Promise.resolve()

    const coursesRequest = fetchCourses({ params: { ...params, page: pageNumber, per_page: PER_PAGE } }).then((response) => {
      const result = response?.body
      if (!result?.ok) throw new Error("خطا در دریافت دوره‌ها")
      if (!current()) return
      setCourses(result.data ?? [])
      setMeta(result.meta ?? null)
    })

    return Promise.all([coachesRequest, coursesRequest]).then(
      () => {
        if (!current()) return
        setLoadError(null)
        setLoaded(true)
      },
      (err: unknown) => {
        if (!current()) return
        setLoadError(getApiErrorMessage(err))
        setLoaded(true)
      },
    )
  }, [category, search, fetchCoaches, fetchCourses])

  useEffect(() => {
    load(page)
  }, [load, page])

  const retry = useCallback(() => {
    if (categories.length === 0) loadCategories()
    load(page)
  }, [categories.length, loadCategories, load, page])

  function changePage(next: number) {
    setPage(next)
    coursesRef.current?.scrollIntoView({ behavior: "smooth", block: "start" })
  }

  const chips: { key: string | null; title: string }[] = [{ key: null, title: "همه" }, ...categories.map((c) => ({ key: c.key, title: c.title }))]

  return (
    <div className="flex flex-col flex-1 bg-background text-right min-h-full">
      <div className="flex-1 overflow-y-auto px-4 pt-4 pb-6">
        <h1 className="text-title-1 font-extrabold">کاوش</h1>

        <label className="mt-3 flex items-center h-12 px-3.5 rounded-2xl bg-canvas border border-line focus-within:border-sienna">
          <Search className="w-5 h-5 text-ink-soft shrink-0" aria-hidden="true" />
          <input
            type="search"
            value={query}
            onChange={(e) => setQuery(e.target.value)}
            placeholder="مربی، دوره یا تکنیک…"
            aria-label="جست‌وجو"
            className="flex-1 bg-transparent outline-none text-body mr-2"
          />
        </label>

        <div className="flex overflow-x-auto no-scrollbar -mx-4 px-4 mt-3 pb-1 [&>*:not(:last-child)]:ml-2" role="tablist" aria-label="دسته‌ها">
          {chips.map((chip) => {
            const on = chip.key === category
            return (
              <button
                key={chip.key ?? "all"}
                type="button"
                role="tab"
                aria-selected={on}
                onClick={() => {
                  setCategory(chip.key)
                  setPage(1)
                }}
                className={cn(
                  "h-9 px-4 rounded-full text-body-sm font-bold whitespace-nowrap border transition-colors",
                  on ? "bg-ink text-canvas border-ink" : "bg-canvas text-ink-soft border-line"
                )}
              >
                {chip.title}
              </button>
            )
          })}
        </div>

        <Loading loading={!loaded}>
          <ErrorBox active={!!loadError} title="خطا در بارگذاری" description={loadError} showRetry onRetry={retry}>
            {coaches.length > 0 && (
              <section className="mt-5">
                <SectionHeader title="مربی‌ها" />
                <div className="flex overflow-x-auto no-scrollbar -mx-4 px-4 pb-1 [&>*:not(:last-child)]:ml-3">
                  {coaches.map((coach) => <CoachCard key={coach.slug} coach={coach} />)}
                </div>
              </section>
            )}

            <section className="mt-5 scroll-mt-4" ref={coursesRef}>
              <SectionHeader title={meta && meta.total > 0 ? `دوره‌ها (${faNumber(meta.total)})` : "دوره‌ها"} />
              {courses.length === 0 ? (
                <EmptyState
                  icon={<SearchX className="w-8 h-8" />}
                  title="چیزی پیدا نشد"
                  description="عبارت یا دسته‌ی دیگری را امتحان کن."
                />
              ) : (
                <div className="flex flex-col [&>*:not(:last-child)]:mb-2.5">
                  {courses.map((course) => <CourseRow key={course.id} course={course} />)}
                </div>
              )}

              {meta && meta.last_page > 1 && (
                <div className="mt-4">
                  <PaginationControl meta={meta} onChange={changePage} />
                </div>
              )}
            </section>
          </ErrorBox>
        </Loading>
      </div>
    </div>
  )
}
