/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see .
For commercial licensing, please contact support@quantumnous.com
*/
import { useEffect, useState } from 'react'
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { useTranslation } from 'react-i18next'
import { toast } from 'sonner'
import { getCurrencyDisplay, getCurrencyLabel } from '@/lib/currency'
import { addTimeToDate } from '@/lib/time'
import { Button } from '@/components/ui/button'
import {
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage,
} from '@/components/ui/form'
import { Input } from '@/components/ui/input'
import {
Sheet,
SheetClose,
SheetContent,
SheetDescription,
SheetFooter,
SheetHeader,
SheetTitle,
} from '@/components/ui/sheet'
import { DateTimePicker } from '@/components/datetime-picker'
import {
SideDrawerSection,
sideDrawerContentClassName,
sideDrawerFooterClassName,
sideDrawerFormClassName,
sideDrawerHeaderClassName,
} from '@/components/drawer-layout'
import { createRedemption, updateRedemption, getRedemption } from '../api'
import { SUCCESS_MESSAGES } from '../constants'
import {
getRedemptionFormSchema,
type RedemptionFormValues,
REDEMPTION_FORM_DEFAULT_VALUES,
transformFormDataToPayload,
transformRedemptionToFormDefaults,
} from '../lib'
import { type Redemption } from '../types'
import { useRedemptions } from './redemptions-provider'
type RedemptionsMutateDrawerProps = {
open: boolean
onOpenChange: (open: boolean) => void
currentRow?: Redemption
}
export function RedemptionsMutateDrawer({
open,
onOpenChange,
currentRow,
}: RedemptionsMutateDrawerProps) {
const { t } = useTranslation()
const isUpdate = !!currentRow
const { triggerRefresh } = useRedemptions()
const [isSubmitting, setIsSubmitting] = useState(false)
const form = useForm({
resolver: zodResolver(getRedemptionFormSchema(t)),
defaultValues: REDEMPTION_FORM_DEFAULT_VALUES,
})
// Load existing data when updating
useEffect(() => {
if (open && isUpdate && currentRow) {
// For update, fetch fresh data
getRedemption(currentRow.id).then((result) => {
if (result.success && result.data) {
form.reset(transformRedemptionToFormDefaults(result.data))
}
})
} else if (open && !isUpdate) {
// For create, reset to defaults
form.reset(REDEMPTION_FORM_DEFAULT_VALUES)
}
}, [open, isUpdate, currentRow, form])
const onSubmit = async (data: RedemptionFormValues) => {
setIsSubmitting(true)
try {
const basePayload = transformFormDataToPayload(data)
if (isUpdate && currentRow) {
const result = await updateRedemption({
...basePayload,
id: currentRow.id,
})
if (result.success) {
toast.success(t(SUCCESS_MESSAGES.REDEMPTION_UPDATED))
onOpenChange(false)
triggerRefresh()
}
} else {
// Create mode
const result = await createRedemption(basePayload)
if (result.success) {
const count = result.data?.length || 0
toast.success(
count > 1
? t('Successfully created {{count}} redemption codes', {
count,
})
: t(SUCCESS_MESSAGES.REDEMPTION_CREATED)
)
onOpenChange(false)
triggerRefresh()
}
}
} finally {
setIsSubmitting(false)
}
}
const handleSetExpiry = (months: number, days: number, hours: number) => {
const newDate = addTimeToDate(months, days, hours)
form.setValue('expired_time', newDate)
}
const { meta: currencyMeta } = getCurrencyDisplay()
const currencyLabel = getCurrencyLabel()
const tokensOnly = currencyMeta.kind === 'tokens'
const quotaLabel = t('Quota ({{currency}})', { currency: currencyLabel })
const quotaPlaceholder = tokensOnly
? t('Enter quota in tokens')
: t('Enter quota in {{currency}}', { currency: currencyLabel })
return (
{
onOpenChange(v)
if (!v) {
form.reset()
}
}}
>
{isUpdate
? t('Update Redemption Code')
: t('Create Redemption Code')}
{isUpdate
? t('Update the redemption code by providing necessary info.')
: t(
'Add new redemption code(s) by providing necessary info.'
)}{' '}
{t('Click save when you're done.')}
}>
{t('Close')}
)
}