import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import { AddOutlined, DeleteOutlineOutlined } from '@mui/icons-material';
import { Box, Button, IconButton, TextField, Typography } from '@mui/material';
import { get } from 'lodash';
import { Controller, useFieldArray, useFormContext } from 'react-hook-form';

export default function MetadataForm() {
  const { t } = useLocaleContext();
  const {
    control,
    formState: { errors },
  } = useFormContext();
  const features = useFieldArray({ control, name: 'features' });
  return (
    <Box sx={{ width: 1 }}>
      <Typography>{t('admin.product.features.label')}</Typography>
      {features.fields.map((feature, index) => (
        <Box
          key={feature.id}
          sx={{ width: 1, gap: 1, display: 'flex', alignItems: 'center', justifyContent: 'space-between', mt: 2 }}>
          <Controller
            render={({ field }) => (
              <TextField
                {...field}
                sx={{ flex: 1, width: 'calc(100% - 60px)' }}
                size="small"
                error={!!get(errors, field.name)}
                helperText={get(errors, field.name)?.message as string}
                slotProps={{
                  htmlInput: { maxLength: 64 },
                }}
              />
            )}
            rules={{ maxLength: { value: 64, message: t('common.maxLength', { len: 64 }) } }}
            name={`features.${index}.name`}
            control={control}
          />
          <IconButton
            size="small"
            onClick={() => features.remove(index)}
            sx={{
              border: '1px solid',
              borderColor: 'divider',
              borderRadius: 1,
              padding: '8px',
            }}>
            <DeleteOutlineOutlined color="error" sx={{ opacity: 0.75 }} />
          </IconButton>
        </Box>
      ))}
      <Box
        sx={{
          mt: features.fields.length ? 2 : 1,
        }}>
        <Button
          size="small"
          variant="outlined"
          color="primary"
          sx={{ color: 'text.primary' }}
          onClick={() => features.append({ name: '' })}>
          <AddOutlined fontSize="small" /> {t('admin.product.features.add')}
        </Button>
      </Box>
    </Box>
  );
}
