import { Card, CardList } from '@blueprintjs/core'
import type { EmailThread } from '@inject/graphql/fragment-types'
import { useTypedQuery } from '@inject/graphql/graphql'
import { GetEmailDrafts } from '@inject/graphql/queries.client'
import notEmpty from '@inject/shared/utils/notEmpty'
import { type FC } from 'react'
import DraftLogCard from './DraftLogCard'

interface DraftLogCardsProps {
  teamId: string
  inInstructor?: boolean
  selectedEmailThreadId?: string
  onClick: (emailThread?: EmailThread | null) => void
}

const DraftLogCards: FC<DraftLogCardsProps> = ({
  teamId,
  inInstructor = false,
  selectedEmailThreadId,
  onClick,
}) => {
  const [{ data }] = useTypedQuery({
    query: GetEmailDrafts,
    variables: { instructor: inInstructor, teamId },
    requestPolicy: 'network-only',
  })
  const emailDrafts = data?.getEmailDrafts?.filter(notEmpty) || []

  return (
    <CardList bordered={false}>
      {emailDrafts.length > 0 ? (
        emailDrafts.map((emailDraft, index) => (
          <DraftLogCard
            key={index}
            teamId={teamId}
            isSelected={
              notEmpty(emailDraft.emailThreadId) &&
              emailDraft.emailThreadId === selectedEmailThreadId
            }
            emailDraft={emailDraft}
            onClick={onClick}
          />
        ))
      ) : (
        <Card>No drafts</Card>
      )}
    </CardList>
  )
}

export default DraftLogCards
