"use client"

import { useCallback, useEffect, useState } from "react"
import { Brush, Flag, Heart, Pencil, Trash2, X } from "lucide-react"

import Loading from "@/components/common/loading.component"
import ErrorBox from "@/components/common/error-box.component"
import Link from "@/components/common/versioned-link"
import { Button } from "@/components/ui/button"
import { Drawer, DrawerContent, DrawerDescription, DrawerHeader, DrawerTitle } from "@/components/ui/drawer"
import { toast } from "@/components/ui/use-toast"

import { useGalleryLike } from "@/hooks/use-gallery-like"
import { useNumberQueryParam } from "@/hooks/useNumberQueryParam"
import { useVersionedRouter } from "@/hooks/use-versioned-router"
import { GalleryCardDto, GalleryPieceDto } from "@/lib/dto/gallery.dto"
import { convertDate } from "@/lib/helpers/date.helper"
import { faNumber } from "@/lib/helpers/format.helper"
import { ApiEndpoint } from "@/lib/services/api.service"
import { getApiErrorMessage, useApi } from "@/lib/services/axios.service"
import { cn } from "@/lib/utils"

const CAPTION_MAX = 300

/** One piece: the photo (tap to zoom), artist, course, caption, the coach's summary, like and report. */
export default function GalleryPieceView() {
  const id = useNumberQueryParam("id")

  return id ? <GalleryPiece key={id} id={id} /> : null
}

function GalleryPiece({ id }: { id: number }) {
  const router = useVersionedRouter()
  const [piece, setPiece] = useState<GalleryPieceDto | null>(null)
  const [loadError, setLoadError] = useState<string | null>(null)
  const [zoom, setZoom] = useState(false)
  const [sheet, setSheet] = useState<"report" | "caption" | "withdraw" | null>(null)
  const [text, setText] = useState("")

  const url = ApiEndpoint("gallery", "show", { id })
  const [{ loading }, fetchPiece] = useApi<GalleryPieceDto>({ url, method: "GET" })
  const [{ loading: saving }, patchPiece] = useApi<GalleryPieceDto>({ url, method: "PATCH" })
  const [{ loading: withdrawing }, deletePiece] = useApi({ url, method: "DELETE" })
  const [{ loading: reporting }, postReport] = useApi({ url: ApiEndpoint("gallery", "report", { id }), method: "POST" })

  const load = useCallback(() => fetchPiece().then(
    (response) => {
      setPiece(response?.body?.data ?? null)
      setLoadError(null)
    },
    (err: unknown) => setLoadError(getApiErrorMessage(err)),
  ), [fetchPiece])

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

  const update = useCallback((_: number, patch: Partial<GalleryCardDto>) => {
    setPiece((p) => (p ? { ...p, ...patch } : p))
  }, [])
  const toggleLike = useGalleryLike(update)

  async function run(action: () => Promise<unknown>, done: string) {
    try {
      await action()
      toast({ title: done, variant: "success" })
      setSheet(null)
    } catch (err) {
      toast({ title: "خطا", description: getApiErrorMessage(err), variant: "error" })
    }
  }

  const src = piece?.image ?? piece?.preview ?? null

  return (
    <div className="flex flex-col flex-1 bg-background min-h-0">
      <div className="flex-1 overflow-y-auto min-h-0">
        <Loading loading={loading && !piece}>
          <ErrorBox active={!!loadError} title="اثر پیدا نشد" description={loadError} showRetry onRetry={load}>
            {piece && (
              <div className="w-full max-w-md mx-auto px-4 pt-4 pb-10 text-right">
                {src && (
                  <button type="button" onClick={() => setZoom(true)} className="block w-full rounded-3xl overflow-hidden bg-paper-2 shadow-card" aria-label="بزرگ‌نمایی عکس">
                    {/* eslint-disable-next-line @next/next/no-img-element */}
                    <img src={src} alt={piece.title} className="w-full max-h-[70vh] object-contain" />
                  </button>
                )}

                {piece.mine && piece.status !== "approved" && (
                  <div className={cn("mt-3 rounded-2xl p-3 text-body-sm leading-7", piece.status === "rejected" ? "bg-rose-soft text-rose" : "bg-ochre-soft text-ochre-ink")}>
                    <b>{piece.status_label}</b>
                    {piece.status === "pending" && " · پس از تأیید رنگوک در گالری دیده می‌شود."}
                    {piece.rejection_reason && <span className="block">{piece.rejection_reason}</span>}
                  </div>
                )}

                <div className="flex items-start justify-between gap-3 mt-4">
                  <div className="min-w-0">
                    <h1 className="text-title-2 font-extrabold leading-tight">{piece.title}</h1>
                    <p className="text-caption text-ink-soft mt-1">
                      {piece.artist}
                      {piece.category ? ` · ${piece.category.title}` : ""}
                      {piece.published_at ? ` · ${convertDate(piece.published_at)}` : ""}
                    </p>
                  </div>
                  <button
                    type="button"
                    onClick={() => toggleLike(piece)}
                    disabled={piece.mine || piece.status !== "approved"}
                    aria-pressed={piece.liked}
                    aria-label={piece.liked ? "برداشتن پسند" : "پسندیدن"}
                    className="flex flex-col items-center shrink-0 text-caption font-bold text-ink-soft disabled:opacity-60 tabular-nums"
                  >
                    <Heart className={cn("w-7 h-7 transition", piece.liked ? "fill-rose text-rose scale-110" : "")} aria-hidden="true" />
                    {faNumber(piece.likes_count)}
                  </button>
                </div>

                {piece.course && (
                  <Link href={`/course/detail?id=${piece.course.id}`} className="inline-flex mt-2 text-caption font-bold text-sienna">
                    از دوره‌ی {piece.course.title} · دیدن دوره
                  </Link>
                )}

                {piece.caption && <p className="text-body leading-7 text-ink/90 mt-3 whitespace-pre-line">{piece.caption}</p>}

                {piece.coach_review && (
                  <div className="mt-4 rounded-2xl bg-ochre-soft/60 border border-line p-3.5">
                    <p className="flex items-center gap-1.5 text-caption font-bold text-ochre-ink">
                      <Brush className="w-4 h-4" aria-hidden="true" />
                      نظر مربی{piece.coach_review.coach ? ` · ${piece.coach_review.coach}` : ""}
                    </p>
                    <p className="text-body-sm leading-7 mt-1 whitespace-pre-line">{piece.coach_review.summary}</p>
                  </div>
                )}

                <div className="flex flex-wrap gap-2 mt-6">
                  {piece.mine ? (
                    <>
                      <Button variant="outline" className="rounded-2xl h-11" onClick={() => { setText(piece.caption ?? ""); setSheet("caption") }}>
                        <Pencil className="w-4 h-4" /> ویرایش توضیح
                      </Button>
                      <Button variant="outline" className="rounded-2xl h-11 text-rose" onClick={() => setSheet("withdraw")}>
                        <Trash2 className="w-4 h-4" /> برداشتن از گالری
                      </Button>
                    </>
                  ) : (
                    <Button variant="ghost" className="rounded-2xl h-11 text-ink-soft" onClick={() => { setText(""); setSheet("report") }}>
                      <Flag className="w-4 h-4" /> گزارش
                    </Button>
                  )}
                </div>
              </div>
            )}
          </ErrorBox>
        </Loading>
      </div>

      {zoom && src && (
        <div role="dialog" aria-modal="true" aria-label="عکس بزرگ" className="fixed inset-0 z-[60] bg-ink/95 grid place-items-center" onClick={() => setZoom(false)}>
          {/* eslint-disable-next-line @next/next/no-img-element */}
          <img src={src} alt={piece?.title ?? ""} className="max-w-full max-h-full object-contain" />
          <button type="button" className="absolute top-[max(16px,env(safe-area-inset-top))] left-4 w-10 h-10 rounded-full bg-canvas/15 text-canvas grid place-items-center" aria-label="بستن">
            <X className="w-5 h-5" />
          </button>
        </div>
      )}

      <Drawer open={sheet !== null} onOpenChange={(open) => !open && setSheet(null)}>
        <DrawerContent className="mx-auto w-full max-w-[480px]">
          <DrawerHeader className="text-right">
            <DrawerTitle className="text-title-3 font-extrabold">
              {sheet === "report" ? "گزارش اثر" : sheet === "caption" ? "توضیح اثر" : "برداشتن از گالری"}
            </DrawerTitle>
            <DrawerDescription>
              {sheet === "report"
                ? "رنگوک گزارش را بررسی می‌کند؛ صاحب اثر نمی‌فهمد چه کسی گزارش داده است."
                : sheet === "caption"
                  ? "چند جمله درباره‌ی این اثر؛ همه می‌بینند."
                  : "اثر فوراً از گالری برداشته می‌شود؛ هر وقت خواستی دوباره به اشتراک بگذار."}
            </DrawerDescription>
          </DrawerHeader>
          <div className="px-4 pb-[max(16px,env(safe-area-inset-bottom))] flex flex-col gap-3">
            {sheet !== "withdraw" && (
              <textarea
                value={text}
                onChange={(e) => setText(e.target.value.slice(0, sheet === "report" ? 500 : CAPTION_MAX))}
                rows={3}
                placeholder={sheet === "report" ? "چه مشکلی دارد؟" : "توضیح (اختیاری)"}
                aria-label={sheet === "report" ? "دلیل گزارش" : "توضیح اثر"}
                className="rounded-2xl border border-line bg-background px-3.5 py-2.5 text-body outline-none focus:border-sienna"
              />
            )}
            {sheet === "report" && (
              <Button size="lg" className="h-12 rounded-2xl" disabled={reporting || text.trim().length < 3}
                      onClick={() => run(() => postReport({ data: { reason: text.trim() } }), "گزارش ثبت شد")}>
                ثبت گزارش
              </Button>
            )}
            {sheet === "caption" && (
              <Button size="lg" className="h-12 rounded-2xl" disabled={saving}
                      onClick={() => run(async () => {
                        const response = await patchPiece({ data: { caption: text.trim() || null } })
                        if (response?.body?.data) setPiece(response.body.data)
                      }, "ذخیره شد")}>
                ذخیره
              </Button>
            )}
            {sheet === "withdraw" && (
              <Button size="lg" variant="destructive" className="h-12 rounded-2xl" disabled={withdrawing}
                      onClick={() => run(async () => { await deletePiece(); router.replace("/gallery/mine") }, "از گالری برداشته شد")}>
                برداشتن از گالری
              </Button>
            )}
          </div>
        </DrawerContent>
      </Drawer>
    </div>
  )
}
