import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import { Button, CircularProgress, Stack } from '@mui/material';
import { isObject } from 'lodash';
import type { EventHandler } from 'react';
import Dialog from '@arcblock/ux/lib/Dialog';
import { FormProvider, useForm } from 'react-hook-form';

import { isObjectContent } from '../../libs/util';
import MetadataForm from './form';

export default function MetadataEditor({
  data,
  loading,
  onSave,
  onCancel,
}: {
  data: any;
  loading: boolean;
  onSave: EventHandler<any>;
  onCancel: EventHandler<any>;
}) {
  const { t } = useLocaleContext();
  const metadata = data.metadata || {};
  const methods = useForm<any>({
    mode: 'onSubmit',
    defaultValues: {
      metadata:
        Object.keys(metadata).length < 1
          ? [{ key: '', value: '' }]
          : Object.keys(metadata).map((key: string) => ({
              key,
              value: isObject(metadata[key]) ? JSON.stringify(metadata[key]) : metadata[key],
            })),
    },
  });

  const { handleSubmit, reset } = methods;
  const onReset = (e: any) => {
    reset();
    onCancel(e);
  };
  const onSubmit = () => {
    handleSubmit(async (formData: any) => {
      const payload = {
        ...(formData || {}),
        metadata: Array.isArray(formData.metadata)
          ? formData.metadata.reduce((acc: any, x: any) => {
              acc[x.key] = isObjectContent(x.value) ? JSON.parse(x.value) : x.value;
              return acc;
            }, {})
          : [],
      };
      await onSave(payload);
      reset();
      onCancel(null);
    })();
  };

  return (
    <Dialog
      open
      disableEscapeKeyDown
      fullWidth
      onClose={() => onCancel(null)}
      title={t('common.metadata.edit')}
      className="base-dialog">
      <FormProvider {...methods}>
        <MetadataForm
          actions={
            <Stack direction="row">
              <Button size="small" color="primary" variant="outlined" sx={{ mr: 2 }} onClick={onReset}>
                {t('common.cancel')}
              </Button>
              <Button variant="contained" color="primary" size="small" disabled={loading} onClick={onSubmit}>
                {loading && <CircularProgress size="small" />} {t('common.save')}
              </Button>
            </Stack>
          }
          minHeight="400px"
        />
      </FormProvider>
    </Dialog>
  );
}
