"use client";

import { useEffect, useState } from "react";

import { AccordionProps } from "@shared/components/accordion/types";
import { Button } from "@shared/components/button";
import { Collapse } from "@shared/components/collapse";
import { MaterialIcon } from "@shared/components/material-icon";
import { cx } from "@shared/utils";

export const Accordion: React.FC<AccordionProps> = props => {
  const {
    title,
    defaultOpen,
    children,
    containerClassName,
    titleClassName,
    className,
    buttonClassName,
    iconClassName,
    openOnlyOnDesktop,
    borderRadiusNone = false,
  } = props;
  const [open, setOpen] = useState<boolean>(Boolean(false));

  useEffect(() => {
    // Only execute responsive logic if the prop is true
    if (openOnlyOnDesktop) {
      const isDesktop = window.innerWidth >= 1024;
      setOpen(isDesktop);
    } else {
      // Otherwise, fall back to standard defaultOpen behavior
      setOpen(Boolean(defaultOpen));
    }
  }, [openOnlyOnDesktop, defaultOpen]);

  return (
    <div
      className={cx(
        borderRadiusNone ? "rounded-none border" : "rounded-surface-xs border",
        containerClassName
      )}
    >
      <Button
        type="button"
        className={cx(
          borderRadiusNone ? "rounded-none" : "rounded-t-surface-xs",
          "flex w-full items-center justify-between gap-4 px-4 py-3 text-left",
          buttonClassName
        )}
        onClick={() => setOpen(v => !v)}
      >
        <span className={cx("label5 flex-1", titleClassName)}>{title}</span>
        <MaterialIcon
          className={cx("flex-shrink-0", iconClassName)}
          name={open ? "keyboard_arrow_up" : "keyboard_arrow_down"}
          fill={1}
          size={24}
        />
      </Button>
      <Collapse open={open}>
        <div className={cx("px-4 py-4", className)}>{children}</div>
      </Collapse>
    </div>
  );
};

Accordion.displayName = "Accordion";

export type { AccordionProps };
