import { FC, useCallback, useEffect, useMemo, useState } from 'react'
import { useHistory } from 'react-router-dom'
import Select from 'react-select'
import styled from 'styled-components'

import { getUserInfo } from '../api'
import { CSMap } from '../CSMap'
import logos from '../logos.svg'
import { colors } from '../style-vars'
import { useSearchStr } from '../useSearch'

interface UInfo {
  name: string
  avatar: string
}

const AppWrapper = styled.div`
  height: 100vh;
  background-color: ${colors.bgMain};
  display: flex;
  flex-direction: column;
  align-items: center;
  min-width: 1280px;
  min-height: 820px;
  box-sizing: border-box;

  .mainArea {
    flex-grow: 1;
    width: 100%;
    display: flex;
    flex-direction: column;
  }
  .footerArea {
    height: 42px;
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    text-align: center;
    font-size: 12px;
    line-height: 18px;
    color: rgba(0, 0, 0, 0.4);
    width: 100%;
    transform: scale(0.95);

    & > div {
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .colorTip {
      margin-right: 8px;
      display: flex;
      align-items: center;
      border-radius: 4px;
      background-color: white;
      padding: 0 3px;
      box-shadow: 0 0 8px 0 rgba(0, 0, 0, 0.1);
    }
    .colorBlock {
      height: 12px;
      width: 5px;
      border-radius: 2px;
      margin-right: 2px;
    }
  }
`

const Header = styled.div`
  height: 60px;
  box-sizing: border-box;
  margin-top: 24px;
  flex-shrink: 0;
  width: 100%;
  text-align: center;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  white-space: nowrap;
  box-sizing: border-box;
  position: relative;
  z-index: 40;

  .title {
    font-size: 28px;
    font-weight: 600;
    color: ${colors.fgMain};
    height: 48px;
    line-height: 48px;
    display: flex;
    align-items: center;
    position: relative;
    z-index: 10;
  }

  .userLogo {
    position: absolute;
    top: 0;
    right: 44px;
    bottom: 0;
    padding-left: 24px;
    z-index: 12;
    display: flex;
    justify-content: flex-end;
    align-items: center;
  }
`

const Logos = styled.img`
  display: block;
  height: 16px;
  width: 125px;
  margin-left: 24px;
`

const views = [
  {
    value: 'vewBWpOYLm',
    label: 'R&D Customer',
  },
  {
    value: 'vewiNSBRTX',
    label: 'All Top',
  },
  // {
  //   value: 'veww5z6bL0',
  //   label: 'IBG Example',
  // },
  // {
  //   value: 'vewFPdAnhk',
  //   label: 'CMG Top Lighthouse',
  // },
  // {
  //   value: 'vewuboCz4o',
  //   label: 'IBG Top KA/SA',
  // },
  // {
  //   value: 'vew4IvDMLy',
  //   label: 'CBG Top KA/SA',
  // },
  {
    value: 'vewtUK5hLo',
    label: 'All Customer',
  },
]

const selectStyle = {
  menu: (provided: any) => ({
    ...provided,
    top: 'calc(100% - 12px)',
  }),
  option: (provided: any, state: any) => ({
    ...provided,
    color: state.isSelected ? '#E7EFFE' : '#232323',
    backgroundColor: state.isSelected ? '#2070F9' : 'transparent',
    display: 'flex',
    alignItems: 'center',
    fontSize: '20px',
    lineHeight: '40px',
    height: 40,

    '&:hover': {
      backgroundColor: state.isSelected ? '#2070F9' : '#E7EFFE',
      cursor: 'pointer',
    },
  }),
  control: () => ({
    minWidth: 320,
    display: 'flex',
    alignItems: 'center',
  }),
  singleValue: (provided: any, state: any) => {
    const opacity = state.isDisabled ? 0.5 : 1
    const transition = 'opacity 300ms'

    return { ...provided, opacity, transition }
  },
  indicatorSeparator: () => ({
    display: 'none',
  }),
  menuList: (provided: any) => ({
    ...provided,
    maxHeight: 600,
  }),
}

const UserInfo = styled.div`
  display: block;
  height: 20px;
  max-width: 200px;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  .avatar {
    height: 20px;
    width: 20px;
    flex-shrink: 0;
    border-radius: 10px;
    display: block;
    margin-right: 8px;
  }
  .name {
    height: 16px;
    line-height: 16px;
    font-size: 12px;
    white-space: nowrap;
    flex-grow: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    color: rgba(0, 0, 0, 0.4);
  }
`

export const MainPage: FC = () => {
  const his = useHistory()
  const [vid] = useSearchStr(['vid'])
  const viewId = useMemo(() => {
    return vid || views[0].value
  }, [vid])
  const [uInfo, setUInfo] = useState<UInfo | null>(null)
  const handleViewChange = useCallback(
    (val) => {
      his.push(`/?vid=${val.value}`)
    },
    [his],
  )

  useEffect(() => {
    ;(async () => {
      const userInfo = await getUserInfo()
      if (userInfo?.name && userInfo?.avatarMiddle) {
        setUInfo({
          name: userInfo?.name,
          avatar: userInfo?.avatarMiddle,
        })
      }
    })()
  }, []) // eslint-disable-line

  return (
    <AppWrapper>
      <Header>
        <div className="title">
          <div className="titlePrefix">PingCAP Customer Success: </div>
          <Select
            styles={selectStyle}
            options={views}
            defaultValue={views.find((v) => v.value === viewId)}
            onChange={handleViewChange}
          />
        </div>
        <div className="userLogo">
          {uInfo ? (
            <UserInfo>
              <img className="avatar" src={uInfo?.avatar} alt="avatar" />
              <div className="name">{uInfo?.name || '-'}</div>
            </UserInfo>
          ) : null}
          <Logos src={logos} alt="PingCAP & TiDB logo" />
        </div>
      </Header>
      <div className="mainArea">
        <CSMap viewId={viewId} />
      </div>
      <div className="footerArea">
        <div className="footerAreaTips">
          双击图中任一块色块（含有客户）或左下"未分类"块可以放大查看，放大后再次双击复原，列表显示不全可以滚动（滚动条隐藏了）
        </div>
        <div>
          每一项客户业务前的颜色块表示停留在该列的时长(如内有人名，表示 PM)：
          <div className="colorTip">
            <div className="colorBlock" style={{ backgroundColor: '#4ADE80' }} />
            {`NEW: <7Days`}
          </div>
          <div className="colorTip">
            <div className="colorBlock" style={{ backgroundColor: 'rgba(0,5,8,0.1)' }} />
            {`NORMAL: 7-60Days`}
          </div>
          <div className="colorTip">
            <div className="colorBlock" style={{ backgroundColor: '#FACC15' }} />
            {`WARNING: >60Days`}
          </div>
          <div className="colorTip">
            <div className="colorBlock" style={{ backgroundColor: '#F87171' }} />
            {`ALERT: >180Days`}
          </div>
          <div className="colorTip">
            <div className="colorBlock" style={{ backgroundColor: '#BE123C' }} />
            {`PANIC: >365Days`}
          </div>
        </div>
      </div>
    </AppWrapper>
  )
}
