"use client"

import { ChangeEvent, useEffect, useState } from "react"
import { ImagePlus, Loader2, Send, CreditCard } 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 { toast } from "@/components/ui/use-toast"

import { useVersionedRouter } from "@/hooks/use-versioned-router"
import { ApiEndpoint } from "@/lib/services/api.service"
import { getApiErrorMessage, useApi } from "@/lib/services/axios.service"
import { MAX_UPLOAD_TIME_OUT } from "@/constants/upload-file.constant"
import { SubmissionDto, SubmissionKind } from "@/lib/dto/submission.dto"
import { ProductType } from "@/lib/enums/product-type.enum"
import { faNumber } from "@/lib/helpers/format.helper"

// The API takes JPG, PNG or WebP up to 15 MB and re-encodes it (EXIF removed).
const MAX_ARTWORK_SIZE = 15 * 1024 * 1024
const ARTWORK_TYPES = ["image/jpeg", "image/png", "image/webp"]

export interface SubmissionSheetProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  kind: SubmissionKind
  /** Homework: the lesson it belongs to. */
  lessonId?: number
  /** Paid critique: the coach's slug, name and current price. */
  coach?: { slug: string; name: string; critique_price: number | null }
  /** Paid critique from a course page: tie it to that course. */
  courseId?: number
  parentId?: number
  /** A line under the title, e.g. */
  context?: string
}

export default function SubmissionSheet({
  open,
  onOpenChange,
  kind,
  lessonId,
  coach,
  courseId,
  parentId,
  context,
}: SubmissionSheetProps) {
  const router = useVersionedRouter()

  const [file, setFile] = useState<File | null>(null)
  const [preview, setPreview] = useState<string | null>(null)
  const [title, setTitle] = useState("")
  const [note, setNote] = useState("")

  const [{ loading }, sendRequest] = useApi<SubmissionDto>({
    url: ApiEndpoint("submission", "store"),
    method: "POST",
    timeout: MAX_UPLOAD_TIME_OUT,
  })

  // Free the preview's object URL when it changes or the sheet goes away.
  useEffect(() => {
    return () => {
      if (preview) URL.revokeObjectURL(preview)
    }
  }, [preview])

  const isCritique = kind === "critique"
  const sheetTitle = parentId
    ? "ارسال نسخه‌ی اصلاح‌شده"
    : isCritique ? "درخواست نقد ویژه" : "ارسال تکلیف برای نقد"

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

    if (!ARTWORK_TYPES.includes(picked.type)) {
      toast({ title: "این فایل تصویر نیست", description: "عکس JPG، PNG یا WebP بفرست.", variant: "error" })
      return
    }

    if (picked.size > MAX_ARTWORK_SIZE) {
      toast({ title: "عکس خیلی بزرگ است", description: "حجم عکس حداکثر ۱۵ مگابایت است.", variant: "error" })
      return
    }

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

  async function handleSend() {
    if (loading) return

    if (!file) {
      toast({ title: "اول عکس نقاشی‌ات را انتخاب کن", variant: "error" })
      return
    }

    if (!title.trim()) {
      toast({ title: "برای اثرت یک نام بنویس", variant: "error" })
      return
    }

    const formData = new FormData()
    formData.append("kind", kind)
    formData.append("image", file)
    formData.append("title", title.trim())
    if (note.trim()) formData.append("note", note.trim())
    if (parentId) formData.append("parent_id", String(parentId))
    if (!parentId && lessonId) formData.append("lesson_id", String(lessonId))
    if (!parentId && coach) formData.append("coach", coach.slug)
    if (courseId) formData.append("course_id", String(courseId))

    try {
      const response = await sendRequest({ data: formData })
      const result = response?.body ?? response

      if (!result?.ok) {
        toast({ title: "خطا", description: result?.msg || "ارسال اثر انجام نشد", variant: "error" })
        return
      }

      const submission: SubmissionDto = result.data
      onOpenChange(false)

      if (submission.purchase) {
        // Paid critique: on to the purchase page; it enters the coach's queue once paid.
        router.push(`/course/purchase?type=${ProductType.CRITIQUE}&id=${submission.purchase.id}`)
        return
      }

      toast({ title: "ارسال شد", description: result.msg || "تکلیفت برای مربی فرستاده شد.", variant: "success" })
      router.push(`/submissions/view?id=${submission.id}`)
    } catch (err: unknown) {
      toast({ title: "خطا", description: getApiErrorMessage(err), variant: "error" })
    }
  }

  const price = coach?.critique_price ?? null

  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-lg font-extrabold">{sheetTitle}</DrawerTitle>
            {context && <DrawerDescription>{context}</DrawerDescription>}
          </DrawerHeader>

          <label
            className="flex flex-col items-center justify-center min-h-40 rounded-2xl border-2 border-dashed border-line bg-canvas p-3 cursor-pointer transition hover:bg-paper-2/50"
          >
            <input
              type="file"
              className="hidden"
              accept={ARTWORK_TYPES.join(",")}
              onChange={handleFile}
            />

            {preview ? (
              // eslint-disable-next-line @next/next/no-img-element
              <img src={preview} alt="پیش‌نمایش اثر" className="max-h-56 rounded-xl object-contain" />
            ) : (
              <div className="flex flex-col items-center text-ink-soft [&>*:not(:last-child)]:mb-1.5">
                <ImagePlus className="w-7 h-7" />
                <span className="text-sm font-bold text-ink">عکس نقاشی‌ات را انتخاب کن</span>
                <span className="text-xs">در نور روز و از روبه‌رو عکس بگیر</span>
              </div>
            )}
          </label>

          {preview && (
            <p className="text-xs text-muted-foreground mt-1.5">برای عوض کردن عکس، دوباره روی آن بزن.</p>
          )}

          <Input
            className="mt-3"
            value={title}
            maxLength={120}
            onChange={(e) => setTitle(e.target.value)}
            placeholder="نام اثر (مثلاً: گل‌های شقایق)"
          />

          <Textarea
            className="mt-2 resize-none"
            rows={3}
            value={note}
            maxLength={1000}
            onChange={(e) => setNote(e.target.value)}
            placeholder="برای مربی بنویس کجای کار برایت سخت بود…"
          />

          {isCritique && (
            <p className="text-xs text-muted-foreground mt-2 leading-6">
              {price !== null
                ? `هزینه‌ی نقد ${faNumber(price)} تومان است؛ بعد از پرداخت، مربی تا ۴۸ ساعت نقدت می‌کند.`
                : "بعد از پرداخت، مربی تا ۴۸ ساعت نقدت می‌کند."}
            </p>
          )}

          <Button size="lg" className="w-full rounded-xl mt-3 h-12" onClick={handleSend} disabled={loading}>
            {loading ? (
              <Loader2 className="w-4 h-4 animate-spin" />
            ) : isCritique ? (
              <>
                <CreditCard className="w-4 h-4" />
                ادامه و پرداخت
              </>
            ) : (
              <>
                <Send className="w-4 h-4" />
                ارسال برای مربی
              </>
            )}
          </Button>
        </div>
      </DrawerContent>
    </Drawer>
  )
}
