'use client';

import React, { ReactNode, useRef, useCallback } from 'react';
import { Drawer, Button } from 'antd';
import { useIsMobile } from '@/hooks/useIsMobile';
import styles from './MobileFiltersDrawer.module.scss';

export interface MobileFiltersDrawerProps {
  /** Controla abertura do drawer */
  open: boolean;
  onClose: () => void;
  /** Conteúdo dos filtros (scrollável) */
  children: ReactNode;
  /** Chamado ao clicar em "Aplicar filtros"; fecha o drawer após aplicar */
  onApply: () => void;
  /** Chamado ao clicar em "Limpar" */
  onReset?: () => void;
  /** Título do drawer (ex.: "Filtros") */
  title?: string;
  /** Só renderiza o drawer em viewport mobile; em desktop retorna null */
  mobileOnly?: boolean;
  /** `data-testid` na região scrollável (smoke / E2E). */
  dataTestId?: string;
}

/**
 * Drawer padrão para exibir filtros em mobile (viewport ≤ 768px).
 * Conteúdo scrollável; botão "Aplicar filtros" fixo no rodapé.
 * MOB-035: Touch targets ≥44px, foco no conteúdo ao abrir, fechamento por Escape.
 */
export function MobileFiltersDrawer({
  open,
  onClose,
  children,
  onApply,
  onReset,
  title = 'Filtros',
  mobileOnly = true,
  dataTestId,
}: MobileFiltersDrawerProps) {
  const isMobile = useIsMobile();
  const bodyRef = useRef<HTMLDivElement>(null);

  // MOB-035: após abrir, mover foco para o conteúdo (primeiro focusável) para ordem de tabulação correta
  const handleAfterOpenChange = useCallback((isOpen: boolean) => {
    if (isOpen && bodyRef.current) {
      const focusable = bodyRef.current.querySelector<HTMLElement>(
        'button:not([aria-hidden]), [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
      );
      if (focusable) {
        focusable.focus({ preventScroll: true });
      } else {
        bodyRef.current.focus({ preventScroll: true });
      }
    }
  }, []);

  if (mobileOnly && !isMobile) {
    return null;
  }

  return (
    <Drawer
      title={title}
      placement="right"
      onClose={onClose}
      open={open}
      width="100%"
      keyboard
      afterOpenChange={handleAfterOpenChange}
      className={styles.drawer}
      styles={{
        body: { padding: 0, display: 'flex', flexDirection: 'column', overflow: 'hidden' },
        footer: { padding: 16 },
      }}
      footer={
        <div className={styles.footer}>
          {onReset && (
            <Button
              onClick={onReset}
              className={styles.footerButtonSecondary}
              aria-label="Limpar filtros"
            >
              Limpar
            </Button>
          )}
          <Button type="primary" onClick={onApply} className={styles.footerButtonPrimary} aria-label="Aplicar filtros">
            Aplicar filtros
          </Button>
        </div>
      }
    >
      <div ref={bodyRef} className={styles.body} tabIndex={-1} data-testid={dataTestId}>
        {children}
      </div>
    </Drawer>
  );
}

export default MobileFiltersDrawer;
