"use client"

import { useState } from "react"
import { ChevronLeft, Images } from "lucide-react"

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 { GalleryPieceDto } from "@/lib/dto/gallery.dto"
import { SubmissionDto } from "@/lib/dto/submission.dto"
import { ApiEndpoint } from "@/lib/services/api.service"
import { getApiErrorMessage, useApi } from "@/lib/services/axios.service"

type Shared = NonNullable<SubmissionDto["gallery"]>

/** «اشتراک در گالری» for a critiqued piece, or where it stands once shared. */
export default function GalleryShare({ submission, onShared }: { submission: SubmissionDto; onShared: (gallery: Shared) => void }) {
  const [open, setOpen] = useState(false)
  const [caption, setCaption] = useState("")
  const [{ loading }, share] = useApi<GalleryPieceDto>({ url: ApiEndpoint("gallery", "share"), method: "POST" })

  if (submission.gallery) {
    return (
      <Link href={`/gallery/view?id=${submission.gallery.id}`} className="flex items-center gap-3 mt-5 rounded-card border border-line bg-canvas p-3.5 shadow-card">
        <span className="w-10 h-10 rounded-xl bg-sienna-soft text-sienna grid place-items-center shrink-0" aria-hidden="true"><Images className="w-5 h-5" /></span>
        <span className="flex-1 min-w-0">
          <span className="block text-body-sm font-bold">در گالری هنرجوها</span>
          <span className="block text-micro text-ink-soft">{submission.gallery.status_label}</span>
        </span>
        <ChevronLeft className="w-4 h-4 text-ink-soft" aria-hidden="true" />
      </Link>
    )
  }

  async function submit() {
    try {
      const response = await share({ data: { source_type: "submission", source_id: submission.id, caption: caption.trim() || null } })
      const piece = response?.body?.data
      if (!piece) return
      onShared({ id: piece.id, status: piece.status ?? "pending", status_label: piece.status_label ?? "در انتظار تأیید" })
      setOpen(false)
      toast({ title: "فرستاده شد", description: "پس از تأیید رنگوک در گالری منتشر می‌شود.", variant: "success" })
    } catch (err) {
      toast({ title: "خطا", description: getApiErrorMessage(err), variant: "error" })
    }
  }

  return (
    <>
      <Button size="lg" variant="outline" className="w-full rounded-xl mt-5 h-12" onClick={() => setOpen(true)}>
        <Images className="w-4 h-4" />
        اشتراک در گالری
      </Button>

      <Drawer open={open} onOpenChange={setOpen}>
        <DrawerContent className="mx-auto w-full max-w-[480px]">
          <DrawerHeader className="text-right">
            <DrawerTitle className="text-title-3 font-extrabold">اشتراک در گالری هنرجوها</DrawerTitle>
            <DrawerDescription className="leading-6">
              اثر با نام کوچکت و متن نظر مربی نمایش داده می‌شود؛ صدا، نکته‌ها و نمره‌ها خصوصی می‌مانند. پس از تأیید رنگوک منتشر می‌شود.
            </DrawerDescription>
          </DrawerHeader>
          <div className="px-4 pb-[max(16px,env(safe-area-inset-bottom))] flex flex-col gap-3">
            <textarea
              value={caption}
              onChange={(e) => setCaption(e.target.value.slice(0, 300))}
              rows={3}
              placeholder="چند جمله درباره‌ی این اثر (اختیاری)"
              aria-label="توضیح اثر"
              className="rounded-2xl border border-line bg-background px-3.5 py-2.5 text-body outline-none focus:border-sienna"
            />
            <Button size="lg" className="h-12 rounded-2xl" disabled={loading} onClick={submit}>بفرست برای تأیید</Button>
          </div>
        </DrawerContent>
      </Drawer>
    </>
  )
}
