import styles from './SettingBaseModal.module.scss';

import { memo, useContext, type ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
import { cn } from '@/lib/utils';
import { calModalWidth } from '@/c-utils/common';
import { AppContext } from '@/c-components/AppContext';
import { Button } from '@/components/ui/Button';
import { Loader2 } from 'lucide-react';
import { Dialog, DialogContent } from '@/components/ui/Dialog';

type SettingBaseModalProps = {
  open: any;
  children: ReactNode;
  onOk: any;
  onClose: any;
  defaultWidth?: string;
  title: any;
  header?: (t: any, title: any) => ReactNode;
  okText?: any;
  okDisabled?: boolean;
  okLoading?: boolean;
  className?: string;
  closeOnMaskClick?: boolean;
};

export const SettingBaseModal = ({
  open,
  children,
  onOk,
  onClose,
  defaultWidth = '100%',
  title,
  header = (t, title) => <div className={styles.header}>{title}</div>,
  okText,
  okDisabled = false,
  okLoading = false,
  className,
  closeOnMaskClick = true,
}: SettingBaseModalProps) => {
  const { t } = useTranslation();
  const { mobileStyle } = useContext(AppContext);

  function handleOpenChange(open: boolean) {
    if (!open) {
      onClose?.();
    }
  }

  return (
    <Dialog
      open={open}
      onOpenChange={handleOpenChange}
    >
      <DialogContent
        className={cn(styles.SettingBaseModal, className)}
        onInteractOutside={event => {
          if (!closeOnMaskClick) {
            event.preventDefault();
          }
        }}
      >
        <div
          style={{
            width: calModalWidth({
              inMobile: mobileStyle,
              width: defaultWidth,
            }),
          }}
          className={styles.modalWrapper}
        >
          {header(t, title || t('common.core.settings'))}
          {children}
          <div className={styles.btnWrapper}>
            <Button
              className={cn('w-full')}
              onClick={onOk}
              disabled={okDisabled || okLoading}
            >
              {okLoading ? (
                <Loader2 className='h-4 w-4 animate-spin mr-2' />
              ) : null}
              {okText || t('common.core.ok')}
            </Button>
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
};

export default memo(SettingBaseModal);
