import { DotsHorizontalIcon } from '@heroicons/react/outline'
import clsx from 'clsx'
import { useState } from 'react'
import { Contract } from '../../../common/contract'
import { useFoldsWithTags } from '../../hooks/use-fold'
import { useUser } from '../../hooks/use-user'
import {
  contractPath,
  getBinaryProbPercent,
} from '../../lib/firebase/contracts'
import { Col } from '../layout/col'
import { Modal } from '../layout/modal'
import { Row } from '../layout/row'
import { ShareEmbedButton } from '../share-embed-button'
import { TagsInput } from '../tags-input'
import { FoldTagList } from '../tags-list'
import { Title } from '../title'
import { TweetButton } from '../tweet-button'

export function ContractInfoDialog(props: { contract: Contract }) {
  const { contract } = props

  const [open, setOpen] = useState(false)

  const user = useUser()

  const folds = (useFoldsWithTags(contract.tags) ?? []).filter(
    (fold) => fold.followCount > 1 || user?.id === fold.curatorId
  )

  return (
    <>
      <button
        className="group flex items-center rounded-md px-3 py-2 text-sm font-medium text-gray-600 hover:cursor-pointer hover:bg-gray-100"
        onClick={() => setOpen(true)}
      >
        <DotsHorizontalIcon
          className={clsx(
            'h-6 w-6 flex-shrink-0 text-gray-400 group-hover:text-gray-500'
          )}
          aria-hidden="true"
        />
      </button>

      <Modal open={open} setOpen={setOpen}>
        <Col className="gap-4 rounded bg-white p-6">
          <Title className="!mt-0 !mb-0" text="Market info" />

          <div className="text-gray-500">Share</div>
          <Row className="justify-start gap-4">
            <TweetButton
              className="self-start"
              tweetText={getTweetText(contract, false)}
            />
            <ShareEmbedButton contract={contract} />
          </Row>
          <div />
          <div className="text-gray-500">Communities</div>
          <FoldTagList folds={folds} noLabel />
          <div />

          <div className="text-gray-500">Tags</div>
          <TagsInput contract={contract} />

          <div />
        </Col>
      </Modal>
    </>
  )
}

const getTweetText = (contract: Contract, isCreator: boolean) => {
  const { question, creatorName, resolution, outcomeType } = contract
  const isBinary = outcomeType === 'BINARY'

  const tweetQuestion = isCreator
    ? question
    : `${question}\nAsked by ${creatorName}.`
  const tweetDescription = resolution
    ? `Resolved ${resolution}!`
    : isBinary
    ? `Currently ${getBinaryProbPercent(
        contract
      )} chance, place your bets here:`
    : `Submit your own answer:`

  const timeParam = `${Date.now()}`.substring(7)
  const url = `https://manifold.markets${contractPath(contract)}?t=${timeParam}`

  return `${tweetQuestion}\n\n${tweetDescription}\n\n${url}`
}