import { Button, ButtonGroup, Card, Icon } from '@blueprintjs/core'
import { notify } from '@inject/shared/notification/engine'
import type { FC } from 'react'
import { memo, useCallback } from 'react'
import LearningActivityForm from '../LearningActivityForm'
import { deleteLearningActivity } from '../indexeddb/operations'
import { type LearningActivityInfo } from '../indexeddb/types'
import { getLearningActivityIcon } from '../utils'

interface LearningActivityProps {
  learningActivity: LearningActivityInfo
}

const LearningActivityItem: FC<LearningActivityProps> = ({
  learningActivity,
}) => {
  const handleDeleteButton = useCallback(
    async (activity: LearningActivityInfo) => {
      try {
        await deleteLearningActivity(activity.id)
      } catch (error) {
        notify(
          `Failed to delete learning activity '${activity.name}': ${error}`,
          JSON.stringify(error),
          {
            intent: 'danger',
          }
        )
      }
    },
    []
  )

  return (
    <Card style={{ display: 'flex', justifyContent: 'space-between' }}>
      <span style={{ height: '100%', flexGrow: 1 }}>
        <Icon
          icon={getLearningActivityIcon(learningActivity)}
          style={{ marginRight: '1rem' }}
        />
        {learningActivity.name}
      </span>
      <ButtonGroup>
        <LearningActivityForm
          learningActivity={learningActivity}
          learningObjectiveId={learningActivity.learningObjectiveId}
          buttonProps={{
            minimal: true,
            icon: 'edit',
            style: { marginRight: '1rem' },
          }}
        />
        <Button
          minimal
          icon='cross'
          onClick={() => handleDeleteButton(learningActivity)}
        />
      </ButtonGroup>
    </Card>
  )
}

export default memo(LearningActivityItem)
