"use client"

import { useCallback, useEffect, useState } from "react"
import { useSearchParams } from "next/navigation"
import { BadgeCheck, Brush, Clapperboard, MessageCircle } 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 SafeImage from "@/components/common/safe-img"
import SectionHeader from "@/components/common/section-header.component"
import CoachAvatar from "@/components/catalogue/coach-avatar.component"
import CourseRow from "@/components/catalogue/course-row.component"
import SubmissionSheet from "@/components/submission/submission-sheet.component"
import { Button } from "@/components/ui/button"

import { useOpenChat } from "@/hooks/use-open-chat"
import { ApiEndpoint } from "@/lib/services/api.service"
import { getApiErrorMessage, useApi } from "@/lib/services/axios.service"
import { CoachProfileDto } from "@/lib/dto/catalogue.dto"
import { faNumber, toman } from "@/lib/helpers/format.helper"

/** A coach's public profile (/coach/view?slug=): who they are, a paid critique, their courses. */
export default function CoachView() {
  const slug = (useSearchParams().get("slug") ?? "").trim()

  return slug ? <CoachProfile key={slug} slug={slug} /> : null
}

function CoachProfile({ slug }: { slug: string }) {
  const [coach, setCoach] = useState<CoachProfileDto | null>(null)
  const [loadError, setLoadError] = useState<string | null>(null)
  const [critiqueOpen, setCritiqueOpen] = useState(false)
  const { open: openChat, opening } = useOpenChat()

  const [{ loading }, fetchCoach] = useApi<CoachProfileDto>({
    url: ApiEndpoint("catalogue", "coach", { slug: encodeURIComponent(slug) }),
    method: "GET",
  })

  const load = useCallback(() => {
    return fetchCoach().then(
      (response) => {
        const result = response?.body
        if (!result?.ok) {
          setLoadError("خطا در دریافت پروفایل مربی")
          return
        }
        setLoadError(null)
        setCoach(result.data)
      },
      (err: unknown) => setLoadError(getApiErrorMessage(err)),
    )
  }, [fetchCoach])

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

  return (
    <div className="flex flex-col flex-1 bg-background min-h-0">
      <div className="flex-1 overflow-y-auto min-h-0 pb-8">
        <Loading loading={loading && !coach}>
          <ErrorBox active={!!loadError} title="خطا در بارگذاری" description={loadError} showRetry onRetry={load}>
            {coach && (
              <>
                <div className="relative h-40 mx-4 mt-3 rounded-3xl overflow-hidden bg-sienna-soft">
                  <SafeImage src={coach.cover} />
                </div>

                <div className="px-4 -mt-12 relative text-center">
                  <CoachAvatar src={coach.avatar} name={coach.name} className="w-24 h-24 mx-auto ring-4 ring-background shadow-raised text-display" />
                  <h1 className="text-title-1 font-extrabold mt-2 flex items-center justify-center gap-1">
                    {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>}

                  <div className="grid grid-cols-2 gap-2 mt-4">
                    <Stat value={faNumber(coach.courses_count)} label="دوره" />
                    <Stat value={faNumber(coach.learners_count)} label="هنرجو" />
                  </div>

                  {(coach.critique_price !== null || coach.can_message) && (
                    <div className="flex gap-2 mt-3">
                      {coach.can_message && (
                        <Button size="lg" variant={coach.critique_price !== null ? "outline" : "default"} className="flex-1 h-12 rounded-2xl"
                                disabled={opening} onClick={() => openChat({ coachSlug: coach.slug })}>
                          <MessageCircle className="w-4 h-4" />
                          پیام به مربی
                        </Button>
                      )}
                      {coach.critique_price !== null && (
                        <Button size="lg" className="flex-1 h-12 rounded-2xl" onClick={() => setCritiqueOpen(true)}>
                          <Brush className="w-4 h-4" />
                          نقد ویژه · {toman(coach.critique_price)}
                        </Button>
                      )}
                    </div>
                  )}

                  {!coach.can_message && coach.courses.length > 0 && (
                    <p className="flex items-center justify-center gap-1.5 text-caption text-ink-soft mt-3">
                      <MessageCircle className="w-4 h-4 shrink-0" aria-hidden="true" />
                      پیام مستقیم به مربی بعد از خرید یکی از دوره‌هایش باز می‌شود.
                    </p>
                  )}

                  {coach.bio && (
                    <p className="text-body leading-7 text-ink/85 mt-4 text-right whitespace-pre-line">{coach.bio}</p>
                  )}
                </div>

                <section className="px-4 mt-6">
                  <SectionHeader title={`دوره‌ها (${faNumber(coach.courses.length)})`} />
                  {coach.courses.length === 0 ? (
                    <EmptyState
                      icon={<Clapperboard className="w-8 h-8" />}
                      title="هنوز دوره‌ای منتشر نشده"
                      description="دوره‌های این مربی به‌زودی اینجا می‌آیند."
                    />
                  ) : (
                    <div className="flex flex-col [&>*:not(:last-child)]:mb-2.5">
                      {coach.courses.map((course) => <CourseRow key={course.id} course={course} />)}
                    </div>
                  )}
                </section>

                {coach.critique_price !== null && (
                  <SubmissionSheet
                    open={critiqueOpen}
                    onOpenChange={setCritiqueOpen}
                    kind="critique"
                    coach={{ slug: coach.slug, name: coach.name, critique_price: coach.critique_price }}
                    context={coach.name}
                  />
                )}
              </>
            )}
          </ErrorBox>
        </Loading>
      </div>
    </div>
  )
}

function Stat({ value, label }: { value: string; label: string }) {
  return (
    <div className="bg-canvas border border-line rounded-2xl py-2.5">
      <b className="block text-title-3 font-extrabold">{value}</b>
      <span className="text-micro text-ink-soft">{label}</span>
    </div>
  )
}
