import { useState } from 'react';
import PropTypes from 'prop-types';
import { useForm, Controller } from 'react-hook-form';
import Dialog from '@mui/material/Dialog';
import DialogTitle from '@mui/material/DialogTitle';
import DialogContent from '@mui/material/DialogContent';
import DialogActions from '@mui/material/DialogActions';
import Button from '@mui/material/Button';
import TextField from '@mui/material/TextField';
import Box from '@mui/material/Box';
import Stack from '@mui/material/Stack';
import Alert from '@mui/material/Alert';
import Typography from '@mui/material/Typography';
import Checkbox from '@mui/material/Checkbox';
import FormControlLabel from '@mui/material/FormControlLabel';
import FormGroup from '@mui/material/FormGroup';
import Divider from '@mui/material/Divider';
import Card from '@mui/material/Card';
import IconButton from '@mui/material/IconButton';
import CircularProgress from '@mui/material/CircularProgress';
import FormHelperText from '@mui/material/FormHelperText';
import CloseIcon from '@mui/icons-material/Close';
import { OAUTH_SCOPES } from '@abtnode/constant';
import Toast from '@arcblock/ux/lib/Toast';
import { omitBy, isNil } from 'lodash';
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import { useNodeContext } from '../../contexts/node';
import { useTeamContext } from '../../contexts/team';
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
const defaultValues = {
  clientName: '',
  clientUri: '',
  redirectUris: '',
  scope: ['profile:read'],
  contacts: '',
  tosUri: '',
  policyUri: ''
};
export default function CreateOauthClient({
  onCreated,
  onClose
}) {
  const [loading, setLoading] = useState(false);
  const {
    t,
    locale
  } = useLocaleContext();
  const {
    api
  } = useNodeContext();
  const {
    teamDid
  } = useTeamContext();
  const {
    control,
    handleSubmit,
    formState: {
      errors
    },
    watch,
    setValue
  } = useForm({
    defaultValues,
    mode: 'onChange'
  });
  const selectedScopes = watch('scope');
  const handleScopeChange = scope => {
    if (scope === 'profile:read') return; // profile:read is always required

    setValue('scope', selectedScopes.includes(scope) ? selectedScopes.filter(s => s !== scope) : [...selectedScopes, scope]);
  };
  const onSubmit = async data => {
    setLoading(true);
    try {
      const payload = {
        ...data,
        redirectUris: data.redirectUris,
        contacts: data.contacts ? data.contacts.split(',').map(s => s.trim()) : [],
        scope: data.scope.join(' ')
      };
      await api.createOAuthClient({
        input: {
          teamDid,
          input: omitBy(payload, isNil)
        }
      });
      onCreated(payload);
    } catch (e) {
      Toast.error(e.message || 'Failed to create OAuth App');
    } finally {
      setLoading(false);
    }
  };
  return /*#__PURE__*/_jsxs(Dialog, {
    open: true,
    onClose: onClose,
    maxWidth: "md",
    fullWidth: true,
    children: [/*#__PURE__*/_jsxs(DialogTitle, {
      children: [t('oauth.client.register'), ' ', /*#__PURE__*/_jsx(IconButton, {
        onClick: onClose,
        sx: {
          position: 'absolute',
          right: 8,
          top: 8
        },
        children: /*#__PURE__*/_jsx(CloseIcon, {})
      })]
    }), /*#__PURE__*/_jsx(DialogContent, {
      children: /*#__PURE__*/_jsxs(Stack, {
        spacing: 4,
        sx: {
          mt: 2
        },
        children: [/*#__PURE__*/_jsx(Typography, {
          variant: "h6",
          gutterBottom: true,
          children: t('oauth.client.requiredInformation')
        }), /*#__PURE__*/_jsx(Box, {
          children: /*#__PURE__*/_jsx(Controller, {
            name: "clientName",
            control: control,
            rules: {
              required: t('oauth.client.validate.clientName'),
              minLength: {
                value: 3,
                message: t('oauth.client.validate.clientNameMinLength')
              }
            },
            render: ({
              field
            }) => /*#__PURE__*/_jsxs(_Fragment, {
              children: [/*#__PURE__*/_jsx(TextField, {
                size: "small",
                ...field,
                label: t('oauth.client.name'),
                required: true,
                fullWidth: true,
                placeholder: t('oauth.client.input.clientNamePlaceholder'),
                error: !!errors.clientName,
                helperText: errors.clientName?.message
              }), /*#__PURE__*/_jsx(FormHelperText, {
                children: t('oauth.client.helperText.clientName')
              })]
            })
          })
        }), /*#__PURE__*/_jsx(Box, {
          children: /*#__PURE__*/_jsx(Controller, {
            name: "clientUri",
            control: control,
            rules: {
              required: t('oauth.client.validate.clientUri'),
              pattern: {
                value: /^https?:\/\/.+/,
                message: t('oauth.client.validate.clientUriInvalid')
              }
            },
            render: ({
              field
            }) => /*#__PURE__*/_jsxs(_Fragment, {
              children: [/*#__PURE__*/_jsx(TextField, {
                size: "small",
                ...field,
                label: t('oauth.client.input.clientUri'),
                required: true,
                fullWidth: true,
                placeholder: t('oauth.client.input.clientUriPlaceholder'),
                error: !!errors.clientUri,
                helperText: errors.clientUri?.message
              }), /*#__PURE__*/_jsx(FormHelperText, {
                children: t('oauth.client.helperText.clientUri')
              })]
            })
          })
        }), /*#__PURE__*/_jsx(Box, {
          children: /*#__PURE__*/_jsx(Controller, {
            name: "redirectUris",
            control: control,
            rules: {
              required: t('oauth.client.validate.redirectUris'),
              pattern: {
                value: /^https?:\/\/.+/,
                message: t('oauth.client.validate.redirectUrisInvalid')
              }
            },
            render: ({
              field
            }) => /*#__PURE__*/_jsxs(_Fragment, {
              children: [/*#__PURE__*/_jsx(TextField, {
                size: "small",
                ...field,
                label: t('oauth.client.input.redirectUris'),
                required: true,
                fullWidth: true,
                placeholder: t('oauth.client.input.redirectUrisPlaceholder'),
                error: !!errors.redirectUris,
                helperText: errors.redirectUris?.message
              }), /*#__PURE__*/_jsxs(Box, {
                sx: {
                  display: 'flex',
                  gap: '2px'
                },
                children: [/*#__PURE__*/_jsx(FormHelperText, {
                  children: t('oauth.client.helperText.redirectUris')
                }), /*#__PURE__*/_jsx(FormHelperText, {
                  children: t('oauth.client.helperText.read')
                }), /*#__PURE__*/_jsx(FormHelperText, {
                  sx: {
                    color: 'info.main'
                  },
                  component: "a",
                  href: `https://www.arcblock.io/docs/blocklet-developer/${locale}/oauth-service`,
                  target: "_blank",
                  rel: "noopener noreferrer",
                  children: t('oauth.client.helperText.document')
                }), /*#__PURE__*/_jsx(FormHelperText, {
                  children: t('oauth.client.helperText.more')
                })]
              })]
            })
          })
        }), /*#__PURE__*/_jsxs(Card, {
          variant: "outlined",
          sx: {
            p: 2,
            display: 'none'
          },
          children: [/*#__PURE__*/_jsx(Typography, {
            variant: "subtitle2",
            gutterBottom: true,
            children: t('oauth.client.input.permissions')
          }), /*#__PURE__*/_jsx(Box, {
            sx: {
              border: '1px solid',
              borderColor: 'divider',
              borderRadius: 1,
              p: 2
            },
            children: /*#__PURE__*/_jsx(FormGroup, {
              children: Object.entries(OAUTH_SCOPES).map(([scope, description]) => /*#__PURE__*/_jsx(FormControlLabel, {
                control: /*#__PURE__*/_jsx(Checkbox, {
                  checked: selectedScopes.includes(scope),
                  onChange: () => handleScopeChange(scope),
                  disabled: scope === 'profile:read',
                  color: "primary"
                }),
                label: /*#__PURE__*/_jsx(Box, {
                  children: /*#__PURE__*/_jsx(Typography, {
                    variant: "body2",
                    sx: {
                      fontWeight: 500
                    },
                    children: description
                  })
                })
              }, scope))
            })
          })]
        }), /*#__PURE__*/_jsx(Divider, {}), /*#__PURE__*/_jsx(Typography, {
          variant: "h6",
          gutterBottom: true,
          children: t('oauth.client.optionalInformation')
        }), /*#__PURE__*/_jsx(Stack, {
          children: /*#__PURE__*/_jsx(Controller, {
            name: "contacts",
            control: control,
            rules: {
              pattern: {
                value: /^$|^[^@\s]+@[^@\s]+\.[^@\s]+(\s*,\s*[^@\s]+@[^@\s]+\.[^@\s]+)*$/,
                message: t('oauth.client.validate.contacts')
              }
            },
            render: ({
              field
            }) => /*#__PURE__*/_jsxs(_Fragment, {
              children: [/*#__PURE__*/_jsx(TextField, {
                size: "small",
                ...field,
                label: t('oauth.client.input.contacts'),
                fullWidth: true,
                placeholder: t('oauth.client.input.contactsPlaceholder'),
                error: !!errors.contacts,
                helperText: errors.contacts?.message
              }), /*#__PURE__*/_jsx(FormHelperText, {
                children: t('oauth.client.helperText.contacts')
              })]
            })
          })
        }), /*#__PURE__*/_jsxs(Stack, {
          direction: {
            xs: 'column',
            sm: 'row'
          },
          spacing: 2,
          children: [/*#__PURE__*/_jsx(Controller, {
            name: "tosUri",
            control: control,
            rules: {
              pattern: {
                value: /^$|^https?:\/\/.+/,
                message: t('oauth.client.validate.tosUriInvalid')
              }
            },
            render: ({
              field
            }) => /*#__PURE__*/_jsxs(Box, {
              sx: {
                width: '50%'
              },
              children: [/*#__PURE__*/_jsx(TextField, {
                size: "small",
                ...field,
                label: t('oauth.client.input.tosUri'),
                fullWidth: true,
                placeholder: t('oauth.client.input.tosUriPlaceholder'),
                error: !!errors.tosUri,
                helperText: errors.tosUri?.message
              }), /*#__PURE__*/_jsx(FormHelperText, {
                children: t('oauth.client.helperText.tosUri')
              })]
            })
          }), /*#__PURE__*/_jsx(Controller, {
            name: "policyUri",
            control: control,
            rules: {
              pattern: {
                value: /^$|^https?:\/\/.+/,
                message: t('oauth.client.validate.policyUriInvalid')
              }
            },
            render: ({
              field
            }) => /*#__PURE__*/_jsxs(Box, {
              sx: {
                width: '50%'
              },
              children: [/*#__PURE__*/_jsx(TextField, {
                size: "small",
                ...field,
                label: t('oauth.client.input.policyUri'),
                fullWidth: true,
                placeholder: t('oauth.client.input.policyUriPlaceholder'),
                error: !!errors.policyUri,
                helperText: errors.policyUri?.message
              }), /*#__PURE__*/_jsx(FormHelperText, {
                children: t('oauth.client.helperText.policyUri')
              })]
            })
          })]
        }), errors.error && /*#__PURE__*/_jsx(Alert, {
          severity: "error",
          children: errors.error.message
        })]
      })
    }), /*#__PURE__*/_jsxs(DialogActions, {
      children: [/*#__PURE__*/_jsx(Button, {
        onClick: onClose,
        children: t('common.cancel')
      }), /*#__PURE__*/_jsxs(Button, {
        onClick: handleSubmit(onSubmit),
        disabled: loading,
        variant: "contained",
        color: "primary",
        children: [loading ? /*#__PURE__*/_jsx(CircularProgress, {
          size: 20,
          sx: {
            mr: 1
          }
        }) : null, t('oauth.client.registerButton')]
      })]
    })]
  });
}
CreateOauthClient.propTypes = {
  onCreated: PropTypes.func.isRequired,
  onClose: PropTypes.func.isRequired
};