import { Button, Input } from 'antd'
import { FC, useCallback, useEffect, useState } from 'react'
import ReactModal from 'react-modal'
import { toast } from 'react-toastify'
import styled from 'styled-components'

import { associateHealthDoc } from '../api'
import Associate from './Associate'

ReactModal.setAppElement('#root')

interface TrackDocModalProps {
  isOpen: boolean
  url: string
  recordId?: string
  onRequestClose: () => void
  onUrlChange: (url: string, rid: string) => void
}

enum Status {
  LOCK = 'lock',
  UNLOCK = 'UNLOCK',
  EMPTY = 'EMPTY',
}

const StyledBtn = styled(Button)`
  &&& {
    margin-left: 24px;
    padding-right: 24px;
    padding-left: 24px;
  }
`

const ContentWrapper = styled.div`
  position: relative;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;

  .content {
    flex-grow: 1;
    position: relative;
    z-index: 1;
  }
  .form {
    position: relative;
    z-index: 2;
    height: 80px;
    flex-shrink: 0;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 32px;
    box-shadow: 0 -2px 12px 2px rgba(0, 0, 0, 0.1);
  }
`

export const TrackDocModal: FC<TrackDocModalProps> = ({
  isOpen,
  recordId = '',
  url,
  onRequestClose,
  onUrlChange,
}) => {
  const [urlInstant, setUrlInstant] = useState(url)
  const [status, setStatus] = useState<Status>(!!url ? Status.LOCK : Status.EMPTY)
  const [isAssociating, setIsAssociating] = useState(false)
  const changeUrlInstant = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
    const val = e.target.value
    setUrlInstant(val.trim())
  }, [])
  const confirm = useCallback(async () => {
    if (status === Status.LOCK) {
      setStatus(Status.UNLOCK)
    } else {
      if (!urlInstant || !urlInstant.match(/^https?:\/\//)) {
        toast.warning('必须指定以 https:// 开头的完整URL')
        return
      }
      setIsAssociating(true)
      try {
        const r = await associateHealthDoc(recordId, urlInstant.trim())
        if (!r) {
          throw new Error('Something wrong')
        }
        onUrlChange(urlInstant.trim(), recordId)
        toast.success(status === Status.UNLOCK ? '修改成功' : '关联成功')
        setStatus(Status.LOCK)
      } catch {
        toast.error('关联失败')
      } finally {
        setIsAssociating(false)
      }
    }
  }, [recordId, status, urlInstant, onUrlChange])
  const cancelModify = useCallback(() => {
    setUrlInstant(url || '')
    setStatus(url ? Status.LOCK : Status.EMPTY)
  }, [url])

  useEffect(() => {
    setUrlInstant(url)
    setStatus(!!url ? Status.LOCK : Status.EMPTY)
  }, [url])

  return (
    <ReactModal
      onRequestClose={onRequestClose}
      isOpen={isOpen}
      closeTimeoutMS={isOpen ? 300 : 0}
      parentSelector={() => document.querySelector('#overlay') || document.body}
      preventScroll={true}
      style={{
        overlay: {
          position: 'fixed',
          top: 0,
          left: 0,
          right: 0,
          bottom: 0,
          zIndex: 200,
          backgroundColor: 'rgba(0, 0, 0, 0.718)',
        },
        content: {
          position: 'absolute',
          top: '96px',
          left: '48px',
          right: '48px',
          bottom: '48px',
          border: '1px solid #ccc',
          boxSizing: 'border-box',
          background: '#fff',
          WebkitOverflowScrolling: 'touch',
          borderRadius: '4px',
          outline: 'none',
          padding: '0',
        },
      }}
    >
      <ContentWrapper>
        <div className="content">
          {!!url ? (
            <iframe
              width="100%"
              height="100%"
              title="Business Health Record"
              frameBorder="0"
              src={url}
            />
          ) : (
            <Associate />
          )}
        </div>
        {recordId ? (
          <div className="form">
            <Input
              size="large"
              value={urlInstant}
              onChange={changeUrlInstant}
              disabled={status === Status.LOCK}
              placeholder="输入客户档案文档的 URL 链接，点击右侧按钮建立关联"
              autoFocus={true}
            />
            <StyledBtn size="large" type="primary" onClick={confirm} disabled={isAssociating}>
              {status === Status.LOCK ? '修改' : status === Status.UNLOCK ? '确认' : '关联'}
            </StyledBtn>
            {status === Status.UNLOCK ? (
              <StyledBtn size="large" onClick={cancelModify} disabled={isAssociating}>
                取消
              </StyledBtn>
            ) : null}
          </div>
        ) : null}
      </ContentWrapper>
    </ReactModal>
  )
}
