import { useState, useEffect, useCallback, useRef } from 'react';
import axios from 'axios';

interface PaginationData {
  current_page: number;
  last_page: number;
  per_page: number;
  total: number;
  from?: number;
  to?: number;
}

interface UseInfiniteContactosProps {
  initialItems: any[];
  initialPagination: PaginationData;
  filters?: Record<string, string>;
}

export const useInfiniteContactos = ({ initialItems, initialPagination, filters = {} }: UseInfiniteContactosProps) => {
  const [items, setItems] = useState<any[]>(initialItems || []);
  const [pagination, setPagination] = useState<PaginationData>(initialPagination);
  const [isLoading, setIsLoading] = useState(false);
  const [hasMore, setHasMore] = useState<boolean>(
    initialPagination.current_page < initialPagination.last_page
  );

  const sentinelRef = useRef<HTMLDivElement | null>(null);
  const loadingRef = useRef(false);

  const loadMore = useCallback(async () => {
    if (loadingRef.current || !hasMore) return;

    loadingRef.current = true;
    setIsLoading(true);

    try {
      const resp = await axios.get((window as any).route('contactos.load-more'), {
        params: {
          page: pagination.current_page + 1,
          per_page: pagination.per_page,
          ...filters,
        }
      });

      const data = resp.data || {};
      setItems(prev => [...prev, ...(data.data || [])]);
      setPagination({
        current_page: data.current_page,
        last_page: data.last_page,
        per_page: data.per_page,
        total: data.total,
        from: data.from,
        to: data.to,
      });
      setHasMore(data.current_page < data.last_page);
    } catch (error) {
      console.error('Error cargando más contactos:', error);
    } finally {
      setIsLoading(false);
      loadingRef.current = false;
    }
  }, [pagination.current_page, pagination.per_page, hasMore, filters]);

  const resetWithFilters = useCallback(async (newFilters: Record<string, string>) => {
    setIsLoading(true);
    try {
      const resp = await axios.get((window as any).route('contactos.load-more'), {
        params: {
          page: 1,
          per_page: pagination.per_page,
          ...newFilters,
        }
      });

      const data = resp.data || {};
      setItems(data.data || []);
      setPagination({
        current_page: data.current_page,
        last_page: data.last_page,
        per_page: data.per_page,
        total: data.total,
        from: data.from,
        to: data.to,
      });
      setHasMore(data.current_page < data.last_page);
    } catch (error) {
      console.error('Error filtrando contactos:', error);
    } finally {
      setIsLoading(false);
    }
  }, [pagination.per_page]);

  useEffect(() => {
    const el = sentinelRef.current;
    if (!el) return;
    const observer = new IntersectionObserver((entries) => {
      if (entries[0].isIntersecting && hasMore && !isLoading) {
        loadMore();
      }
    }, { rootMargin: '200px' });

    observer.observe(el);
    return () => observer.disconnect();
  }, [hasMore, isLoading, loadMore]);

  const updateItem = useCallback((contactoId: number, updates: Partial<any>) => {
    setItems(prev => prev.map(item => {
      if (item.CodConCli === contactoId) {
        const updated = { ...item, ...updates };
        // Actualizar el estado y el label
        const estado = updated.EstConCli ?? updated.EstCli ?? 0;
        updated.EstConCli = estado;
        updated.EstConCliLabel = estado == 1 ? 'ACTIVO' : 'INACTIVO';
        return updated;
      }
      return item;
    }));
    // Actualizar el total en la paginación
    setPagination(prev => ({ ...prev, total: Math.max(0, prev.total) }));
  }, []);

  const removeItem = useCallback((contactoId: number) => {
    setItems(prev => {
      const filtered = prev.filter(item => item.CodConCli !== contactoId);
      // Actualizar el total en la paginación
      setPagination(prevPagination => ({
        ...prevPagination,
        total: Math.max(0, prevPagination.total - 1),
      }));
      return filtered;
    });
  }, []);

  const refreshCurrentPage = useCallback(async () => {
    setIsLoading(true);
    try {
      const resp = await axios.get((window as any).route('contactos.load-more'), {
        params: {
          page: pagination.current_page,
          per_page: pagination.per_page,
          ...filters,
        }
      });

      const data = resp.data || {};
      setItems(data.data || []);
      setPagination({
        current_page: data.current_page,
        last_page: data.last_page,
        per_page: data.per_page,
        total: data.total,
        from: data.from,
        to: data.to,
      });
      setHasMore(data.current_page < data.last_page);
    } catch (error) {
      console.error('Error refrescando contactos:', error);
    } finally {
      setIsLoading(false);
    }
  }, [pagination.current_page, pagination.per_page, filters]);

  return {
    items,
    pagination,
    isLoading,
    hasMore,
    loadMore,
    resetWithFilters,
    updateItem,
    removeItem,
    refreshCurrentPage,
    sentinelRef,
  } as const;
};

export default useInfiniteContactos;
