import {
  createEffect,
  createMemo,
  createSignal,
  FlowComponent,
  onCleanup,
  useContext,
} from "solid-js";
import { UiStoreContext } from "~/stores";
import { de } from "date-fns/locale";
import { formatDistanceToNow, fromUnixTime, getUnixTime } from "date-fns";

const Page: FlowComponent = (props) => {
  const [uiState] = useContext(UiStoreContext)!;
  const [now, setNow] = createSignal(new Date());
  createEffect(function () {
    const interval = setInterval(function () {
      setNow(new Date());
    }, 10000);
    onCleanup(() => clearInterval(interval));
  });
  const lastSavedWords = createMemo(function () {
    now();

    let words = "Nie";

    if (uiState.lastSaved > 0) {
      words = formatDistanceToNow(fromUnixTime(uiState.lastSaved), {
        includeSeconds: true,
        addSuffix: true,
        locale: de,
      });
    }

    return words;
  });
  const savedDistance = createMemo(function () {
    now();

    if (uiState.lastSaved === 0) {
      return -1;
    }

    const nowUnix = getUnixTime(new Date());
    const distance = nowUnix - uiState.lastSaved;

    return distance;
  });

  return (
    <div class="flex-1 flex flex-col justify-start print:block overflow-y-hidden overflow-x-hidden xxl:overflow-y-auto items-center lg:max-w-[none] max-h-screen lg:max-h-[none] print:max-h-[none] min-h-screen print:min-h-0 p-5 pt-3 print:p-0">
      <div
        aria-disabled="true"
        class="print:hidden text-xs text-black text-opacity-50 uppercase mb-2"
      >
        Zuletzt gespeichert:{" "}
        <span
          classList={{
            "text-green-700 text-opacity-50":
              savedDistance() >= 0 && savedDistance() < 60,
            "text-lime-800 text-opacity-50":
              savedDistance() >= 60 && savedDistance() < 120,
            "text-yellow-700 text-opacity-60":
              savedDistance() >= 120 && savedDistance() < 180,
            "text-orange-700 text-opacity-70":
              savedDistance() >= 180 && savedDistance() < 300,
            "text-red-700 text-opacity-75": savedDistance() >= 300,
            "font-bold": savedDistance() >= 600,
          }}
        >
          {lastSavedWords()}
        </span>
      </div>
      <div class="w-[900px] lg:w-[1000px] xl:w-[1100px] xxl:w-[1200px] print:w-full shrink-0 scale-75 md:scale-90 lg:scale-100 origin-top print:scale-100 shadow-md print:shadow-none bg-white p-5 print:p-0">
        {props.children}
      </div>
    </div>
  );
};

export default Page;
