import React, { useState, useEffect } from 'react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { Button } from '../Button';
import { CloseBtn } from '../CloseBtn';
import { Modal } from '../Modal';
import { IItemsAlertBtn, IItemsAlert } from './Alert.interface';
import { AlertObs } from './Alert.obs';

export const Alert: React.FunctionComponent<any> & { show: (options: IItemsAlert) => void } = function Alert(): any {
   const [opened, setOpened] = useState(false);
   const [items, setItems] = useState<Partial<IItemsAlert>>({});

   function close(): void {
      setOpened(false);
      if (items.onClose) items.onClose();
   }

   useEffect(() => {
      const obs = AlertObs.observable.subscribe((value) => {
         setItems(value);
         setOpened(true);
      });

      return () => obs.unsubscribe();
   }, []);

   function onPress(btn: IItemsAlertBtn): void {
      if (btn.onPress) btn.onPress();
      close();
   }

   return (
      <Modal show={opened} onRequestClose={close}>
         <Modal.Body className="alert-container p-4">
            <div className="float-right absolute">
               <CloseBtn onClick={() => close()} size={22} />
            </div>
            <div className="text-center">
               <h1 className="m-0 p-0">
                  {items.icon && <FontAwesomeIcon icon={items.icon} color={items.iconColor} />}
               </h1>
               <div className="p-4">
                  {items.title &&
                     (typeof items.title === 'string' ? (
                        <h4>
                           <div style={{ color: items.titleColor || 'black' }}>{items.title}</div>
                        </h4>
                     ) : (
                        items.title
                     ))}

                  <div className="description">{items.message}</div>
               </div>
               <div className="d-flex justify-center justify-content-center">
                  {items.buttons &&
                     items.buttons.map((btn, index) => (
                        <div className="pr-2" key={`btn-${index}`}>
                           <Button
                              onClick={() => onPress(btn)}
                              bgColor={btn.bgColor}
                              data-testid={`alert-btn-${index}`}
                           >
                              {btn.text}
                           </Button>
                        </div>
                     ))}
               </div>
            </div>
         </Modal.Body>
      </Modal>
   );
} as any;

Alert.show = (options: IItemsAlert) => {
   AlertObs.set(options);
};
