import { Button } from '@blueprintjs/core'
import { css } from '@emotion/css'
import type { FC, ReactNode } from 'react'
import { useMemo, useState } from 'react'
import { VIEW } from '../utilities'
import Label from './Label'

const wrapper = css`
  display: flex;
  flex-direction: column;
  height: 100%;
  gap: 0.5rem;
`

const titleWrapper = css`
  display: flex;
  align-items: stretch;
  gap: 0.5rem;
`

const button = css`
  box-shadow: none !important;
`

interface CardProps {
  tableView?: ReactNode | undefined
  plotView?: ReactNode | undefined
  label: string
}

const Card: FC<CardProps> = ({ tableView, plotView, label }) => {
  const [view, setView] = useState(tableView ? VIEW.TABLE : VIEW.PLOT)

  const { disabled, onClick, title } = useMemo(() => {
    if (!tableView)
      return {
        disabled: true,
        onClick: () => {},
        title: 'No table view available',
      }
    if (!plotView)
      return {
        disabled: true,
        onClick: () => {},
        title: 'No plot view available',
      }
    return {
      disabled: false,
      onClick: () =>
        setView(prev => (prev === VIEW.TABLE ? VIEW.PLOT : VIEW.TABLE)),
      title:
        view === VIEW.TABLE ? 'Switch to plot view' : 'Switch to table view',
    }
  }, [plotView, tableView, view])

  if (!tableView && !plotView) return <div />

  return (
    <div className={wrapper}>
      <div className={titleWrapper}>
        <Button
          icon={view === VIEW.TABLE ? VIEW.PLOT : VIEW.TABLE}
          disabled={disabled}
          onClick={onClick}
          title={title}
          className={button}
        />
        <Label text={label} />
      </div>

      <div style={{ overflow: 'auto', flex: 1 }}>
        {view === VIEW.TABLE ? tableView : plotView}
      </div>
    </div>
  )
}

export default Card
