"use client";

import { useEffect, useMemo, useState } from "react";
import { IoClose } from "react-icons/io5";
import Button from "@/components/Componentes/button";
import InformationSheet from "@/components/Componentes/information-sheet";
import type { FormOverviewSection } from "@/hooks/marriage/use-form-schema";
import { useI18n } from "@/translations/provider";

const bookingTerms = [
  "All provided information is held in strict confidence.",
  "Data is utilized exclusively to ensure optimal matchmaking accuracy.",
];

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

const FIRST_ENTRY_TERMS = [
  ...bookingTerms,
  "Do you struggle to understand the underlying psychological drivers that dictate your interpersonal connections and communication barriers?",
  "Taking this test is not mandatory, but it will help you better search for a spouse. The Kettle test is a test for self-knowledge and better understanding of your spouse.",
  'Do you operate based on superficial behavioral adaptations, or are you aware of the deep "source traits" that fundamentally control your decision-making processes?',
  "Do you struggle to understand the underlying psychological drivers that dictate your interpersonal connections and communication barriers?",
  "Taking this test is not mandatory, but it will help you better search for a spouse. The Kettle test is a test for self-knowledge and better understanding of your spouse.",
  'Do you operate based on superficial behavioral adaptations, or are you aware of the deep "source traits" that fundamentally control your decision-making processes?',
] as const;

export default function SectionsRequest({
  sections,
  isOpen: controlledIsOpen,
  onClose: controlledOnClose,
}: {
  sections?: FormOverviewSection[] | undefined;
  isOpen?: boolean;
  onClose?: () => void;
}) {
  const { dictionary: t } = useI18n();
  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?.();
  };

  const termsTitle = t["terms & conditions"] || "Terms & Conditions";
  const gotItLabel = t["Got it"] || "Got it";

  return (
    <InformationSheet
      isOpen={isSheetOpen}
      icon={null}
      showCloseButton={false}
      title={({ close }) => (
        <span className="flex w-full items-start justify-between gap-3 text-start">
          <span className="text-[14px] leading-5 font-bold tracking-normal text-[#8B8B8B]">
            {termsTitle}
          </span>
          <button
            type="button"
            aria-label="Close terms and conditions"
            className="-mt-0.5 flex size-6 shrink-0 items-center justify-center text-[#8F8F8F] cursor-pointer"
            onClick={close}
          >
            <IoClose aria-hidden="true" className="text-[22px]" />
          </button>
        </span>
      )}
      description={
        <ul className="max-h-[60dvh] space-y-2 overflow-y-auto ps-4 text-start text-[12px] leading-[1.35] font-medium list-disc text-[#4C4C4C] marker:text-[#2B2B2B]">
          {FIRST_ENTRY_TERMS.map((item, index) => (
            <li key={`${index}-${item}`}>{(t as Record<string, string>)[item] || item}</li>
          ))}
        </ul>
      }
      buttons={({ close }) => (
        <Button className="rounded-[8px]" onClick={close}>
          {gotItLabel}
        </Button>
      )}
      onClose={handleClose}
      className="text-start"
    />
  );
}
