import { Dialog, DialogTitle, DialogContent, DialogActions, Button } from '@mui/material';
import { useTranslation } from 'react-i18next';
import { PermissionManager } from './PermissionManager';
import { useEffect, useState } from 'react';

type PermissionModalProps = {
  open: boolean;
  onClose: () => void;
  value: Record<string, any>;
  onChange: (value: Record<string, any>) => void;
  onSave: () => void;
};
export const PermissionModal = ({ open, onClose, value, onChange, onSave }: PermissionModalProps) => {
  const { t } = useTranslation();
  return (
    <Dialog open={open} onClose={onClose}>
      <DialogTitle>{t('app.share')}</DialogTitle>
      <DialogContent sx={{ width: '400px' }}>
        <PermissionManager value={value} onChange={onChange} />
        <DialogActions>
          <Button onClick={onClose}>{t('Cancel')}</Button>
          <Button color='primary' onClick={onSave}>
            {t('Submit')}
          </Button>
        </DialogActions>
      </DialogContent>
    </Dialog>
  );
};

type UsePermissionModalProps = {
  /**
   * 保存回调
   */
  onSave: (values: Record<string, any>) => Promise<boolean>;
};
export const usePermissionModal = ({ onSave }: UsePermissionModalProps) => {
  const [open, setOpen] = useState(false);
  const [formData, setFormData] = useState<Record<string, any>>({});
  const onChange = (value: Record<string, any>) => {
    setFormData(value);
  };
  const _onSave = async () => {
    const res = await onSave(formData);
    if (res) {
      setOpen(false);
    }
  };
  const contextHolder = <PermissionModal open={open} onClose={() => setOpen(false)} value={formData} onChange={onChange} onSave={_onSave} />;
  return {
    open,
    setOpen: (open: boolean, fromData?: any) => {
      setOpen(open);
      if (open) {
        setFormData(fromData ?? {});
      }
    },
    setFormData: (values: any) => {
      setFormData({ ...formData, ...values });
    },
    contextHolder,
  };
};
