import ContentComponent from '@/components/ContentComponent'
import Done from '@/components/Done'
import type { ButtonProps } from '@blueprintjs/core'
import { Button } from '@blueprintjs/core'
import { css } from '@emotion/css'
import type {
  Confirmation,
  Content,
  RestrictedUserF,
} from '@inject/graphql/fragment-types'
import { Confirm } from '@inject/graphql/mutations'
import useBlockableMutation from '@inject/graphql/utils/useBlockableMutation'
import { timedFormatter } from '@inject/shared/components/StyledTag/Timestamp'
import type { FC } from 'react'
import { useMemo } from 'react'
import { alignRight } from './classes'

const wrapper = css`
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
  height: 100%;
`

interface InjectContentProps {
  logId: string
  content: Content
  confirmation?: Confirmation | null
  confirmed?: boolean | null
  confirmedBy?: RestrictedUserF | null
  timestampConfirmed?: string | null
  teamId: string
  exerciseId: string
  inInstructor: boolean
  onClose?: () => void
}

const InjectContent: FC<InjectContentProps> = ({
  logId,
  content,
  confirmation,
  confirmed,
  confirmedBy,
  timestampConfirmed,
  teamId,
  exerciseId,
  inInstructor,
  onClose,
}) => {
  const [running, { fetching: loading }, confirm] =
    useBlockableMutation(Confirm)

  const { disabled, title } = useMemo<ButtonProps>(() => {
    if (confirmed) {
      return {
        disabled: true,
        title: `Confirmed${confirmedBy ? ` by ${confirmedBy?.username}` : ''}${timestampConfirmed ? ` ${timedFormatter({ datetime: new Date(timestampConfirmed) })}` : ''}`,
      }
    }
    if (inInstructor) {
      return {
        disabled: true,
        title: 'Confirming injects is not allowed in the instructor view',
      }
    }
    if (!running) {
      return {
        disabled: true,
        title: 'The exercise had been paused/stopped',
      }
    }
    return {
      disabled: false,
      title: undefined,
    }
  }, [confirmed, confirmedBy, inInstructor, running, timestampConfirmed])

  return (
    <div className={wrapper}>
      <ContentComponent
        content={content}
        teamId={teamId}
        exerciseId={exerciseId}
        inInstructor={inInstructor}
      />
      {(onClose || confirmation) && (
        <div className={alignRight}>
          {onClose && <Button text='Close' onClick={onClose} />}
          {confirmation && (
            <Done done={!!confirmed} title={title}>
              <Button
                intent='primary'
                text={confirmation.text}
                onClick={() =>
                  confirm({ logId, teamId }).then(() => onClose?.())
                }
                loading={loading}
                disabled={disabled}
                title={title}
              />
            </Done>
          )}
        </div>
      )}
    </div>
  )
}

export default InjectContent
