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

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

export const CountdownBar = ({ timeSeconds, onCancel, onExpiry, label, description, additionalInfo }: 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={label || "Authentication Timeout"}
      description={description || "Dial the buzzer before the time expires"} 
      additionalInfo={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"
    />
  );
}
