import { useRef } from 'react';
import { Box, Button, IconButton, Tooltip } from '@mui/material';
import { useMemoizedFn, useRequest } from 'ahooks';
import Datatable from '@arcblock/ux/lib/Datatable';
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import { useConfirm } from '@arcblock/ux/lib/Dialog';
import { Icon } from '@iconify/react';
import iconDeleteRounded from '@iconify-icons/material-symbols/delete-rounded';
import iconEditRounded from '@iconify-icons/material-symbols/edit-rounded';
import iconPreview from '@iconify-icons/material-symbols/preview';
import iconLockOutline from '@iconify-icons/material-symbols/lock-outline';
import Toast from '@arcblock/ux/lib/Toast';
import omit from 'lodash/omit';
import sortBy from 'lodash/sortBy';
import { useBlockletContext } from '../../contexts/blocklet';
import { useNodeContext } from '../../contexts/node';
import BlockletResponseHeaderPolicyItemDialog from './response-header-policy-item-dialog';
import { formatResponseHeaderPolicy } from './utils';
import { echoError } from './dom-utils';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
export default function BlockletResponseHeaderPolicy() {
  const {
    t,
    locale
  } = useLocaleContext();
  const {
    blocklet
  } = useBlockletContext();
  const {
    api
  } = useNodeContext();
  const did = blocklet?.meta?.did;
  const dialogRef = useRef(null);
  const datatableRef = useRef(null);
  const {
    confirmApi,
    confirmHolder
  } = useConfirm();
  const onTableChange = () => {};
  const dataState = useRequest(async () => {
    const {
      responseHeaderPolicies
    } = await api.getBlockletResponseHeaderPolicies({
      input: {
        did
      }
    });
    return sortBy(responseHeaderPolicies.map(item => formatResponseHeaderPolicy(item)), x => x.isProtected ? 1 : 0);
  });
  const dataList = dataState.data || [];
  const handleItemAdd = useMemoizedFn(() => {
    dialogRef.current.open(async (data, {
      close,
      done
    }) => {
      await echoError(async () => {
        await api.addBlockletResponseHeaderPolicy({
          input: {
            did,
            data
          }
        });
        Toast.success(t('common.succeeded'));
        dataState.run();
        close();
      });
      done();
    });
  });
  const handleItemView = useMemoizedFn(dataItem => {
    dialogRef.current.open((_, {
      close,
      done
    }) => {
      done();
      close();
    }, omit(dataItem, ['id']));
  });
  const handleItemEdit = useMemoizedFn(dataItem => {
    dialogRef.current.open(async (data, {
      close,
      done
    }) => {
      await echoError(async () => {
        await api.updateBlockletResponseHeaderPolicy({
          input: {
            did,
            data: {
              ...data,
              id: dataItem.id
            }
          }
        });
        Toast.success(t('common.succeeded'));
        dataState.run();
        close();
      });
      done();
    }, dataItem);
  });
  const handleItemDelete = useMemoizedFn(dataItem => {
    confirmApi.open({
      title: t('responseHeaderPolicy.delete.title'),
      content: t('responseHeaderPolicy.delete.description'),
      confirmButtonText: t('common.confirm'),
      confirmButtonProps: {
        color: 'error'
      },
      cancelButtonText: t('common.cancel'),
      onConfirm(close) {
        echoError(async () => {
          await api.deleteBlockletResponseHeaderPolicy({
            input: {
              did,
              id: dataItem.id
            }
          });
          Toast.success(t('common.succeeded'));
          dataState.run();
          close();
        });
      }
    });
  });
  const tableOptions = {
    sort: false,
    download: false,
    filter: false,
    print: false,
    search: false,
    viewColumns: false,
    expandableRowsOnClick: true,
    searchDebounceTime: 600,
    onRowClick(row, {
      dataIndex
    }, e) {
      if (datatableRef.current?.contains(e.target)) {
        const dataItem = dataList[dataIndex];
        handleItemView(dataItem);
      }
    }
  };
  const customButtons = [/*#__PURE__*/_jsx(Button, {
    size: "small",
    variant: "outlined",
    onClick: () => {
      dataState.run();
    },
    sx: {
      mr: 1
    },
    children: t('common.refresh')
  }, "refresh"), /*#__PURE__*/_jsx(Button, {
    size: "small",
    variant: "contained",
    onClick: handleItemAdd,
    children: t('common.add')
  }, "add")];
  const columns = [{
    label: t('common.name'),
    name: 'name',
    options: {
      // eslint-disable-next-line react/no-unstable-nested-components
      customBodyRenderLite(rowIndex) {
        const dataItem = dataList[rowIndex];
        const protectedEle = dataItem.isProtected ? /*#__PURE__*/_jsx(Tooltip, {
          title: "Built-in policy, can't edit",
          children: /*#__PURE__*/_jsx(Box, {
            component: Icon,
            icon: iconLockOutline,
            sx: {
              fontSize: 16
            }
          })
        }) : null;
        return /*#__PURE__*/_jsxs(Box, {
          sx: {
            display: 'flex',
            alignItems: 'center',
            gap: 0.5
          },
          children: [protectedEle, " ", dataItem.name]
        });
      }
    }
  }, {
    label: t('common.description'),
    name: 'description'
  }, {
    label: t('common.actions'),
    name: '',
    width: 100,
    align: 'center',
    verticalKeyAlign: 'center',
    options: {
      // eslint-disable-next-line react/no-unstable-nested-components
      customBodyRenderLite(rowIndex) {
        const dataItem = dataList[rowIndex];
        return /*#__PURE__*/_jsxs(Box, {
          sx: {
            display: 'flex',
            alignItems: 'center',
            gap: 0
          },
          onClick: e => e.stopPropagation(),
          children: [dataItem.isProtected ? /*#__PURE__*/_jsx(Tooltip, {
            title: t('common.view'),
            children: /*#__PURE__*/_jsx(IconButton, {
              size: "small",
              onClick: () => {
                handleItemView(dataItem, rowIndex);
              },
              children: /*#__PURE__*/_jsx(Icon, {
                icon: iconPreview,
                fontSize: 18
              })
            })
          }) : null, dataItem.isProtected ? null : /*#__PURE__*/_jsx(Tooltip, {
            title: t('common.edit'),
            children: /*#__PURE__*/_jsx(IconButton, {
              size: "small",
              onClick: () => {
                handleItemEdit(dataItem, rowIndex);
              },
              color: "success",
              children: /*#__PURE__*/_jsx(Icon, {
                icon: iconEditRounded,
                fontSize: 18
              })
            })
          }), dataItem.isProtected ? null : /*#__PURE__*/_jsx(Tooltip, {
            title: t('common.delete'),
            children: /*#__PURE__*/_jsx(IconButton, {
              size: "small",
              onClick: () => {
                handleItemDelete(dataItem, rowIndex);
              },
              color: "error",
              children: /*#__PURE__*/_jsx(Icon, {
                icon: iconDeleteRounded,
                fontSize: 18
              })
            })
          })]
        });
      }
    }
  }].filter(Boolean);
  return /*#__PURE__*/_jsxs(Box, {
    sx: {
      display: 'flex',
      flexDirection: 'column',
      gap: 2
    },
    ref: datatableRef,
    children: [/*#__PURE__*/_jsx(Datatable, {
      verticalKeyWidth: 100,
      locale: locale,
      title: t('responseHeaderPolicy.title'),
      data: dataList,
      columns: columns,
      customButtons: customButtons,
      options: tableOptions,
      loading: dataState.loading,
      onChange: onTableChange
    }), /*#__PURE__*/_jsx(BlockletResponseHeaderPolicyItemDialog, {
      ref: dialogRef
    }), confirmHolder]
  });
}