import React, { useState } from 'react';
import { ExpandDropdownIcon } from '../../';
import {
  DrawerContainer,
  DrawerHeader,
  DrawerHeaderLeftContent,
  ExpandedContentContainer,
  ExpandIconContainer,
} from './styles';
import {
  ExpandableDrawerProps,
  ExpandableDrawerDirection,
} from './typesAndConfig';
import { useSpring } from 'react-spring';

//Expandable Drawer renders content passed in when clicked and expanded.
// Make sure that content passed in is width 100% in order to fill the entire Drawer.
// The most common use case is a floating bottom Drawer on mobile.

// this is the max that we are using as max-height for the animation
const MAX_DRAWER_CONTENT_HEIGHT = '1000px';

const ExpandableDrawer: React.FC<ExpandableDrawerProps> = ({
  expandedContent,
  expandDirection,
  stickToBottom,
  headerHeight,
  headerLeftContent,
  onExpand,
  onClose,
}) => {
  const [isExpanded, setIsExpanded] = useState(false);

  const expand = useSpring({
    config: { friction: 30 },
    maxHeight: isExpanded ? MAX_DRAWER_CONTENT_HEIGHT : '0px',
  });

  const spin = useSpring({
    transform: isExpanded ? 'rotate(180deg)' : 'rotate(0deg)',
  });

  return (
    <DrawerContainer stickToBottom={stickToBottom}>
      {isExpanded && expandDirection === ExpandableDrawerDirection.UP && (
        <ExpandedContentContainer
          $expandDirection={expandDirection}
          $isExpanded={isExpanded}
          style={expand}
          $stickToBottom={stickToBottom}
        >
          {expandedContent}
        </ExpandedContentContainer>
      )}
      <DrawerHeader
        stickToBottom={stickToBottom}
        onClick={() => {
          if (!isExpanded && onExpand) {
            onExpand();
          }
          if (isExpanded && onClose) {
            onClose();
          }
          setIsExpanded(!isExpanded);
        }}
        headerHeight={headerHeight}
        isExpanded={isExpanded}
        expandDirection={expandDirection}
      >
        <DrawerHeaderLeftContent>{headerLeftContent}</DrawerHeaderLeftContent>
        <ExpandIconContainer style={spin}>
          <ExpandDropdownIcon
            height={24}
            width={24}
            arrowPointsUp={
              (stickToBottom &&
                expandDirection === ExpandableDrawerDirection.DOWN) ||
              expandDirection === ExpandableDrawerDirection.UP
            }
          />
        </ExpandIconContainer>
      </DrawerHeader>
      {isExpanded && expandDirection === ExpandableDrawerDirection.DOWN && (
        <ExpandedContentContainer
          $expandDirection={expandDirection}
          $isExpanded={isExpanded}
          style={expand}
          $stickToBottom={stickToBottom}
        >
          {expandedContent}
        </ExpandedContentContainer>
      )}
    </DrawerContainer>
  );
};

export { ExpandableDrawerDirection, ExpandableDrawer };
