import { ProgressBar } from "@cloudscape-design/components";
import { useEffect, useState } from "react";

export interface ICountdownBarProps {
  timeSeconds: number;
  onCancel?: () => void;
  onExpiry?: () => void;
}

export const CountdownBar = ({ timeSeconds, onCancel, onExpiry }: ICountdownBarProps) => {
  const [ countdown, setCountdown ] = useState<number>(timeSeconds);

  useEffect(() => {
    setCountdown(countdown - 1);
  }, []);

  useEffect(() => {
    if (countdown === 0) {
      onExpiry ? onExpiry(): null;
      return;
    }
    const timer = setTimeout(() => {
      setCountdown(countdown - 1);
    }, 1000);

    return () => clearTimeout(timer);
  }, [countdown]);

  

  return (
    <ProgressBar
      label={"Authentication Timeout"}
      description={"Dial the buzzer before the time expires"} 
      additionalInfo={`Authentication expires after ${timeSeconds}s to keep the door secure. Please dial the buzzer within the time remaining or it won't unlock`} 
      value={(countdown / timeSeconds) * 100}
      variant="flash"
    />
  );

}