import { useState, useEffect } from "react";
import { BerlinClock } from "./BerlinClock";
import { DigitalClock } from "./DigitalClock";
import { useCurrentTime } from "../hooks/useCurrentTime";
import { dateToBerlin } from "../utils";

export function TimeConverter() {
  const { currentTime, setCurrentTime } = useCurrentTime();
  const [useSystemTime, setUseSystemTime] = useState(false);
  const berlinClock = dateToBerlin(currentTime);

  useEffect(() => {
    if (!useSystemTime) return;
    const id = setInterval(() => {
      setCurrentTime(new Date());
    }, 1000);
    return () => clearInterval(id);
  }, [useSystemTime, setCurrentTime]);

  return (
    <div>
      <label>
        <input
          type="checkbox"
          data-testid="use-system-time"
          checked={useSystemTime}
          onChange={(e) => {
            setUseSystemTime(e.target.checked);
            if (e.target.checked) {
              setCurrentTime(new Date());
            }
          }}
        />
        Use system time
      </label>
      <BerlinClock enabled={true} clock={berlinClock} />
      <DigitalClock
        currentTime={currentTime}
        onTimeChange={setCurrentTime}
        disabled={useSystemTime}
      />
    </div>
  );
}
