"use client"

import { ChangeEvent, useEffect, useState } from "react"
import { Camera, Flame, Images, Loader2 } from "lucide-react"

import { Drawer, DrawerContent, DrawerDescription, DrawerHeader, DrawerTitle } from "@/components/ui/drawer"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import { Switch } from "@/components/ui/switch"
import { toast } from "@/components/ui/use-toast"

import { ApiEndpoint } from "@/lib/services/api.service"
import { getApiErrorMessage, useApi } from "@/lib/services/axios.service"
import { apiCache } from "@/lib/services/cache.service"
import { CategoryDto } from "@/lib/dto/catalogue.dto"
import { PracticeLoggedDto } from "@/lib/dto/practice.dto"
import { faNumber } from "@/lib/helpers/format.helper"
import { cn } from "@/lib/utils"

const KIDS_CATEGORY = "kids"
const PHOTO_TYPES = ["image/jpeg", "image/png", "image/webp"]
const MAX_PHOTO = 15 * 1024 * 1024
const MINUTES = [10, 20, 30, 45, 60]

/** Fired on window after a practice is saved. */
export const PRACTICE_LOGGED_EVENT = "rangook:practice-logged"

export interface PracticePreset {
  title?: string
  category?: string
  minutes?: number
}

export default function PracticeSheet({
  open,
  onOpenChange,
  preset,
  onLogged,
}: {
  open: boolean
  onOpenChange: (open: boolean) => void
  preset?: PracticePreset | null
  onLogged: (result: PracticeLoggedDto) => void
}) {
  const [file, setFile] = useState<File | null>(null)
  const [preview, setPreview] = useState<string | null>(null)
  const [title, setTitle] = useState("")
  const [category, setCategory] = useState<string | null>(null)
  const [minutes, setMinutes] = useState(20)
  const [note, setNote] = useState("")
  const [isPublic, setIsPublic] = useState(true)
  const [publicTouched, setPublicTouched] = useState(false)
  const [categories, setCategories] = useState<CategoryDto[]>([])

  const [, fetchCategories] = useApi<CategoryDto[]>({ url: ApiEndpoint("catalogue", "categories"), method: "GET", useCache: true, cacheTTL: 300000 })
  const [{ loading }, send] = useApi<PracticeLoggedDto>({ url: ApiEndpoint("practice", "store"), method: "POST", timeout: 70000 })

  useEffect(() => {
    if (!open) return
    fetchCategories().then((response) => setCategories(response?.body?.data ?? []), () => setCategories([]))
  }, [open, fetchCategories])

  // A fresh sheet each time it opens, filled from the exercise when there is one.
  const [openedWith, setOpenedWith] = useState<PracticePreset | null | undefined>(undefined)
  if (open && openedWith !== preset) {
    setOpenedWith(preset)
    setFile(null)
    setPreview(null)
    setTitle(preset?.title ?? "")
    setCategory(preset?.category ?? null)
    setMinutes(preset?.minutes && MINUTES.includes(preset.minutes) ? preset.minutes : 20)
    setNote("")
    setIsPublic(preset?.category !== KIDS_CATEGORY)
    setPublicTouched(false)
  }
  if (!open && openedWith !== undefined) {
    setOpenedWith(undefined)
  }

  useEffect(() => () => {
    if (preview) URL.revokeObjectURL(preview)
  }, [preview])

  function pick(e: ChangeEvent<HTMLInputElement>) {
    const picked = e.target.files?.[0]
    e.target.value = ""
    if (!picked) return

    if (!PHOTO_TYPES.includes(picked.type)) {
      toast({ title: "این فایل تصویر نیست", description: "عکس JPG، PNG یا WebP انتخاب کن.", variant: "error" })
      return
    }
    if (picked.size > MAX_PHOTO) {
      toast({ title: "عکس خیلی بزرگ است", description: "حجم عکس حداکثر ۱۵ مگابایت است.", variant: "error" })
      return
    }

    setFile(picked)
    setPreview(URL.createObjectURL(picked))
  }

  // Kids' art is not shared unless the learner (a parent) turns it on.
  function chooseCategory(key: string | null) {
    setCategory(key)
    if (!publicTouched) setIsPublic(key !== KIDS_CATEGORY)
  }

  async function save() {
    if (loading) return
    if (!file) {
      toast({ title: "یک عکس از تمرینت انتخاب کن", variant: "error" })
      return
    }

    const data = new FormData()
    data.append("photo", file)
    data.append("title", title.trim())
    if (category) data.append("category", category)
    data.append("minutes", String(minutes))
    if (note.trim()) data.append("note", note.trim())
    data.append("is_public", isPublic ? "1" : "0")

    try {
      const response = await send({ data })
      const result = response?.body
      if (!result?.ok) {
        toast({ title: "خطا", description: result?.msg || "ثبت تمرین انجام نشد", variant: "error" })
        return
      }

      // Home and the tab bar read the streak; drop their cached copies.
      apiCache.remove(ApiEndpoint("home", "get"))
      apiCache.remove(ApiEndpoint("practice", "streak"))
      onOpenChange(false)
      onLogged(result.data)
      // The tab bar's centre button turns sage without waiting for a page change.
      window.dispatchEvent(new CustomEvent(PRACTICE_LOGGED_EVENT))
    } catch (err: unknown) {
      toast({ title: "خطا", description: getApiErrorMessage(err), variant: "error" })
    }
  }

  return (
    <Drawer open={open} onOpenChange={onOpenChange}>
      <DrawerContent className="mx-auto w-full max-w-[480px]">
        <div className="overflow-y-auto px-4 pb-4">
          <DrawerHeader className="px-0 text-right">
            <DrawerTitle className="text-title-2 font-extrabold">ثبت تمرین امروز</DrawerTitle>
            <DrawerDescription>یک عکس از کار امروزت؛ کامل یا نیمه‌کاره فرقی ندارد.</DrawerDescription>
          </DrawerHeader>

          <label className="flex flex-col items-center justify-center min-h-32 rounded-2xl border-2 border-dashed border-line bg-canvas p-3 cursor-pointer">
            <input type="file" accept={PHOTO_TYPES.join(",")} className="hidden" onChange={pick} />
            {preview ? (
              // eslint-disable-next-line @next/next/no-img-element
              <img src={preview} alt="عکس تمرین" className="max-h-44 rounded-xl object-contain" />
            ) : (
              <span className="flex flex-col items-center text-ink-soft">
                <Camera className="w-7 h-7" aria-hidden="true" />
                <span className="text-body font-bold text-ink mt-1.5">عکس تمرین</span>
              </span>
            )}
          </label>

          <Input
            className="mt-3"
            value={title}
            maxLength={120}
            onChange={(e) => setTitle(e.target.value)}
            placeholder="چه تمرین کردی؟ (مثلاً: سه لکه‌ی آبرنگی)"
          />

          {categories.length > 0 && (
            <div className="flex overflow-x-auto no-scrollbar -mx-4 px-4 mt-3 [&>*:not(:last-child)]:ml-1.5" role="radiogroup" aria-label="دسته">
              {categories.map((c) => (
                <button
                  key={c.key}
                  type="button"
                  role="radio"
                  aria-checked={category === c.key}
                  onClick={() => chooseCategory(category === c.key ? null : c.key)}
                  className={cn(
                    "h-9 px-3.5 rounded-full text-body-sm font-bold whitespace-nowrap border",
                    category === c.key ? "bg-ink text-canvas border-ink" : "bg-canvas text-ink-soft border-line"
                  )}
                >
                  {c.title}
                </button>
              ))}
            </div>
          )}

          <p className="text-caption font-bold text-ink-soft mt-3 mb-1.5">مدت تمرین (دقیقه)</p>
          <div className="flex bg-paper-2 rounded-xl p-1" role="radiogroup" aria-label="مدت تمرین">
            {MINUTES.map((m) => (
              <button
                key={m}
                type="button"
                role="radio"
                aria-checked={minutes === m}
                onClick={() => setMinutes(m)}
                className={cn("flex-1 h-9 rounded-xl text-body-sm font-bold tabular-nums", minutes === m ? "bg-canvas shadow-card text-ink" : "text-ink-soft")}
              >
                {faNumber(m)}
              </button>
            ))}
          </div>

          <Textarea className="mt-3 resize-none" rows={2} maxLength={500} value={note} onChange={(e) => setNote(e.target.value)} placeholder="یادداشت (اختیاری)" />

          <label className="flex items-center justify-between mt-3">
            <span className="text-body font-bold flex items-center gap-2">
              <Images className="w-4 h-4 text-sienna" aria-hidden="true" />
              نمایش در گالری هنرجوها
            </span>
            <Switch checked={isPublic} onCheckedChange={(on) => { setIsPublic(on); setPublicTouched(true) }} aria-label="نمایش در گالری هنرجوها" />
          </label>
          <p className="text-micro text-ink-soft mt-1">
            {isPublic ? "پس از تأیید رنگوک در گالری منتشر می‌شود؛ فقط نام کوچکت دیده می‌شود." : "فقط خودت این تمرین را می‌بینی."}
          </p>

          <Button size="lg" className="w-full h-12 rounded-2xl mt-4" onClick={save} disabled={loading}>
            {loading ? <Loader2 className="w-4 h-4 animate-spin" /> : (
              <>
                <Flame className="w-5 h-5" />
                ثبت و ادامه‌ی استمرار
              </>
            )}
          </Button>
        </div>
      </DrawerContent>
    </Drawer>
  )
}
