import React, { AllHTMLAttributes, useEffect, useState } from 'react';
import { Close20 } from '@carbon/icons-react';
import { twMerge } from 'tailwind-merge';

import Block from '../../atoms/Block';
import Scrollbars from '../../elements/Scrollbars';
import style from '../../../style';

export interface ModalProps {
    show: boolean;
    onClose: () => void;
    className?: string;
    hasBackdrop?: boolean;
    children?: React.ReactNode;
}

export interface ModalHeaderProps extends AllHTMLAttributes<HTMLDivElement> {
    title: string;
    subtitle?: string;
    onClose?: () => void;
}

export const Modal: React.FC<ModalProps> = (props) => {
    const { className, children, show, onClose, hasBackdrop } = props;

    const [isShown, setIsShown] = useState(show);

    useEffect(() => {
        setIsShown(show);
    }, [show]);

    if (!isShown) {
        return <></>;
    }

    return hasBackdrop ? (
        <Block
            onClick={() => {
                onClose();
            }}
            className={`${style.modal.backdrop} ${className}`}
        >
            <Block onClick={(e) => e.stopPropagation()} className={`${style.modal.root} `}>
                {children}
            </Block>
        </Block>
    ) : (
        <Block onClick={(e) => e.stopPropagation()} className={`${style.modal.root} ${className}`}>
            {children}
        </Block>
    );
};

export const ModalHeader: React.FC<ModalHeaderProps> = (props) => {
    const { title, subtitle, className, children, onClose } = props;

    return (
        <Block className={` ${style.modal.header} ${className} `}>
            <Block className="flex-auto">
                <Block className={twMerge(`${style.modal.title}`)}>{title}</Block>
                {subtitle && <Block className={twMerge(`${style.modal.subtitle}`)}>{subtitle}</Block>}
            </Block>
            {onClose && (
                <Close20
                    className="cursor-pointer shrink-0"
                    onClick={() => {
                        onClose();
                    }}
                />
            )}
            {children}
        </Block>
    );
};

export const ModalBody: React.FC<AllHTMLAttributes<HTMLDivElement>> = (props) => {
    const { className, children } = props;

    return <Block className={`${style.modal.body} ${className}`}>{children}</Block>;
};

export const ModalContent: React.FC<AllHTMLAttributes<HTMLDivElement>> = (props) => {
    const { className, children } = props;

    return (
        <Block className={`${style.modal.content} ${className}`}>
            <Scrollbars translateContentSize={true}>{children}</Scrollbars>
        </Block>
    );
};

export const ModalFooter: React.FC<AllHTMLAttributes<HTMLDivElement>> = (props) => {
    const { className, children } = props;

    return <Block className={`flex ${className}`}>{children}</Block>;
};
