import { Flex } from '@citric/core'
import { LoadingCircular } from '@citric/ui'
import { JinjaRawContext } from '../context/JinjaContext'
import { useAscendInputsEffect, useComputedInputsEffect, useJinjaFormsInit } from './hooks'
import { JinjaFormModel } from './JinjaFormModel'

interface Props extends React.DetailedHTMLProps<React.FormHTMLAttributes<HTMLFormElement>, HTMLFormElement> {
  model: JinjaFormModel,
}

export const JinjaForm = ({ model, children, onSubmit, onReset, ...props }: Props) => {
  const status = useJinjaFormsInit()
  useComputedInputsEffect(Object.values(model.context.computedVariables), model.context)
  useAscendInputsEffect(model.context)
  
  if (status === 'pending') {
    return (
      <Flex alignItems="center" justifyContent="center" style={{ padding: '20px' }}>
        <LoadingCircular />
      </Flex>
    )
  }

  if (status === 'error') {
    throw new Error('There was an error while loading Python environment.')
  }

  return (
    <JinjaRawContext value={model.context as any}>
      <form
        onSubmit={(e) => {
          e.preventDefault()
          onSubmit?.(e)
          model.submit()
        }}
        onReset={(e) => {
          e.preventDefault()
          onReset?.(e)
          model.reset()
        }}
        {...props}
      >
        {children}
      </form>
    </JinjaRawContext>
  )
}
