"use client"

import { useForm } from "react-hook-form"
import { useEffect, useState } from "react"
import { useVersionedRouter } from "@/hooks/use-versioned-router"

import { Input } from "@/components/ui/input"
import { Button } from "@/components/ui/button"
import VersionedLink from "@/components/common/versioned-link"
import { Textarea } from "@/components/ui/textarea"
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group"
import { Label } from "@/components/ui/label"
import AttachmentInput from "@/components/common/attachment-input.component"
import PriceBreakdown from "@/components/common/price-breakdown.component"
import { toast } from "@/components/ui/use-toast"

import { getApiErrorMessage, useApi } from "@/lib/services/axios.service"
import { ApiEndpoint } from "@/lib/services/api.service"

import ErrorBox from "@/components/common/error-box.component"
import Loading from "@/components/common/loading.component"

import { Form, FormField, FormItem, FormLabel, FormControl, FormMessage, FormDescription } from "@/components/ui/form"
import { Separator } from "@/components/ui/separator"
import { PaymentMethod } from "@/lib/enums/payment-method.enum"
import { ProductType } from "@/lib/enums/product-type.enum"
import { CoursePurchaseDetails, CritiquePurchaseDetails, PurchaseFetchResponseDto } from "@/lib/dto/purchase.dto"
import { DiscountValidateResultDto } from "@/lib/dto/discount.dto"
import { convertDate } from "@/lib/helpers/date.helper"
import CourseRemainingTime from "@/components/course/course-remaining-time"
import { useNumberQueryParam } from "@/hooks/useNumberQueryParam"
import { useSearchParams } from "next/navigation"
import { ALLOWED_ATTACHMENT_TYPES, ATTACHMENT_ERROR_MESSAGE, MAX_ATTACHMENT_SIZE, MAX_UPLOAD_TIME_OUT } from "@/constants/upload-file.constant"
import Sticky from "@/components/common/sticky.component"
import PaymentExpiryCountdown from "@/components/payment/payment-expiry-countdown.component"
import { Loader2, Check, X, Receipt, CreditCard, Wallet, Landmark, Ban } from "lucide-react"
import { cn } from "@/lib/utils"
import { PaymentMethodOption } from "@/lib/dto/purchase.dto"
import { getPlatformServices } from "@/lib/platform/services"
import { faNumber } from "@/lib/helpers/format.helper"

const PAYMENT_METHOD_ICON: Record<string, typeof Receipt> = {
  [PaymentMethod.MANUAL]: Receipt,
  [PaymentMethod.IPG]: CreditCard,
  [PaymentMethod.WALLET]: Wallet,
}

const PAYMENT_METHOD_DESCRIPTION: Record<string, string> = {
  [PaymentMethod.MANUAL]: "واریز کارت به کارت و بارگذاری تصویر رسید",
  [PaymentMethod.IPG]: "پرداخت آنلاین امن از طریق درگاه بانکی",
  [PaymentMethod.WALLET]: "پرداخت از موجودی کیف پول شما",
}

const SUBMIT_BUTTON_LABEL: Record<string, string> = {
  [PaymentMethod.MANUAL]: "ثبت درخواست",
  [PaymentMethod.IPG]: "شروع پرداخت",
  [PaymentMethod.WALLET]: "پرداخت با کیف پول",
}

const PRODUCT_COPY: Record<ProductType, {
  loadError: string
  notPurchasable: string
  alreadyPaid: string
  pendingIpg: string
  cardLabel: string
  returnPath: (id: number | null) => string
}> = {
  [ProductType.COURSE]: {
    loadError: "خطا در دریافت اطلاعات دوره",
    notPurchasable: "دوره در حال حاضر قابل فروش نمی باشد",
    alreadyPaid: "این دوره قبلاً توسط شما خریداری شده است",
    pendingIpg: "شما یک پرداخت آنلاین در حال انجام برای این دوره دارید.",
    cardLabel: "خرید دوره",
    returnPath: (id) => `/course/detail?id=${id}`,
  },
  [ProductType.CRITIQUE]: {
    loadError: "خطا در دریافت اطلاعات درخواست نقد",
    notPurchasable: "این درخواست نقد دیگر قابل پرداخت نیست",
    alreadyPaid: "هزینه‌ی این نقد قبلاً پرداخت شده است",
    pendingIpg: "شما یک پرداخت آنلاین در حال انجام برای این نقد دارید.",
    cardLabel: "نقد ویژه",
    returnPath: (id) => `/submissions/view?id=${id}`,
  },
}

type FormValues = {
  payment_method: string
  receipt_code: string
  description: string
  receipt_img: File | null
}

type PurchaseResult = {
  order_id: number
  payment_method: string
  redirect_url: string | null
}

export default function PurchaseView() {
  const id = useNumberQueryParam("id");

  if (!id) {
    return null;
  }

  return <PurchaseContent key={id} id={id} />
}

function PurchaseContent({ id }: { id: number }) {
  const searchParams = useSearchParams()
  const router = useVersionedRouter()
  const productType = searchParams.get("type") === ProductType.CRITIQUE ? ProductType.CRITIQUE : ProductType.COURSE
  const copy = PRODUCT_COPY[productType]

  const [purchase, setPurchase] = useState<PurchaseFetchResponseDto | null>(null)
  const [loadError, setLoadError] = useState<string | null>(null)

  const methods = useForm<FormValues>({
    defaultValues: {
      payment_method: "",
      receipt_code: "",
      description: "",
      receipt_img: null
    }
  })

  const {
    handleSubmit,
    setValue,
    reset,
    watch
  } = methods

  const receiptImg = watch("receipt_img")
  const paymentMethod = watch("payment_method")
  const [fileName, setFileName] = useState<string | null>(null)

  const isManual = paymentMethod === PaymentMethod.MANUAL
  const isIpg = paymentMethod === PaymentMethod.IPG

  const [discountCodeInput, setDiscountCodeInput] = useState("")
  const [appliedDiscount, setAppliedDiscount] = useState<DiscountValidateResultDto | null>(null)
  const [discountError, setDiscountError] = useState<string | null>(null)
  const [isValidatingDiscount, setIsValidatingDiscount] = useState(false)
  const [isCancelling, setIsCancelling] = useState(false)

  const [{ loading: fetchLoading }, fetchPurchase] = useApi<PurchaseFetchResponseDto>({
    url: ApiEndpoint("order", "purchase-preview", { purchasable_type: productType, purchasable_id: id }),
    method: "GET",
  })

  const [{ loading: createLoading }, purchaseCourse] = useApi<any>({
    url: ApiEndpoint("order", "purchase"),
    method: "POST",
    timeout: MAX_UPLOAD_TIME_OUT
  })

  const [, validateDiscountRequest] = useApi<DiscountValidateResultDto>({
    url: ApiEndpoint("order", "discount-validate"),
    method: "POST",
  })

  const [, cancelPendingRequest] = useApi<any>({
    url: ApiEndpoint("order", "cancel-pending", { purchasable_type: productType, purchasable_id: id }),
    method: "POST",
  })

  const loadPurchase = async () => {
    try {

      const response = await fetchPurchase()
      const result = response?.body

      if (!result || !result.ok) {
        setLoadError(copy.loadError)
        setPurchase(null)
        return
      }

      setLoadError(null)
      setPurchase(result.data)

      const methodsList: PaymentMethodOption[] = result.data?.payment?.methods ?? []
      const firstEnabledMethod = methodsList.find((method) => method.enabled)
      if (firstEnabledMethod) {
        setValue("payment_method", firstEnabledMethod.key)
      }

      // No retry/resume, so each fetch is a clean slate.
      setAppliedDiscount(null)

    } catch (err: any) {
      setLoadError(getApiErrorMessage(err))
      setPurchase(null)
    }
  }

  useEffect(() => {
    if (id) loadPurchase()
  }, [id])

  function handleFileChange(e: React.ChangeEvent<HTMLInputElement>) {

    const file = e.target.files?.[0]
    if (!file) return

    const isSizeOk = file.size <= MAX_ATTACHMENT_SIZE
    const isTypeOk = ALLOWED_ATTACHMENT_TYPES.includes(file.type)

    if (!isSizeOk || !isTypeOk) {

      setValue("receipt_img", null, { shouldValidate: false })
      setFileName(null)

      toast({
        title: "خطای فایل",
        description: ATTACHMENT_ERROR_MESSAGE,
        variant: "error"
      })

      return
    }

    setValue("receipt_img", file, { shouldValidate: false })
    setFileName(file.name)
  }

  const isPendingManual = purchase?.purchase_status === "pending" && purchase?.payment_method === PaymentMethod.MANUAL
  const isPendingIpg = purchase?.purchase_status === "pending" && purchase?.payment_method === PaymentMethod.IPG

  const paymentMethods = purchase?.payment?.methods ?? []
  const hasEnabledPaymentMethod = paymentMethods.some((method) => method.enabled)

  function getPurchaseStatusMessage() {

    if (!purchase) return null

    if (!purchase.details.is_purchasable) {
      return copy.notPurchasable
    }

    if (isPendingManual) {
      return "درخواست خرید شما در حال بررسی است"
    }

    if (purchase.purchase_status === "paid") {
      return copy.alreadyPaid
    }

    if (!hasEnabledPaymentMethod) {
      return "در حال حاضر هیچ روش پرداختی فعال نیست"
    }

    return null
  }

  function getFreeCourseMessage() {
    if (!purchase) return null
    if (purchase.price === 0) {
      return productType === ProductType.COURSE ? "این دوره رایگان است و نیازی به خرید ندارد" : "این مورد رایگان است و نیازی به پرداخت ندارد"
    }
    return null
  }

  function handleDiscountInputChange(value: string) {
    setDiscountCodeInput(value)
    if (appliedDiscount) setAppliedDiscount(null)
    if (discountError) setDiscountError(null)
  }

  async function handleApplyDiscount() {
    const code = discountCodeInput.trim()
    if (!code || isValidatingDiscount) return

    setIsValidatingDiscount(true)
    setDiscountError(null)

    try {

      const response = await validateDiscountRequest({
        data: {
          purchasable_type: purchase?.purchasable_type,
          purchasable_id: id,
          discount_code: code
        }
      })

      const result = response?.body ?? response

      if (result?.ok && result.data?.valid) {
        setAppliedDiscount(result.data)
        setDiscountError(null)
      } else {
        setAppliedDiscount(null)
        setDiscountError(result?.data?.message || "کد تخفیف معتبر نیست یا منقضی شده است")
      }

    } catch (err: any) {
      setAppliedDiscount(null)
      setDiscountError(getApiErrorMessage(err))
    } finally {
      setIsValidatingDiscount(false)
    }
  }

  function handleRemoveDiscount() {
    setAppliedDiscount(null)
    setDiscountError(null)
    setDiscountCodeInput("")
  }

  async function handleCancelPending() {
    if (isCancelling) return
    setIsCancelling(true)

    try {

      const response = await cancelPendingRequest()
      const result = response?.body ?? response

      if (!result?.ok) {
        toast({
          title: "خطا",
          description: result?.msg || "لغو پرداخت با خطا مواجه شد",
          variant: "error"
        })

        // Resync - the order's server-side state may have already moved on.
        loadPurchase()

        return
      }

      toast({
        title: "لغو شد",
        description: result.msg || "پرداخت در انتظار لغو شد.",
        variant: "success"
      })

      loadPurchase()

    } catch (err: any) {

      if (err?.httpStatus === 404) {
        toast({
          title: "قبلاً منقضی شده بود",
          description: "این پرداخت پیش از این به‌صورت خودکار منقضی شده بود.",
          variant: "success"
        })
      } else {
        toast({
          title: "خطا",
          description: getApiErrorMessage(err),
          variant: "error"
        })
      }

      // Always resync - otherwise an out-of-band expiry leaves this stale panel up forever.
      loadPurchase()

    } finally {
      setIsCancelling(false)
    }
  }

  async function onSubmit(data: FormValues) {

    const formData = new FormData()

    formData.append("purchasable_type", purchase?.purchasable_type ?? "")
    formData.append("purchasable_id", String(id))
    formData.append("payment_method", data.payment_method)

    if (appliedDiscount) {
      formData.append("discount_code", appliedDiscount.code)
    }

    if (isManual) {
      formData.append("receipt_code", data.receipt_code.trim())

      if (data.receipt_img) {
        formData.append("receipt_img", data.receipt_img)
      }
    }

    if (data.description.trim()) {
      formData.append("description", data.description.trim())
    }

    try {

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

      if (!result?.ok) {

        toast({
          title: "خطا",
          description: result?.msg || "خطا در ثبت درخواست خرید",
          variant: "error"
        })

        if (appliedDiscount) {
          handleRemoveDiscount()
        }

        // Resync - the order may already exist server-side (a race with another tab).
        loadPurchase()

        return
      }

      const purchaseResult: PurchaseResult = result.data

      if (purchaseResult.redirect_url) {
        // Website: go to the gateway.
        await getPlatformServices().startPayment(purchaseResult.redirect_url, copy.returnPath(id))
        return
      }

      toast({
        title: "موفقیت آمیز!",
        description: result.msg || "درخواست خرید با موفقیت ثبت شد",
        variant: "success"
      })

      reset({
        payment_method: data.payment_method,
        receipt_code: "",
        description: "",
        receipt_img: null
      })

      setFileName(null)
      handleRemoveDiscount()

      router.replace(copy.returnPath(id))

    } catch (err: any) {

      toast({
        title: "خطا",
        description: getApiErrorMessage(err),
        variant: "error"
      })

      if (appliedDiscount) {
        handleRemoveDiscount()
      }

      loadPurchase()

    }
  }

  const statusMessage = getPurchaseStatusMessage()

  const isFreeCourse = purchase?.price === 0
  const isCoursePurchasable = purchase?.details.is_purchasable == true
  const freeMessage = getFreeCourseMessage()
  const paymentGateways = purchase?.payment?.gateways ?? []
  const submitButtonLabel = SUBMIT_BUTTON_LABEL[paymentMethod] ?? "ثبت درخواست"

  const allowForm =
    purchase &&
    isCoursePurchasable &&
    !isFreeCourse &&
    hasEnabledPaymentMethod &&
    (!purchase.purchase_status ||
      purchase.purchase_status === "failed" ||
      purchase.purchase_status === "cancelled")

  const finalPrice = appliedDiscount ? appliedDiscount.final_price : purchase?.price ?? 0

  // Narrowed per product type: course details have dates, a critique has the artwork.
  const courseDetails = productType === ProductType.COURSE ? (purchase?.details as CoursePurchaseDetails | undefined) : undefined
  const critiqueDetails = productType === ProductType.CRITIQUE ? (purchase?.details as CritiquePurchaseDetails | undefined) : undefined

  const productInfoCard = purchase && (
    <div className="flex flex-col [&>*:not(:last-child)]:mb-4">

      <div className="flex items-start justify-between">
        <div className="min-w-0">
          <div className="text-xs text-muted-foreground mb-1">{copy.cardLabel}</div>
          <div className="font-semibold text-base text-primary leading-tight">
            {purchase.title}
          </div>
        </div>

        <div className="text-left shrink-0">
          <div className="font-bold text-lg">
            {faNumber(finalPrice)}
          </div>
          <div className="text-xs text-muted-foreground">تومان</div>
        </div>
      </div>

      {courseDetails && (
        <div className="flex flex-wrap items-center">
          {courseDetails.start_date && (
            <div className="ml-1 px-3 py-1 rounded-full text-xs bg-muted text-foreground">
              شروع: {convertDate(courseDetails.start_date)}
            </div>
          )}

          {courseDetails.end_date && (
            <div className="mx-1 px-3 py-1 rounded-full text-xs bg-muted text-foreground">
              پایان: {convertDate(courseDetails.end_date)}
            </div>
          )}

          <CourseRemainingTime
            startDate={courseDetails.start_date}
            endDate={courseDetails.end_date}
            className="bg-blue-100 text-blue-700 text-xs px-3 py-1 rounded-full border-none shadow-none hover:bg-blue-100"
          />
        </div>
      )}

      {critiqueDetails && (
        <div className="flex items-start">
          {critiqueDetails.artwork && (
            // eslint-disable-next-line @next/next/no-img-element
            <img
              src={critiqueDetails.artwork}
              alt={critiqueDetails.title}
              className="w-20 h-20 rounded-xl object-cover shrink-0 bg-muted"
            />
          )}
          <div className="min-w-0 flex-1 mr-3 text-xs text-muted-foreground leading-6">
            <div>مربی تا ۴۸ ساعت بعد از پرداخت، روی خود اثر نکته می‌گذارد و با امتیاز و یادداشت صوتی نقدش می‌کند.</div>
            {critiqueDetails.note && <div className="line-clamp-2 mt-1">یادداشت شما: {critiqueDetails.note}</div>}
          </div>
        </div>
      )}
    </div>
  )

  return (
    <div className="flex flex-col flex-1 bg-background py-5 text-right">
      <div className="flex-1 overflow-y-auto min-h-0 px-4 ">
        <div className="w-full max-w-md mx-auto flex flex-col [&>*:not(:last-child)]:mb-1">

          <Loading loading={fetchLoading}>
            <ErrorBox
              active={!!loadError}
              title="خطا"
              description={loadError}
              showRetry={!!loadError}
              onRetry={loadPurchase}
            >
              {isPendingIpg ? (

                <div className="flex flex-col [&>*:not(:last-child)]:mb-4">
                  {productInfoCard}

                  <div className="rounded-2xl border border-dashed bg-muted/50 p-4 flex flex-col [&>*:not(:last-child)]:mb-3">
                    <div className="flex items-center gap-2 text-sm font-medium">
                      <Landmark className="h-4 w-4 text-primary shrink-0" />
                      <span>{copy.pendingIpg}</span>
                    </div>

                    {purchase?.payment_expires_at && (
                      <div className="flex items-center justify-between text-xs text-muted-foreground">
                        <span>تا لغو خودکار:</span>
                        <PaymentExpiryCountdown
                          expiresAt={purchase.payment_expires_at}
                          onExpire={loadPurchase}
                          className="font-medium text-foreground"
                        />
                      </div>
                    )}

                    <p className="text-xs text-muted-foreground">
                      برای تلاش دوباره (همین حالا یا با روش دیگر)، ابتدا پرداخت فعلی را لغو کنید.
                    </p>

                    <Button
                      type="button"
                      variant="outline"
                      className="w-full rounded-xl border-destructive/40 text-destructive hover:bg-destructive/10 hover:text-destructive"
                      onClick={handleCancelPending}
                      disabled={isCancelling}
                    >
                      {isCancelling ? <Loader2 className="h-4 w-4 animate-spin" /> : "لغو پرداخت"}
                    </Button>
                  </div>
                </div>

              ) : !allowForm && isFreeCourse ? (
                <ErrorBox
                  active={true}
                  title="امکان خرید وجود ندارد"
                  description={freeMessage}
                  showRetry={false}
                />
              ) : !allowForm && statusMessage ? (
                <ErrorBox
                  active={true}
                  title="امکان ثبت درخواست وجود ندارد"
                  description={statusMessage}
                  showRetry={false}
                />
              ) : (

                <>

                  {productInfoCard}

                  <div className="flex flex-col mt-2 [&>*:not(:last-child)]:mb-6">

                    {allowForm && (
                      <Form {...methods}>
                        <form
                          onSubmit={handleSubmit(onSubmit)}
                          className="flex flex-col [&>*:not(:last-child)]:mb-4"
                        >

                          <Separator />

                          {paymentMethods.length > 1 && (
                            <FormField
                              control={methods.control}
                              name="payment_method"
                              render={({ field }) => (
                                <FormItem className="flex flex-col [&>*:not(:last-child)]:mb-2">
                                  <FormLabel>روش پرداخت</FormLabel>
                                  <FormControl>
                                    <RadioGroup
                                      value={field.value}
                                      onValueChange={field.onChange}
                                      className="gap-2.5"
                                    >
                                      {paymentMethods.map((method) => {
                                        const selected = field.value === method.key
                                        const Icon = method.enabled ? (PAYMENT_METHOD_ICON[method.key] ?? CreditCard) : Ban
                                        const description = method.enabled
                                          ? PAYMENT_METHOD_DESCRIPTION[method.key]
                                          : (method.unavailability_reason ?? "در حال حاضر غیرفعال است")

                                        return (
                                          <Label
                                            key={method.key}
                                            htmlFor={`payment-method-${method.key}`}
                                            className={cn(
                                              "flex items-center gap-3 rounded-2xl border p-3.5 font-normal transition-all",
                                              !method.enabled
                                                ? "cursor-not-allowed opacity-60 border-border bg-muted/20"
                                                : selected
                                                  ? "cursor-pointer border-primary bg-primary/5 ring-1 ring-primary/30"
                                                  : "cursor-pointer border-border bg-card hover:bg-muted/40"
                                            )}
                                          >
                                            <div
                                              className={cn(
                                                "flex h-10 w-10 shrink-0 items-center justify-center rounded-xl transition-colors",
                                                !method.enabled
                                                  ? "bg-muted text-muted-foreground"
                                                  : selected
                                                    ? "bg-primary text-primary-foreground"
                                                    : "bg-muted text-muted-foreground"
                                              )}
                                            >
                                              <Icon className="h-5 w-5" />
                                            </div>

                                            <div className="min-w-0 flex-1">
                                              <div className="text-sm font-medium flex items-center gap-1.5">
                                                {method.label}
                                                {!method.enabled && (
                                                  <span className="text-[10px] font-normal text-muted-foreground">
                                                    (غیرفعال)
                                                  </span>
                                                )}
                                              </div>

                                              {description && (
                                                <div className="text-xs text-muted-foreground mt-0.5">
                                                  {description}
                                                </div>
                                              )}
                                            </div>

                                            <RadioGroupItem
                                              id={`payment-method-${method.key}`}
                                              value={method.key}
                                              disabled={!method.enabled}
                                              className="shrink-0"
                                            />
                                          </Label>
                                        )
                                      })}
                                    </RadioGroup>
                                  </FormControl>
                                  <FormMessage />
                                </FormItem>
                              )}
                            />
                          )}

                          {isManual && (
                            <div className="flex flex-col [&>*:not(:last-child)]:mb-1">
                              <div className="text-xs text-muted-foreground">شماره کارت جهت واریز</div>
                              <div className="font-medium text-sm tracking-widest break-all bg-muted/50 px-3 py-3 rounded-xl border border-dashed">
                                {purchase?.payment_card}
                              </div>
                            </div>
                          )}

                          {isManual && (
                            <FormField
                              control={methods.control}
                              name="receipt_code"
                              rules={{
                                required: "کد رسید نمی‌تواند خالی باشد",
                                pattern: {
                                  value: /^[0-9]+$/,
                                  message: "کد رسید باید فقط شامل عدد باشد"
                                },
                                maxLength: {
                                  value: 25,
                                  message: "کد رسید نمی‌تواند بیشتر از 25 رقم باشد"
                                }
                              }}
                              render={({ field }) => (
                                <FormItem className="flex flex-col [&>*:not(:last-child)]:mb-2">
                                  <FormLabel>کد رسید</FormLabel>
                                  <FormControl>
                                    <Input
                                      placeholder="کد رسید را وارد کنید"
                                      inputMode="numeric"
                                      maxLength={25}
                                      {...field}
                                    />
                                  </FormControl>
                                  <FormMessage />
                                </FormItem>
                              )}
                            />
                          )}

                          {isManual && (
                            <div className="flex flex-col [&>*:not(:last-child)]:mb-3">

                              <FormField
                                control={methods.control}
                                name="receipt_img"
                                rules={{ required: "تصویر رسید الزامی است" }}
                                render={() => (
                                  <FormItem className="flex flex-col [&>*:not(:last-child)]:mb-2">
                                    <FormLabel>تصویر رسید</FormLabel>

                                    <AttachmentInput
                                      fileName={fileName}
                                      hasFile={!!receiptImg}
                                      accept=".png,.jpg,.jpeg"
                                      onChange={handleFileChange}
                                    />

                                    <FormMessage />
                                  </FormItem>
                                )}
                              />

                              <FormDescription>
                                {ATTACHMENT_ERROR_MESSAGE}
                              </FormDescription>

                            </div>
                          )}

                          {isIpg && paymentGateways.length > 0 && (
                            <div className="flex flex-col [&>*:not(:last-child)]:mb-1">
                              <div className="text-xs text-muted-foreground">درگاه پرداخت</div>
                              <div className="flex flex-col gap-1.5">
                                {paymentGateways.map((gateway) => (
                                  <div
                                    key={gateway.key}
                                    className={cn(
                                      "flex items-center gap-2.5 px-3 py-3 rounded-xl border border-dashed",
                                      gateway.enabled ? "bg-muted/50" : "bg-muted/20 opacity-60"
                                    )}
                                  >
                                    <div
                                      className={cn(
                                        "flex h-8 w-8 shrink-0 items-center justify-center rounded-lg",
                                        gateway.enabled ? "bg-primary/10 text-primary" : "bg-muted text-muted-foreground"
                                      )}
                                    >
                                      {gateway.enabled ? <Landmark className="h-4 w-4" /> : <Ban className="h-4 w-4" />}
                                    </div>
                                    <span className="text-sm font-medium flex items-center gap-1.5">
                                      {gateway.label}
                                      {!gateway.enabled && (
                                        <span className="text-[10px] font-normal text-muted-foreground">
                                          (غیرفعال)
                                        </span>
                                      )}
                                    </span>
                                  </div>
                                ))}
                              </div>
                            </div>
                          )}

                          <FormField
                            control={methods.control}
                            name="description"
                            rules={{
                              maxLength: {
                                value: 99,
                                message: "توضیحات نمی‌تواند بیشتر از 99 کاراکتر باشد"
                              }
                            }}
                            render={({ field }) => (
                              <FormItem className="flex flex-col [&>*:not(:last-child)]:mb-2">
                                <FormLabel>توضیحات (اختیاری)</FormLabel>
                                <FormControl>
                                  <Textarea
                                    rows={1}
                                    maxLength={99}
                                    placeholder="در صورت نیاز توضیحات خود را بنویسید"
                                    className="min-h-0 h-12 py-3 resize-none"
                                    {...field}
                                  />
                                </FormControl>
                                <FormMessage />
                              </FormItem>
                            )}
                          />

                          <div className="flex flex-col [&>*:not(:last-child)]:mb-2">
                            <FormLabel>کد تخفیف (اختیاری)</FormLabel>

                            {appliedDiscount ? (
                              <div className="flex items-center justify-between rounded-xl border border-green-600/30 bg-green-600/10 px-3.5 py-2.5">
                                <div className="flex items-center gap-2 text-green-700 dark:text-green-500">
                                  <Check className="h-4 w-4 shrink-0" />
                                  <span className="text-sm font-medium">
                                    کد «{appliedDiscount.code}» اعمال شد
                                  </span>
                                </div>

                                <button
                                  type="button"
                                  onClick={handleRemoveDiscount}
                                  className="text-muted-foreground hover:text-destructive transition-colors"
                                  aria-label="حذف کد تخفیف"
                                >
                                  <X className="h-4 w-4" />
                                </button>
                              </div>
                            ) : (
                              <>
                                <div className="flex gap-2">
                                  <Input
                                    value={discountCodeInput}
                                    onChange={(e) => handleDiscountInputChange(e.target.value)}
                                    placeholder="کد تخفیف را وارد کنید"
                                    autoComplete="off"
                                  />

                                  <Button
                                    type="button"
                                    variant="outline"
                                    className="h-12 min-w-20 shrink-0 rounded-xl"
                                    disabled={isValidatingDiscount || !discountCodeInput.trim()}
                                    onClick={handleApplyDiscount}
                                  >
                                    {isValidatingDiscount ? (
                                      <Loader2 className="h-4 w-4 animate-spin" />
                                    ) : (
                                      "اعمال"
                                    )}
                                  </Button>
                                </div>

                                {discountError && (
                                  <p className="text-xs font-medium text-red-600 dark:text-red-500">
                                    {discountError}
                                  </p>
                                )}
                              </>
                            )}
                          </div>

                          {purchase && (
                            <div className="rounded-xl bg-muted/50 p-4">
                              <PriceBreakdown
                                rawPrice={appliedDiscount?.raw_price ?? purchase.price}
                                discountCode={appliedDiscount?.code}
                                discountAmount={appliedDiscount?.discount_amount}
                                feeAmount={appliedDiscount?.fee_amount}
                                totalAmount={finalPrice}
                                size="base"
                              />
                            </div>
                          )}

                        </form>
                      </Form>
                    )}

                  </div>
                </>

              )}

            </ErrorBox>
          </Loading>
        </div>
      </div>

      {allowForm && (
        <Sticky>
          <Separator className="mb-3" />
          <div className="w-full max-w-md mx-auto px-4">
            <Button
              type="submit"
              size="lg"
              className="w-full rounded-xl mb-3"
              onClick={handleSubmit(onSubmit)}
              disabled={createLoading}
            >
              {submitButtonLabel}
            </Button>
            <p className="text-micro text-ink-soft text-center -mt-1 mb-3">
              با پرداخت، <VersionedLink href="/legal/refund" className="font-bold text-sienna">شرایط بازگشت وجه</VersionedLink> را می‌پذیرید.
            </p>
          </div>
        </Sticky>
      )}
    </div>
  )

}
