import { useState, useEffect, useMemo } from 'react';
import PropTypes from 'prop-types';
import { Box, Typography, Switch, FormControlLabel, TextField, Button, Alert } from '@mui/material';
import { useSnackbar } from 'notistack';
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import { useNodeContext } from '../contexts/node';
import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
function SubServiceConfig({
  blocklet
}) {
  const {
    t
  } = useLocaleContext();
  const {
    api
  } = useNodeContext();
  const {
    enqueueSnackbar
  } = useSnackbar();
  const [enabled, setEnabled] = useState(false);
  const [domain, setDomain] = useState('');
  const [staticRoot, setStaticRoot] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  // Load initial config from blocklet settings
  // Only reload when blocklet DID changes to avoid infinite re-renders
  useEffect(() => {
    if (blocklet?.settings?.subService) {
      const config = blocklet.settings.subService;
      setEnabled(config.enabled || false);
      setDomain(config.domain || '');
      setStaticRoot(config.staticRoot || '');
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [blocklet?.meta?.did]);

  // Validate form - memoized to avoid re-renders
  const validationError = useMemo(() => {
    if (!enabled) return null;
    if (!domain) {
      return t('blocklet.subService.error.domainRequired');
    }

    // Basic domain format validation (allow both *.example.com and example.com)
    const domainPattern = /^(\*\.)?[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i;
    if (!domainPattern.test(domain)) {
      return t('blocklet.subService.error.domainFormat');
    }
    if (!staticRoot) {
      return t('blocklet.subService.error.staticRootRequired');
    }

    // Security: Prevent path traversal attacks
    // Reject paths containing ".." or starting with "/"
    if (staticRoot.includes('..') || staticRoot.startsWith('/')) {
      return t('blocklet.subService.error.invalidPath');
    }
    return null;
  }, [enabled, domain, staticRoot, t]);
  const isValid = validationError === null;

  // Check if the domain is a wildcard domain
  const isWildcard = domain.startsWith('*.');

  // Save configuration
  const handleSave = async () => {
    if (!isValid) {
      setError(validationError);
      return;
    }
    setLoading(true);
    setError('');
    try {
      const config = enabled ? {
        enabled: true,
        domain,
        staticRoot
      } : {
        enabled: false
      };
      await api.updateBlockletSettings({
        input: {
          did: blocklet.meta.did,
          subService: config
        }
      });
      enqueueSnackbar(t('blocklet.subService.saveSuccess'), {
        variant: 'success'
      });
    } catch (err) {
      setError(err.message || t('common.saveFailed'));
      enqueueSnackbar(t('blocklet.subService.saveFailed', {
        error: err.message
      }), {
        variant: 'error'
      });
    } finally {
      setLoading(false);
    }
  };
  return /*#__PURE__*/_jsxs(Box, {
    sx: {
      p: 2,
      maxWidth: 600
    },
    children: [/*#__PURE__*/_jsx(Typography, {
      variant: "h6",
      gutterBottom: true,
      children: t('blocklet.subService.title')
    }), /*#__PURE__*/_jsx(Typography, {
      variant: "body2",
      color: "text.secondary",
      sx: {
        mb: 2
      },
      children: t('blocklet.subService.description')
    }), error && /*#__PURE__*/_jsx(Alert, {
      severity: "error",
      sx: {
        mb: 2
      },
      children: error
    }), /*#__PURE__*/_jsxs(Box, {
      sx: {
        display: 'flex',
        flexDirection: 'column',
        gap: 2
      },
      children: [/*#__PURE__*/_jsx(FormControlLabel, {
        control: /*#__PURE__*/_jsx(Switch, {
          checked: enabled,
          onChange: e => setEnabled(e.target.checked)
        }),
        label: t('blocklet.subService.enable')
      }), enabled && /*#__PURE__*/_jsxs(_Fragment, {
        children: [/*#__PURE__*/_jsx(TextField, {
          fullWidth: true,
          required: true,
          label: t('blocklet.subService.domain'),
          placeholder: t('blocklet.subService.domainPlaceholder'),
          value: domain,
          onChange: e => setDomain(e.target.value),
          helperText: t('blocklet.subService.domainHelp')
        }), /*#__PURE__*/_jsx(TextField, {
          fullWidth: true,
          required: true,
          label: t('blocklet.subService.staticRoot'),
          placeholder: t('blocklet.subService.staticRootPlaceholder'),
          value: staticRoot,
          onChange: e => setStaticRoot(e.target.value),
          helperText: t('blocklet.subService.staticRootHelp')
        }), /*#__PURE__*/_jsxs(Alert, {
          severity: "info",
          children: [/*#__PURE__*/_jsx(Typography, {
            variant: "body2",
            sx: {
              fontWeight: 500
            },
            children: t('blocklet.subService.howItWorks')
          }), /*#__PURE__*/_jsxs(Typography, {
            variant: "body2",
            component: "ul",
            sx: {
              pl: 2,
              mt: 1
            },
            children: [isWildcard ? /*#__PURE__*/_jsxs(_Fragment, {
              children: [/*#__PURE__*/_jsx("li", {
                children: t('blocklet.subService.example1', {
                  relativePath: staticRoot || '{relativePath}'
                })
              }), /*#__PURE__*/_jsx("li", {
                children: t('blocklet.subService.example2', {
                  relativePath: staticRoot || '{relativePath}'
                })
              })]
            }) : /*#__PURE__*/_jsxs(_Fragment, {
              children: [/*#__PURE__*/_jsx("li", {
                children: t('blocklet.subService.singleDomainExample1', {
                  relativePath: staticRoot || '{relativePath}'
                })
              }), /*#__PURE__*/_jsx("li", {
                children: t('blocklet.subService.singleDomainExample2', {
                  relativePath: staticRoot || '{relativePath}'
                })
              })]
            }), /*#__PURE__*/_jsx("li", {
              children: t('blocklet.subService.spaSupport')
            })]
          })]
        })]
      }), /*#__PURE__*/_jsx(Box, {
        children: /*#__PURE__*/_jsx(Button, {
          variant: "contained",
          onClick: handleSave,
          disabled: loading || enabled && !isValid,
          children: loading ? t('blocklet.subService.saving') : t('blocklet.subService.save')
        })
      })]
    })]
  });
}
SubServiceConfig.propTypes = {
  blocklet: PropTypes.shape({
    meta: PropTypes.shape({
      did: PropTypes.string
    }),
    settings: PropTypes.shape({
      subService: PropTypes.shape({
        enabled: PropTypes.bool,
        domain: PropTypes.string,
        staticRoot: PropTypes.string
      })
    })
  }).isRequired
};
export default SubServiceConfig;