
import { useEffect, useState } from 'react';
import { Token } from 'rm-sdk/build/interfaces/token.interface';
import Switch from "react-switch";
import { Spinner } from './Widget';
import { Market } from 'rm-sdk/build/types';
import { renderTemplateString } from '../../utils/commonUtils';
import { insertLinksAndSpinnersInString } from '../../utils/uiUtils';

interface IProps {
  activateProtectionTitle?: string;
  activePolicyTitle?: string;
  isPolicyActive: boolean;
  showBuyPolicyPopUp: () => void;

  rate?: string;
  coverage?: string;
  coverageTokenInfo?: Token;
  quote?: string;
  quoteTokenInfo?: Token;
  controlType?: string;
  className?: string;
  policyUrl?: string;
  marketUrl?: string;
  market?: Market;
  incomeApyRate?: string;
}

export default function WidgetTitle(props: IProps) {
  const [title, setTitle] = useState<string | JSX.Element>();

  useEffect(() => {
    let t = (props.isPolicyActive ? (props.activePolicyTitle || "Protection is active") : (props.activateProtectionTitle || "Activate protection"));

    setTitle(insertLinksAndSpinnersInString(renderTemplateString(t, {
      ...props
    }), props.policyUrl, props.marketUrl));
  }, [props]);

  function renderTitle() {
    return <span>
      {title}
    </span>;
  }

  function handleNavigateButtonClick() {
    //@ts-ignore
    window.open(props.isPolicyActive ? props.policyUrl : props.marketUrl, '_blank')?.focus();
  }

  return (props.isPolicyActive != null && title ? <div className={`AtomicaWidget--ActivateProtection`}>
    <div className='widget-title'>
    {
      props.controlType === 'toggle' ?
        <>
          <Switch onChange={props.showBuyPolicyPopUp} checked={props.isPolicyActive === true} />
          {renderTitle()}
        </>
      : props.controlType === 'checkbox' ?
        <>
          <input type="checkbox" checked={props.isPolicyActive === true} onChange={props.showBuyPolicyPopUp} />
          {renderTitle()}
        </>
      : props.controlType === 'button' ?
        <button className={props.className} onClick={props.showBuyPolicyPopUp}>
          {renderTitle()}
        </button>
      : props.controlType === 'link' ?
        <a className={props.className} onClick={props.showBuyPolicyPopUp}>
          {renderTitle()}
        </a>
      : props.controlType === 'website-link' ?
      <div>
        {renderTitle()}
        <button className={props.className}
          onClick={handleNavigateButtonClick}>
          {props.isPolicyActive ? "Manage protection" : "Get protection"}
        </button>
      </div>
      : <div onClick={props.showBuyPolicyPopUp}>
          {renderTitle()}
        </div>
    }
  </div></div> : <Spinner />)
}
