import { Button, ButtonGroup, Card } from '@blueprintjs/core'
import { notify } from '@inject/shared/notification/engine'
import type { FC } from 'react'
import { memo, useCallback } from 'react'
import LearningActivities from '../LearningActivities'
import LearningActivityForm from '../LearningActivityForm'
import LearningObjectiveForm from '../LearningObjectiveForm'
import { deleteLearningObjective } from '../indexeddb/operations'
import type { LearningObjectiveInfo } from '../indexeddb/types'

interface LearningObjectiveProps {
  learningObjective: LearningObjectiveInfo
}

const LearningObjectiveItem: FC<LearningObjectiveProps> = ({
  learningObjective,
}) => {
  const handleDeleteButton = useCallback(
    async (objective: LearningObjectiveInfo) => {
      try {
        await deleteLearningObjective(objective.id)
      } catch (error) {
        notify(
          `Failed to delete learning objective '${objective.name}': ${error}`,
          JSON.stringify(error),
          {
            intent: 'danger',
          }
        )
      }
    },
    []
  )

  return (
    <Card style={{ flexDirection: 'column' }}>
      <div
        style={{
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          width: '100%',
          padding: '0rem 1rem 1rem 0',
        }}
      >
        <span style={{ height: '100%', flexGrow: 1 }}>
          {learningObjective.name}
        </span>
        <ButtonGroup>
          <LearningObjectiveForm
            learningObjective={learningObjective}
            buttonProps={{
              minimal: true,
              icon: 'edit',
              style: { marginRight: '1rem' },
            }}
          />
          <Button
            minimal
            icon='cross'
            onClick={() => handleDeleteButton(learningObjective)}
          />
        </ButtonGroup>
      </div>
      <div style={{ width: '100%', paddingLeft: '2rem' }}>
        <LearningActivities learningObjectiveId={learningObjective.id} />
        <LearningActivityForm
          learningObjectiveId={learningObjective.id}
          buttonProps={{
            minimal: true,
            text: 'Add new learning activity',
            alignText: 'left',
            icon: 'plus',
            style: { padding: '1rem', width: '100%' },
          }}
        />
      </div>
    </Card>
  )
}

export default memo(LearningObjectiveItem)
