"use client";

import { useEffect, useMemo, useState } from "react";
import type { FormOverviewSection } from "@/hooks/marriage/use-form-schema";
import TermsSheet, {
  TERMS_SECTIONS,
  type TermItem,
  type TermSection,
  type TermsSheetProps,
} from "@/components/Componentes/terms-sheet";

const FIRST_ENTRY_TERMS_SEEN_KEY = "marriage:first-entry-terms-seen";

export { TERMS_SECTIONS, type TermItem, type TermSection, type TermsSheetProps };

export default function SectionsRequest({
  sections,
  isOpen: controlledIsOpen,
  onClose: controlledOnClose,
}: {
  sections?: FormOverviewSection[] | undefined;
  isOpen?: boolean;
  onClose?: () => void;
}) {
  const [hasSeenSheet, setHasSeenSheet] = useState(true);
  const [isAutoOpenDismissed, setIsAutoOpenDismissed] = useState(false);

  const hasNoProgression = useMemo(() => {
    if (!sections?.length) {
      return false;
    }

    return sections.every(
      (section) =>
        section.progress.current_step <= 0 &&
        section.progress.completion_percent <= 0,
    );
  }, [sections]);

  useEffect(() => {
    try {
      const seenLocal =
        window.localStorage.getItem(FIRST_ENTRY_TERMS_SEEN_KEY) === "true";
      const seenSession =
        window.sessionStorage.getItem(FIRST_ENTRY_TERMS_SEEN_KEY) === "true";
      setHasSeenSheet(seenLocal || seenSession);
    } catch (e) {
      console.warn("Storage is not accessible:", e);
      setHasSeenSheet(false);
    }
  }, []);

  const isAutoOpen =
    Boolean(sections) && hasNoProgression && !hasSeenSheet && !isAutoOpenDismissed;
  const isSheetOpen = Boolean(controlledIsOpen) || isAutoOpen;

  const handleClose = () => {
    setIsAutoOpenDismissed(true);
    try {
      window.localStorage.setItem(FIRST_ENTRY_TERMS_SEEN_KEY, "true");
      window.sessionStorage.setItem(FIRST_ENTRY_TERMS_SEEN_KEY, "true");
    } catch (e) {
      console.warn("Storage is not accessible:", e);
    }
    controlledOnClose?.();
  };

  return (
    <TermsSheet
      isOpen={isSheetOpen}
      onClose={handleClose}
    />
  );
}
