import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { GreenScrollbar } from './GreenScrollbar';
import { VistaDatosDocumentoItem } from './VistaDatosDocumentoItem';
import { VistaDatosDocumentosPaginacion } from './VistaDatosDocumentosPaginacion';
import { VISTA_DATOS_DOCUMENTOS_DEFAULTS } from './vistaDatosDocumentosDefaults';

const LIST_SCROLLBAR_GUTTER_PX = 16;

function filterDocumentos(documentos, searchQuery) {
  const q = String(searchQuery ?? '')
    .trim()
    .toLowerCase();
  if (!q) return documentos;
  return documentos.filter((doc) => {
    const haystack = [
      doc.title,
      doc.archivoOrigen,
      doc.personaLine,
      doc.statusLabel,
    ]
      .filter(Boolean)
      .join(' ')
      .toLowerCase();
    return haystack.includes(q);
  });
}

/**
 * Listado de documentos con scroll verde custom y paginado en el front.
 */
export const VistaDatosDocumentosList = ({
  documentos = VISTA_DATOS_DOCUMENTOS_DEFAULTS,
  searchQuery = '',
  pageSize = 4,
  currentPage: currentPageProp,
  defaultPage = 1,
  onPageChange,
  onDocumentoClick,
  emptyMessage = 'No hay documentos para mostrar.',
  className = '',
  style,
  listStyle,
  paginationProps,
  isNarrow = false,
  ...props
}) => {
  const listRef = useRef(null);
  const [internalPage, setInternalPage] = useState(defaultPage);

  const isControlled = currentPageProp !== undefined && currentPageProp !== null;
  const currentPage = isControlled ? currentPageProp : internalPage;

  const filtered = useMemo(
    () => filterDocumentos(Array.isArray(documentos) ? documentos : [], searchQuery),
    [documentos, searchQuery],
  );

  const totalPages = Math.max(1, Math.ceil(filtered.length / Math.max(1, pageSize)));

  const safePage = Math.min(Math.max(1, currentPage), totalPages);

  const handlePageChange = useCallback(
    (page) => {
      const next = Math.min(Math.max(1, page), totalPages);
      if (!isControlled) setInternalPage(next);
      onPageChange?.(next);
      if (listRef.current) listRef.current.scrollTop = 0;
    },
    [isControlled, onPageChange, totalPages],
  );

  useEffect(() => {
    if (!isControlled && internalPage !== safePage) {
      setInternalPage(safePage);
    }
  }, [isControlled, internalPage, safePage]);

  useEffect(() => {
    if (safePage > totalPages) {
      handlePageChange(totalPages);
    }
  }, [safePage, totalPages, handlePageChange]);

  useEffect(() => {
    handlePageChange(1);
  }, [searchQuery, handlePageChange]);

  const paginated = useMemo(() => {
    const start = (safePage - 1) * pageSize;
    return filtered.slice(start, start + pageSize);
  }, [filtered, safePage, pageSize]);

  return (
    <div
      className={['anima-vista-datos-documentos-list', className].filter(Boolean).join(' ')}
      style={{
        display: 'flex',
        flexDirection: 'column',
        height: '100%',
        minHeight: 0,
        flex: 1,
        width: '100%',
        boxSizing: 'border-box',
        ...(style || {}),
      }}
      {...props}
    >
      <div
        style={{
          position: 'relative',
          flex: '1 1 auto',
          minHeight: 0,
          width: '100%',
        }}
      >
        <div
          ref={listRef}
          className="anima-vista-datos-documentos-list__scroll"
          style={{
            height: '100%',
            overflowY: 'auto',
            overflowX: 'hidden',
            paddingRight: LIST_SCROLLBAR_GUTTER_PX,
            boxSizing: 'border-box',
            scrollbarWidth: 'none',
            msOverflowStyle: 'none',
            WebkitOverflowScrolling: 'touch',
            ...(listStyle || {}),
          }}
        >
          <style>{`
            .anima-vista-datos-documentos-list__scroll::-webkit-scrollbar {
              display: none;
              width: 0;
              height: 0;
            }
          `}</style>
          {paginated.length === 0 ? (
            <p
              style={{
                fontFamily: 'IBM Plex Sans, sans-serif',
                fontSize: 14,
                lineHeight: '21px',
                color: '#6B7280',
                margin: 0,
                padding: '8px 0',
              }}
            >
              {emptyMessage}
            </p>
          ) : (
            paginated.map((doc, index) => (
              <VistaDatosDocumentoItem
                key={doc.id ?? `${doc.title}-${index}`}
                status={doc.status}
                title={doc.title}
                archivoOrigen={doc.archivoOrigen}
                archivoOrigenPrefix={doc.archivoOrigenPrefix}
                personaLine={doc.personaLine}
                statusLabel={doc.statusLabel}
                showBorder={index < paginated.length - 1}
                isFirst={index === 0}
                onClick={
                  onDocumentoClick ? () => onDocumentoClick(doc, index) : undefined
                }
              />
            ))
          )}
        </div>
        <GreenScrollbar scrollRef={listRef} />
      </div>

      <VistaDatosDocumentosPaginacion
        currentPage={safePage}
        totalPages={totalPages}
        onPageChange={handlePageChange}
        isNarrow={isNarrow}
        {...(paginationProps || {})}
      />
    </div>
  );
};

export { VISTA_DATOS_DOCUMENTOS_DEFAULTS } from './vistaDatosDocumentosDefaults';
export default VistaDatosDocumentosList;
