import { useState } from 'react';
import { DeleteOutlineOutlined as DeleteOutlineOutlinedIcon, EditOutlined as EditOutlinedIcon, Add as AddIcon } from '@mui/icons-material';
import SearchIcon from '@mui/icons-material/Search';
import { Box, Button, IconButton, InputBase, Divider, Typography, alpha, Alert } from '@mui/material';
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import Empty from '@arcblock/ux/lib/Empty';
import Toast from '@arcblock/ux/lib/Toast';
import pickBy from 'lodash/pickBy';
import PropTypes from 'prop-types';
import LabelIcon from '@mui/icons-material/LocalOfferOutlined';
import LabelChip from './chip';
import LabelFormDialog from './dialog';
import weakKey from './utils';
import { useTeamContext } from '../../contexts/team';
import { useNodeContext } from '../../contexts/node';
import { formatError } from '../../util';
import { LabelsProvider, useLabels } from './context/context';
import { ConfirmProvider, useConfirm } from './context/confirm';
import LabelPicker from './picker/label';
import Labels from './label';
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
function LabelReassign({
  exclude = undefined,
  onChange = undefined
}) {
  const [value, setValue] = useState([]);
  const {
    t
  } = useLocaleContext();
  return /*#__PURE__*/_jsxs(Box, {
    sx: {
      minHeight: 200
    },
    children: [/*#__PURE__*/_jsx(Alert, {
      severity: "info",
      sx: {
        mb: 2
      },
      children: t('label.reassignTip')
    }), /*#__PURE__*/_jsx(Box, {
      sx: {
        display: 'flex',
        alignItems: 'center',
        gap: 1
      },
      children: /*#__PURE__*/_jsx(LabelPicker, {
        value: [value],
        onChange: v => {
          setValue(v);
          onChange?.(v[0]);
        },
        trigger: /*#__PURE__*/_jsxs(Button, {
          color: "inherit",
          variant: "outlined",
          startIcon: /*#__PURE__*/_jsx(LabelIcon, {
            style: {
              fontSize: 14
            }
          }),
          children: [/*#__PURE__*/_jsx(Box, {
            component: "span",
            sx: {
              mr: 1,
              whiteSpace: 'nowrap'
            },
            children: t('label.reassignTo')
          }), !!value.length && /*#__PURE__*/_jsx(Labels, {
            compact: false,
            labels: value
          })]
        }),
        multiple: false,
        excludes: [exclude]
      })
    })]
  });
}
LabelReassign.propTypes = {
  exclude: PropTypes.string,
  onChange: PropTypes.func
};
function LabelManager({
  onReload = () => {},
  ...rest
}) {
  const {
    t
  } = useLocaleContext();
  const {
    api
  } = useNodeContext();
  const {
    teamDid
  } = useTeamContext();
  const {
    confirm
  } = useConfirm();
  const {
    labels: data,
    refetch: run
  } = useLabels();
  const flattenedLabels = data || [];
  const [editingLabel, setEditingLabel] = useState(null);
  const [search, setSearch] = useState('');
  const filteredLabels = flattenedLabels.filter(x => `${x.id}-${x.title}`.toLowerCase().includes(search.toLowerCase()));
  const handleCreate = parentId => {
    if (!editingLabel) {
      setEditingLabel({
        title: 'New label',
        slug: 'new-label',
        parentId
      });
    }
  };
  const handleEdit = label => {
    if (editingLabel) {
      return;
    }
    setEditingLabel(label);
  };
  const handleSubmit = async payload => {
    const tag = pickBy(payload, value => value);
    if (!editingLabel) {
      return;
    }
    try {
      if (editingLabel.id) {
        await api.updateTag({
          input: {
            teamDid,
            tag
          }
        });
      } else {
        await api.createTag({
          input: {
            teamDid,
            tag
          }
        });
      }
      Toast.success(t('label.saveSuccess'));
      setEditingLabel(null);
      run();
      onReload();
    } catch (error) {
      Toast.error(formatError(error));
    }
  };
  const handleDelete = async node => {
    let moveTo;
    const proceed = await confirm({
      title: t('label.deleteTip', {
        name: node.title
      }),
      description: /*#__PURE__*/_jsxs(Box, {
        sx: {
          width: 540,
          maxWidth: '100%'
        },
        children: [/*#__PURE__*/_jsx(Typography, {
          variant: "body1",
          children: t('label.deleteDesc', {
            name: node.title
          })
        }), /*#__PURE__*/_jsx(Box, {
          sx: {
            py: 2,
            color: 'grey.800'
          },
          children: /*#__PURE__*/_jsx(LabelsProvider, {
            children: /*#__PURE__*/_jsx(LabelReassign, {
              exclude: node.id,
              onChange: v => {
                moveTo = v;
              }
            })
          })
        })]
      })
    });
    if (proceed) {
      const input = {
        teamDid,
        tag: node
      };
      if (moveTo) {
        input.moveTo = moveTo;
      }
      await api.deleteTag({
        input
      }).then(() => {
        run();
        Toast.success(t('label.deleteSuccess'));
        onReload();
      }).catch(error => {
        Toast.error(formatError(error));
      });
    }
  };
  return /*#__PURE__*/_jsxs(_Fragment, {
    children: [/*#__PURE__*/_jsxs(Box, {
      sx: {
        display: 'flex',
        flexDirection: 'column',
        gap: 2.5
      },
      ...rest,
      children: [/*#__PURE__*/_jsxs(Box, {
        sx: {
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between'
        },
        children: [/*#__PURE__*/_jsx(Typography, {
          variant: "h3"
        }), /*#__PURE__*/_jsxs(Box, {
          sx: {
            display: 'flex',
            alignItems: 'center',
            gap: 1
          },
          children: [/*#__PURE__*/_jsx(Box, {
            component: InputBase,
            value: search,
            onChange: e => setSearch(e.target.value),
            placeholder: t('label.search'),
            startAdornment: /*#__PURE__*/_jsx(SearchIcon, {}),
            sx: theme => ({
              width: 300,
              '& input': {
                p: 1,
                px: 4.5,
                borderRadius: 1,
                backgroundColor: theme.palette.mode === 'light' ? '#fff' : '#0d1117',
                transition: theme.transitions.create(['border-color', 'box-shadow']),
                border: `1px solid ${theme.palette.mode === 'light' ? '#eaecef' : '#30363d'}`,
                fontSize: 14,
                '&:focus': {
                  boxShadow: `0px 0px 0px 3px ${theme.palette.mode === 'light' ? alpha(theme.palette.primary.light, 0.4) : 'rgb(12, 45, 107)'}`,
                  borderColor: theme.palette.mode === 'light' ? theme.palette.primary.light : '#388bfd'
                }
              },
              '& .MuiSvgIcon-root': {
                position: 'absolute',
                left: 8,
                fontSize: 20,
                color: 'grey.700'
              }
            })
          }), /*#__PURE__*/_jsx(Button, {
            color: "primary",
            variant: "contained",
            startIcon: /*#__PURE__*/_jsx(AddIcon, {}),
            sx: {
              textTransform: 'none'
            },
            onClick: () => handleCreate(),
            children: t('label.create')
          })]
        })]
      }), /*#__PURE__*/_jsx(Divider, {}), /*#__PURE__*/_jsxs(Box, {
        sx: {
          display: 'flex',
          flexDirection: 'column',
          gap: 1
        },
        children: [filteredLabels.map(label => {
          return /*#__PURE__*/_jsxs(Box, {
            sx: {
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'space-between',
              py: 1,
              px: 2,
              border: 1,
              borderColor: 'grey.300',
              gap: 1,
              borderRadius: 1.5
            },
            children: [/*#__PURE__*/_jsx(Box, {
              children: /*#__PURE__*/_jsx(Box, {
                sx: {
                  display: 'flex',
                  flexWrap: 'wrap',
                  alignItems: 'center',
                  gap: 1
                },
                children: /*#__PURE__*/_jsx(Box, {
                  sx: {
                    display: 'inline-flex',
                    alignItems: 'center',
                    gap: 1,
                    py: 0.5,
                    fontSize: 14,
                    color: 'grey.700',
                    fontWeight: 'bold',
                    borderRadius: '4px'
                  },
                  children: /*#__PURE__*/_jsx(LabelChip, {
                    label: label
                  })
                })
              })
            }), /*#__PURE__*/_jsx(Box, {
              sx: {
                display: 'flex',
                gap: 0.5,
                flex: '0 0 auto'
              },
              children: /*#__PURE__*/_jsxs(Box, {
                sx: {
                  display: 'flex',
                  gap: 0.5
                },
                children: [/*#__PURE__*/_jsx(IconButton, {
                  color: "inherit",
                  size: "small",
                  sx: {
                    color: 'grey.500'
                  },
                  onClick: () => handleCreate(label.id),
                  children: /*#__PURE__*/_jsx(AddIcon, {
                    sx: {
                      fontSize: 20
                    }
                  })
                }), /*#__PURE__*/_jsx(IconButton, {
                  color: "inherit",
                  size: "small",
                  sx: {
                    color: 'grey.500'
                  },
                  onClick: () => handleEdit(label),
                  children: /*#__PURE__*/_jsx(EditOutlinedIcon, {
                    sx: {
                      fontSize: 18
                    }
                  })
                }), /*#__PURE__*/_jsx(IconButton, {
                  disabled: label.type === 'system',
                  size: "small",
                  sx: {
                    color: 'error.main'
                  },
                  onClick: () => handleDelete(label),
                  children: /*#__PURE__*/_jsx(DeleteOutlineOutlinedIcon, {
                    sx: {
                      fontSize: 20
                    }
                  })
                })]
              })
            })]
          }, label.id);
        }), filteredLabels?.length === 0 && /*#__PURE__*/_jsx(Box, {
          height: 300,
          children: /*#__PURE__*/_jsx(Empty, {
            children: t('label.noLabels')
          })
        })]
      })]
    }), /*#__PURE__*/_jsx(LabelFormDialog, {
      open: !!editingLabel,
      onClose: () => setEditingLabel(null),
      initialValue: editingLabel,
      onSubmit: handleSubmit
    }, weakKey(editingLabel))]
  });
}
LabelManager.propTypes = {
  onReload: PropTypes.func
};
function LabelManagerWrapper({
  ...rest
}) {
  return /*#__PURE__*/_jsx(ConfirmProvider, {
    children: /*#__PURE__*/_jsx(LabelsProvider, {
      children: /*#__PURE__*/_jsx(LabelManager, {
        ...rest
      })
    })
  });
}
LabelManagerWrapper.propTypes = {
  ...LabelManager.propTypes
};
export default LabelManagerWrapper;