import styled from '@emotion/styled';
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import SwitchControl from '@arcblock/ux/lib/Switch';
import { Box, Button, Divider, Stack } from '@mui/material';
import { Controller, useForm } from 'react-hook-form';
import { useState } from 'react';
import Toast from '@arcblock/ux/lib/Toast';
import { useCreation, useMemoizedFn } from 'ahooks';
import merge from 'lodash/merge';
import isEmpty from 'lodash/isEmpty';
import Section from '../../component/section';
import { useBlockletContext } from '../../contexts/blocklet';
import { useNodeContext } from '../../contexts/node';
import AuthTextVisualMode from './auth-text/visual-mode';
import { defaultConfig } from './auth-text/constants';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
const defaultForm = {
  showDidColor: true,
  showAppInfo: true
};
function Switch(props) {
  return /*#__PURE__*/_jsx(SwitchControl, {
    ...props,
    sx: {
      transform: 'scale(0.75)'
    }
  });
}
export default function DIDConnectSettings() {
  const {
    api
  } = useNodeContext();
  const {
    blocklet
  } = useBlockletContext();
  const did = blocklet?.meta?.did;
  const {
    control,
    reset
  } = useForm({
    defaultValues: merge({}, defaultForm, blocklet?.settings?.didConnect || {})
  });

  // action config is a json object
  const actionConfig = useCreation(() => {
    const config = blocklet?.settings?.actionConfig;
    return config && !isEmpty(config) ? config : defaultConfig;
  }, [blocklet?.settings?.actionConfig]);
  const {
    t
  } = useLocaleContext();
  const [openDialog, setOpenDialog] = useState(false);
  const handleSave = useMemoizedFn(async (fieldName, value) => {
    try {
      const currentData = {
        showDidColor: control._defaultValues?.showDidColor ?? defaultForm.showDidColor,
        showAppInfo: control._defaultValues?.showAppInfo ?? defaultForm.showAppInfo
      };
      currentData[fieldName] = value;
      const {
        blocklet: blockletChanged
      } = await api.configDidConnect({
        input: {
          did,
          didConnect: JSON.stringify(currentData)
        }
      });
      const defaultValues = Object.assign({}, defaultForm, blockletChanged?.settings?.didConnect || {});
      reset(defaultValues);
      Toast.success(t('common.configSuccess'));
    } catch (err) {
      Toast.error(err.message);
      reset(control._defaultValues);
    }
  });
  const handleCloseDialog = useMemoizedFn(() => {
    setOpenDialog(false);
  });
  const handleOpenDialog = useMemoizedFn(() => {
    setOpenDialog(true);
  });
  const handleSaveCustomConfig = useMemoizedFn(async config => {
    try {
      await api.configDidConnectActions({
        input: {
          did,
          actionConfig: config
        }
      });
      Toast.success(t('common.configSuccess'));
    } catch (err) {
      console.error(err);
      Toast.error(err.message);
    }
  });
  return /*#__PURE__*/_jsxs(Div, {
    children: [/*#__PURE__*/_jsxs(Stack, {
      direction: "column",
      sx: {
        gap: 4
      },
      children: [/*#__PURE__*/_jsxs(Box, {
        children: [/*#__PURE__*/_jsx(Box, {
          children: t('authentication.didConnect.basicSettings')
        }), /*#__PURE__*/_jsx(Divider, {
          sx: {
            my: 2
          }
        }), /*#__PURE__*/_jsxs(Stack, {
          sx: {
            gap: 2
          },
          children: [/*#__PURE__*/_jsx(Section, {
            title: t('authentication.didConnect.showDidColor'),
            sectionLeftSx: {
              width: '600px'
            },
            children: /*#__PURE__*/_jsx(Box, {
              sx: {
                alignSelf: 'flex-start'
              },
              children: /*#__PURE__*/_jsx(Controller, {
                name: "showDidColor",
                control: control,
                render: ({
                  field
                }) => {
                  return /*#__PURE__*/_jsx(Switch, {
                    ...field,
                    checked: field.value,
                    onChange: e => {
                      handleSave('showDidColor', e.target.checked);
                      field.onChange(e);
                    }
                  });
                }
              })
            })
          }), /*#__PURE__*/_jsx(Section, {
            title: t('authentication.didConnect.showAppInfo'),
            sectionLeftSx: {
              width: '600px'
            },
            children: /*#__PURE__*/_jsx(Box, {
              sx: {
                alignSelf: 'flex-start'
              },
              children: /*#__PURE__*/_jsx(Controller, {
                name: "showAppInfo",
                control: control,
                render: ({
                  field
                }) => {
                  return /*#__PURE__*/_jsx(Switch, {
                    ...field,
                    checked: field.value,
                    onChange: e => {
                      handleSave('showAppInfo', e.target.checked);
                      field.onChange(e);
                    }
                  });
                }
              })
            })
          })]
        })]
      }), /*#__PURE__*/_jsxs(Box, {
        children: [/*#__PURE__*/_jsx(Box, {
          children: t('authentication.didConnect.customSettings')
        }), /*#__PURE__*/_jsx(Divider, {
          sx: {
            my: 2
          }
        }), /*#__PURE__*/_jsx(Stack, {
          direction: "row",
          sx: {
            gap: 2
          },
          children: /*#__PURE__*/_jsx(Button, {
            variant: "outlined",
            onClick: handleOpenDialog,
            children: t('authentication.didConnect.configDialogTitle')
          })
        })]
      })]
    }), /*#__PURE__*/_jsx(AuthTextVisualMode, {
      open: openDialog,
      onClose: handleCloseDialog,
      onSave: handleSaveCustomConfig,
      initialConfig: actionConfig
    })]
  });
}
const Div = styled.div`
  max-width: 1536px;

  .advanced-config {
    border: 0;
    padding: 0;
  }

  .config-form {
    flex-grow: 1;
    overflow-y: auto;
    will-change: transform;

    &:first-child {
      margin: 0;
    }

    ${props => props.theme.breakpoints.down('md')} {
      width: 100%;
      flex-shrink: 0;
      padding: 0 24px;
      transform: translate(0, 0);
    }
  }

  .config-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .config-desc {
    font-weight: normal;
    font-size: 12px;
    color: #666;
  }

  .form-item {
    margin-top: 0;
  }
`;