import React, { Fragment, useState, useEffect } from 'react'
import { Transition } from '@headlessui/react'
import { XIcon } from '@heroicons/react/solid'
import { CheckCircleIcon, XCircleIcon } from '@heroicons/react/outline'

import '../../tailwind.css'

export interface ToastProps {
  /** The content that should appear in the toast message */
  content: string
  /** The length of time in milliseconds the toast message should persist */
  duration?: number
  /** Display an error toast. */
  error?: boolean
  // Callback when clicked
  onDismiss?(): void
}

export const DEFAULT_TOAST_DURATION = 5000

export const Toast = ({ content, duration, error, onDismiss }: ToastProps) => {
  const [show, setShow] = useState(true)

  // useEffect(() => {
  //     let timeoutDuration = duration || DEFAULT_TOAST_DURATION;

  //     const timer = setTimeout(onDismiss, timeoutDuration);

  //     return () => {
  //         clearTimeout(timer);
  //     };
  // }, [duration, onDismiss]);

  const dismissMarkup = (
    <button
      className="inline-flex rounded-lg bg-white text-secondary-text hover:opacity-90 focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-2"
      onClick={onDismiss}
    >
      <span className="sr-only">Close</span>
      <XIcon className="h-5 w-5" aria-hidden="true" />
    </button>
  )

  const iconMarkup = () => {
    if (error) {
      return (
        <XCircleIcon
          className="h-6 w-6 text-negative-text"
          aria-hidden="true"
        />
      )
    } else {
      return (
        <CheckCircleIcon
          className="h-6 w-6 text-positive-text"
          aria-hidden="true"
        />
      )
    }
  }

  return (
    <div className="w-full">
      <Transition
        show={show}
        as={Fragment}
        enter="transform ease-out duration-300 transition"
        enterFrom="translate-y-2 opacity-0 sm:translate-y-0 sm:translate-x-2"
        enterTo="translate-y-0 opacity-100 sm:translate-x-0"
        leave="transition ease-in duration-100"
        leaveFrom="opacity-100"
        leaveTo="opacity-0"
      >
        <div className="pointer-events-auto w-full max-w-sm overflow-hidden rounded-lg bg-primary-background shadow-lg ring-1 ring-primary ring-opacity-5">
          <div className="p-4">
            <div className="flex items-start">
              <div className="flex-shrink-0">{iconMarkup()}</div>
              <div className="ml-3 w-0 flex-1 pt-0.5">
                <p className="text-sm font-medium text-gray-900">{content}</p>
                {/* <p className="mt-1 text-sm text-gray-500">{content}</p> */}
              </div>
              <div className="ml-4 flex flex-shrink-0">{dismissMarkup}</div>
            </div>
          </div>
        </div>
      </Transition>
    </div>
  )
}
