import router, { useRouter } from 'next/router'
import { useEffect, useState } from 'react'
import clsx from 'clsx'
import dayjs from 'dayjs'
import Textarea from 'react-expanding-textarea'
import { Spacer } from 'web/components/layout/spacer'
import { useUser } from 'web/hooks/use-user'
import { Contract, contractPath } from 'web/lib/firebase/contracts'
import { createMarket } from 'web/lib/firebase/api-call'
import { FIXED_ANTE, MINIMUM_ANTE } from 'common/antes'
import { InfoTooltip } from 'web/components/info-tooltip'
import { Page } from 'web/components/page'
import { Row } from 'web/components/layout/row'
import {
MAX_DESCRIPTION_LENGTH,
MAX_QUESTION_LENGTH,
outcomeType,
} from 'common/contract'
import { formatMoney } from 'common/util/format'
import { removeUndefinedProps } from 'common/util/object'
import { ChoicesToggleGroup } from 'web/components/choices-toggle-group'
import { getGroup, updateGroup } from 'web/lib/firebase/groups'
import { Group } from 'common/group'
import { useTracking } from 'web/hooks/use-tracking'
import { useWarnUnsavedChanges } from 'web/hooks/use-warn-unsaved-changes'
import { track } from 'web/lib/service/analytics'
import { GroupSelector } from 'web/components/groups/group-selector'
import { CATEGORIES } from 'common/categories'
import { User } from 'common/user'
import { TextEditor } from 'web/components/editor'
import { JSONContent } from '@tiptap/react'
export default function Create() {
const [question, setQuestion] = useState('')
// get query params:
const router = useRouter()
const { groupId } = router.query as { groupId: string }
useTracking('view create page')
const creator = useUser()
useEffect(() => {
if (creator === null) router.push('/')
}, [creator, router])
if (!router.isReady || !creator) return
return (
)
}
// Allow user to create a new contract
export function NewContract(props: {
creator: User
question: string
groupId?: string
}) {
const { creator, question, groupId } = props
const [outcomeType, setOutcomeType] = useState('BINARY')
const [initialProb] = useState(50)
const [minString, setMinString] = useState('')
const [maxString, setMaxString] = useState('')
// const [tagText, setTagText] = useState(tag ?? '')
// const tags = parseWordsAsTags(tagText)
useEffect(() => {
if (groupId && creator)
getGroup(groupId).then((group) => {
if (group && group.memberIds.includes(creator.id)) {
setSelectedGroup(group)
setShowGroupSelector(false)
}
})
}, [creator, groupId])
const [ante, _setAnte] = useState(FIXED_ANTE)
// useEffect(() => {
// if (ante === null && creator) {
// const initialAnte = creator.balance < 100 ? MINIMUM_ANTE : 100
// setAnte(initialAnte)
// }
// }, [ante, creator])
// const [anteError, setAnteError] = useState()
// By default, close the market a week from today
const weekFromToday = dayjs().add(7, 'day').format('YYYY-MM-DD')
const [closeDate, setCloseDate] = useState(weekFromToday)
const [closeHoursMinutes, setCloseHoursMinutes] = useState('23:59')
const [marketInfoText, setMarketInfoText] = useState('')
const [isSubmitting, setIsSubmitting] = useState(false)
const [selectedGroup, setSelectedGroup] = useState(
undefined
)
const [showGroupSelector, setShowGroupSelector] = useState(true)
const [category, setCategory] = useState('')
const closeTime = closeDate
? dayjs(`${closeDate}T${closeHoursMinutes}`).valueOf()
: undefined
const balance = creator?.balance || 0
const min = minString ? parseFloat(minString) : undefined
const max = maxString ? parseFloat(maxString) : undefined
// get days from today until the end of this year:
const daysLeftInTheYear = dayjs().endOf('year').diff(dayjs(), 'day')
useWarnUnsavedChanges(!isSubmitting && Boolean(question))
const isValid =
(outcomeType === 'BINARY' ? initialProb >= 5 && initialProb <= 95 : true) &&
question.length > 0 &&
ante !== undefined &&
ante !== null &&
ante >= MINIMUM_ANTE &&
ante <= balance &&
// closeTime must be in the future
closeTime &&
closeTime > Date.now() &&
(outcomeType !== 'NUMERIC' ||
(min !== undefined &&
max !== undefined &&
isFinite(min) &&
isFinite(max) &&
min < max &&
max - min > 0.01))
function setCloseDateInDays(days: number) {
const newCloseDate = dayjs().add(days, 'day').format('YYYY-MM-DD')
setCloseDate(newCloseDate)
}
function submit() {
// TODO: Tell users why their contract is invalid
if (!creator || !isValid) return
setIsSubmitting(true)
}
async function onSubmit(description?: JSONContent) {
// TODO: add contract id to the group contractIds
try {
const result = await createMarket(
removeUndefinedProps({
question,
outcomeType,
description,
initialProb,
ante,
closeTime,
min,
max,
groupId: selectedGroup?.id,
tags: category ? [category] : undefined,
})
)
track('create market', {
slug: result.slug,
initialProb,
selectedGroup: selectedGroup?.id,
isFree: false,
})
if (result && selectedGroup) {
await updateGroup(selectedGroup, {
contractIds: [...selectedGroup.contractIds, result.id],
})
}
await router.push(contractPath(result as Contract))
} catch (e) {
console.log('error creating contract', e)
}
}
const descriptionPlaceholder =
outcomeType === 'BINARY'
? `e.g. This question resolves to "YES" if they receive the majority of votes...`
: `e.g. I will choose the answer according to...`
if (!creator) return <>>
return (
)
}