import { Box, Button, Chip } from '@mui/material'
import { useFieldArray } from 'react-hook-form'
import { FormTextField } from '../../HookForm'
import { RadioGroup } from '../../Input'
import { StyledGrid, StyledStack } from './Styles'

const Authors = ({
  control,
  selectedAuthor,
  setState,
  authorsSelect,
  userName,
  watch,
  setValue,
}) => {
  const { fields, append, remove } = useFieldArray({
    control,
    name: 'authors',
  })

  return (
    <Box>
      <RadioGroup
        row
        label="Authors"
        name="authors"
        required
        value={selectedAuthor}
        options={authorsSelect.map((item) => ({
          label: item?.label,
          value: item?.value,
        }))}
        onChange={(e) => {
          setState((s) => {
            s.selectedAuthor = e.target.value
          })
        }}
      />
      {selectedAuthor === 'singleAuthor' && (
        <Box sx={{ marginTop: 1 }}>
          <Chip variant="outlined" color="primary" label={userName} disabled />
        </Box>
      )}
      {selectedAuthor === 'multipleAuthors' && (
        <Box>
          <StyledStack direction={'row'} gap={1}>
            <FormTextField
              control={control}
              name="newAuthor"
              label="Author Name"
              required
            />
            <Button
              variant="text"
              color="primary"
              size="small"
              onClick={() => {
                append({ name: watch('newAuthor') })
                setValue('newAuthor', '')
              }}
            >
              + Add
            </Button>
          </StyledStack>

          <StyledGrid>
            {fields.map((author: any, index) => (
              <Chip
                key={author.id}
                variant="outlined"
                color="primary"
                label={author.name}
                onDelete={index === 0 ? null : () => remove(index)}
                disabled={index === 0}
              />
            ))}
          </StyledGrid>
        </Box>
      )}
    </Box>
  )
}

export default Authors
