'use client';
import { useControllableValue } from 'ahooks';
import { Dialog as DialogPrimitive } from 'radix-ui';

import './index.css';
import { cn } from '@/lib';
import IconFont from '../iconFont';

type ModalProps = {
  open?: boolean;
  onOpenChange?: (open: boolean) => void;
  children?: React.ReactNode;
  trigger?: React.ReactNode;
  title?: string;
  classNames?: Partial<Record<'content' | 'overlay', string>>;
  destroyOnClose?: boolean;
};

export default function Modal(props: ModalProps) {
  const { children, trigger, title, classNames, destroyOnClose = true } = props;
  const [open, setOpen] = useControllableValue(props, {
    defaultValue: false,
    defaultValuePropName: 'defaultOpen',
    valuePropName: 'open',
    trigger: 'onOpenChange',
  });

  const hiden = destroyOnClose && !open;

  return (
    <DialogPrimitive.Root open={open} onOpenChange={setOpen} modal>
      {trigger && (
        <DialogPrimitive.Trigger
          className="cursor-pointer"
          onClick={() => setOpen(true)}
          asChild
        >
          {trigger}
        </DialogPrimitive.Trigger>
      )}
      {!hiden && (
        <DialogPrimitive.Portal>
          <DialogPrimitive.Overlay className="dialog-overlay" />
          <DialogPrimitive.Content
            className={cn('dialog-content w-125', classNames?.content)}
          >
            <div className="mb-7 flex justify-between">
              <DialogPrimitive.Title className="text-xl font-black">
                {title}
              </DialogPrimitive.Title>
              <DialogPrimitive.Close
                onClick={() => setOpen(false)}
                className="dialog-close-btn translate-x-2.5 -translate-y-2.5 cursor-pointer hover:opacity-80"
              >
                <IconFont type="icon-guanbi" size={30} />
              </DialogPrimitive.Close>
            </div>
            {children}
          </DialogPrimitive.Content>
        </DialogPrimitive.Portal>
      )}
    </DialogPrimitive.Root>
  );
}
