import React from 'react';
import styled from 'styled-components';

import { Dash, DashType } from '../SaveDialog/useSaveDialog';
import { DashConfig, IframeConfig } from '../types';
import { UpdateDialog } from '../SaveDialog';
import { useWindow } from './hooks';
import ContentArea from './ContentArea';
import TitleBar from './TitleBar';

type DashWindowProps = {
  top: number;
  left: number;
  z_index: number;
};
export const DashWindow = styled.div.attrs((props: DashWindowProps) => ({
  style: {
    top: props.top + 'px',
    left: props.left + 'px',
    zIndex: props.z_index
  }
}))<DashWindowProps>`
  position: absolute;
  background: #f9f9fa;
  border: 1px solid rgba(51, 51, 51, 0.1);
  min-width: 2em;
  min-height: 4.2em;
  overflow: hidden;
  border-radius: 0.25rem;
`;

type WindowProps = {
  greatestZIndex: number;
  setZIndex: React.Dispatch<React.SetStateAction<number>>;
  setting: DashConfig | IframeConfig;
  children: React.ReactNode;
  dashType: DashType;
  activeIsClone?: boolean;

};

const Window = (props: WindowProps) => {
  const { setting, setZIndex, greatestZIndex, dashType, activeIsClone } = props;
  const [
    { windowRef, windowPosition, isSettingDialogOpen },
    { onMouseDown, onResizeStop, openSettingDialog, closeSettingDialog }
  ] = useWindow(greatestZIndex, setZIndex, setting);

  const isIframe = dashType === 'iframe';
  const globalIsClone =
    typeof (window as any).__ACTIVE_DASH_IS_CLONE === 'boolean'
      ? (window as any).__ACTIVE_DASH_IS_CLONE
      : false;
  const isCloneActive = activeIsClone != null ? activeIsClone : globalIsClone;

  const canMove = !isCloneActive;
  const canConfigure = !isCloneActive;


  const dashConfig: Dash = {
    id: setting.id,
    dashID: setting.content_id,
    refreshMinutes: setting.refresh_time,
    count: (setting as DashConfig)?.content_count || 10,
    type: dashType,
    chart_start: 0,
    chart_entities: 0,
    dashboardID: 0
  };
  return (
    <React.Fragment>
      <DashWindow
        z_index={windowPosition.z_index}
        ref={windowRef}
        top={windowPosition.top}
        left={windowPosition.left}
      >
        <TitleBar
          move={isCloneActive ? undefined : onMouseDown}
          openSettingDialog={isCloneActive ? undefined : openSettingDialog}
          hideConfig={isCloneActive}
          disableMove={isCloneActive}
          name={setting.name}
        />
        <ContentArea
          width={setting.position.width}
          height={setting.position.height}
          onResizeStop={onResizeStop}
          isHideOverflow={isIframe}
          disableResize={isCloneActive}
        >
          {props.children}
        </ContentArea>
      </DashWindow>
      <UpdateDialog
        dashConfig={dashConfig}
        position={setting.position}
        isOpen={isSettingDialogOpen}
        close={closeSettingDialog}
      />
    </React.Fragment>
  );
};

export default Window;
