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 { useTypedMutation } from '@inject/graphql/graphql'
import { Confirm } from '@inject/graphql/mutations'
import { timedFormatter } from '@inject/shared/components/StyledTag/Timestamp'
import type { FC } from 'react'
import { useMemo } from 'react'

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 [{ fetching: loading }, confirm] = useTypedMutation(Confirm)

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

  return (
    <div className={wrapper}>
      <ContentComponent
        content={content}
        teamId={teamId}
        exerciseId={exerciseId}
        inInstructor={inInstructor}
      />
      {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>
  )
}

export default InjectContent
