import * as React from 'react';
import { CheckCircle, ExclaimTriangle, ExclaimCircle } from '@teachable/icons'
import debounce from 'lodash/debounce'
import { Truncate } from './truncate'

const { useState, useEffect, useMemo, useCallback, useRef } = React

// TODO: make usePromise a util in the monorepo
interface LinkCheckProps {
  url: string
  onConfirm: (url: string) => void
}

enum PromiseState {
  PENDING,
  ERROR,
  COMPLETE
}

enum UrlStatus {
  OK = 'OK',
  ERROR = 'ERROR',
  REDIRECT = 'REDIRECT'
}

const parentStyle = {
  marginTop: '10px',
  display: 'flex',
}
const textStyle = {
  alignSelf: 'center'
}

export const LinkCheck = ({ url, onConfirm }: LinkCheckProps) => {
  const isMounted = useRef(true)
  const [promiseState, setPromiseState] = useState(PromiseState.PENDING)
  const [urlStatus, setUrlStatus] = useState(UrlStatus.OK)
  const [redirectUrl, setRedirectUrl] = useState('')

  const debouncedPromise = useMemo(() => debounce((params: URLSearchParams) =>
    fetch(`/admin/api/tracking_links/test?${params.toString()}`)
      .then(res => res.ok ? res.json() : Promise.reject(res))
      .then(({ status, redirect_url }) => {
        if (isMounted.current) {
          setPromiseState(PromiseState.COMPLETE)
          setUrlStatus(status)
          setRedirectUrl(redirect_url)
        }
      })
      .catch((e) => {
        if (isMounted.current) {
          setPromiseState(PromiseState.ERROR)
        }
      }),
  500), [])

  const handleConfirmClick = useCallback(() => onConfirm(redirectUrl), [redirectUrl])

  useEffect(() => {
    isMounted.current = true
    if (url) {
      // ensure url is valid
      try {
        new URL(url)
      } catch {
        return undefined
      }
      setPromiseState(PromiseState.PENDING)
      const params = new URLSearchParams({ url })
      debouncedPromise(params)
    }
    return () => isMounted.current = false
  }, [url])

  switch (promiseState) {
    case PromiseState.PENDING: {
      return (
        <div style={parentStyle}>
          <div style={textStyle}>
            Preparing to check your link, please wait
          </div>
        </div>
      )
    }
    case PromiseState.COMPLETE: {
      switch (urlStatus) {
        case UrlStatus.OK: {
          return (
            <div style={parentStyle}>
              <CheckCircle />
              <div style={textStyle}>
                &nbsp;Your link doesn't redirect!
              </div>
            </div>
          )
        }
        case UrlStatus.REDIRECT: {
          return (
            <div style={parentStyle}>
              <ExclaimTriangle style={{ cursor: 'pointer' }} onClick={handleConfirmClick} />
              <div style={textStyle}>
                &nbsp;Your link redirects to <Truncate length={50}>{redirectUrl}</Truncate>.
                Click the icon to change it to the destination
              </div>
            </div>
          )
        }
      }
    }
  }
  return (
    <div style={parentStyle}>
      <ExclaimCircle />
      <div style={textStyle}>
        &nbsp;We're getting an error when trying to check your link
      </div>
    </div>
  )
}
