"use client";

import { useEffect, useState } from "react";
import { Button, Modal, useOverlayState } from "@heroui/react";
import { ShopFilterContent, type ShopFilterOptions } from "./ShopFilterContent";
import { DEFAULT_SHOP_FILTER_STATE, type ShopFilterState } from "@/lib/shop/filterState";

/**
 * Hero UI Modal for filters on mobile/tablet. Opens from Filter button.
 * Filters are applied only when the user presses "Apply filter"; closing
 * without applying keeps the previous filter state.
 * When filterOptions/filterState/onApplyFilters are provided, renders ShopFilterContent
 * with pending state; otherwise renders children.
 */
export function ShopFilterModal({
  isOpen,
  onClose,
  onApply,
  children,
  filterOptions,
  filterState,
  onApplyFilters,
  filterOptionsLoading,
}: {
  isOpen: boolean;
  onClose: () => void;
  /** Called when user confirms (without filter state); then modal closes. */
  onApply: () => void;
  children?: React.ReactNode;
  filterOptions?: ShopFilterOptions | null;
  filterState?: ShopFilterState;
  /** When user presses Apply filter with new state; parent should sync URL and close. */
  onApplyFilters?: (state: ShopFilterState) => void;
  filterOptionsLoading?: boolean;
}) {
  const state = useOverlayState({
    isOpen,
    onOpenChange: (open) => {
      if (!open) onClose();
    },
  });

  const showFilterContent =
    filterOptions !== undefined &&
    filterState !== undefined &&
    onApplyFilters !== undefined;

  const [pendingState, setPendingState] = useState<ShopFilterState>(
    filterState ?? DEFAULT_SHOP_FILTER_STATE,
  );

  useEffect(() => {
    if (isOpen && filterState) setPendingState(filterState);
  }, [isOpen, filterState]);

  const handleApply = () => {
    if (showFilterContent) {
      onApplyFilters(pendingState);
    } else {
      onApply();
    }
    onClose();
  };

  if (!isOpen) return null;

  return (
    <Modal state={state}>
      <Modal.Container
        placement="center"
        className="fixed inset-0 z-[9999] flex items-center justify-center p-4 [&[data-entering=true]]:!opacity-100 [&[data-entering=true]]:!scale-100 [&[data-entering=true]]:!animate-none"
      >
        <Modal.Dialog className="my-auto max-h-[85vh] w-full max-w-md rounded-2xl border border-[var(--border)] bg-[var(--surface)] shadow-xl">
          <Modal.Header className="flex flex-col gap-1 border-b border-[var(--border)] px-4 py-3">
            <span className="text-lg font-semibold">Filters</span>
          </Modal.Header>
          <Modal.Body className="max-h-[60vh] overflow-y-auto overflow-x-hidden px-4 py-4 flex flex-col gap-4">
            {showFilterContent && (
              <ShopFilterContent
                options={filterOptions}
                value={pendingState}
                onChange={setPendingState}
                isLoading={filterOptionsLoading}
              />
            )}
            {children}
          </Modal.Body>
          <Modal.Footer className="flex gap-2 border-t border-[var(--border)] px-4 py-3">
            <Button variant="outline" onPress={onClose} className="flex-1 md:flex-none">
              Cancel
            </Button>
            <Button variant="primary" onPress={handleApply} className="flex-1 md:flex-none">
              Apply filter
            </Button>
          </Modal.Footer>
        </Modal.Dialog>
      </Modal.Container>
      <Modal.Backdrop className="fixed inset-0 z-[9998] bg-black/40" />
    </Modal>
  );
}
