import React, { useEffect, useState } from 'react';
import { PopoverAnchor } from '../silke-popover';
import { SilkeBox } from '../silke-box';
import { SilkeButton, SilkeButtonSet } from '../silke-button';
import { SilkeText } from '../silke-text';
import { SilkeTooltip, TooltipHorizontalPosition } from './silke-tooltip';

type SilkeInteractiveTooltipStep = {
  header?: string;
  text: React.ReactNode;
};

interface SilkeInteractiveTooltipProps {
  anchor: PopoverAnchor;
  /**
   * If set, the last step will say 'Next', not 'Finish'
   */
  lastIsNotLast?: boolean;
  /**
   * Callback for when clicking 'Next' or 'Finish' on the last step
   */
  onFinished?: () => void;
  show: boolean;
  steps: SilkeInteractiveTooltipStep[];
}

/**
 * Shows a tooltip with a series of steps
 */
export function SilkeInteractiveTooltip({
  anchor,
  lastIsNotLast,
  onFinished,
  show,
  steps,
}: SilkeInteractiveTooltipProps) {
  const [step, setStep] = useState(0);
  useEffect(() => void (show && setStep(0)), [show]);

  if (!steps) return null;

  const handleBack = () => setStep(step - 1);

  const handleClose = () => {
    if (onFinished) onFinished();
    setStep(steps.length - 1);
  };

  const handleNext = () => {
    if (step >= steps.length - 1) handleClose();
    else setStep(step + 1);
  };

  // Hide if user has pressed Next until there are no more steps
  const actuallyShow = step >= steps.length ? false : show;
  const data = steps[step];

  /**
   * Component holding step data and navigation
   */
  const JustTheTip = (
    <SilkeBox column>
      <SilkeBox vAlign="center" hAlign="end">
        {steps.length > 1 && <SilkeText flex>{`${step + 1}/${steps.length}`}</SilkeText>}
        <SilkeButton kind="ghost" size="base" icon="close" onClick={handleClose} />
      </SilkeBox>

      {data?.header && (
        <SilkeText overflow weight="strong">
          {data.header}
        </SilkeText>
      )}
      <span>{data?.text}</span>

      <SilkeButtonSet>
        {step !== 0 && <SilkeButton label="Back" onClick={handleBack} kind="ghost" />}
        <SilkeButton
          label={step === steps.length - 1 && !lastIsNotLast ? 'Finish' : 'Next'}
          onClick={handleNext}
          kind="primary"
        />
      </SilkeButtonSet>
    </SilkeBox>
  );

  return (
    <SilkeTooltip anchor={anchor} show={actuallyShow}>
      {JustTheTip}
    </SilkeTooltip>
  );
}
