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

export interface FunnelListItem {
  _id: string;
  name: string;
  description?: string;
  status: 'draft' | 'published' | 'archived';
  version: number;
  createdAt: string;
  updatedAt: string;
  publishedAt?: string;
  usage: {
    totalViews: number;
    totalCompletions: number;
    lastUsed?: string;
  };
  funnelData?: {
    meta?: {
      id?: string;
      title?: string;
      description?: string;
    };
  };
}

export interface PaginationInfo {
  current: number;
  total: number;
  count: number;
  totalItems: number;
}

export interface UseFunnelsOptions {
  search?: string;
  status?: string;
  sortBy?: string;
  sortOrder?: 'asc' | 'desc';
  limit?: number;
}

export interface UseFunnelsResult {
  funnels: FunnelListItem[];
  pagination: PaginationInfo;
  loading: boolean;
  error: string | null;
  loadFunnels: (page?: number) => Promise<void>;
  refresh: () => void;
}

export function useFunnels(options: UseFunnelsOptions = {}): UseFunnelsResult {
  const {
    search = '',
    status = 'all',
    sortBy = 'updatedAt',
    sortOrder = 'desc',
    limit = 20,
  } = options;

  const [funnels, setFunnels] = useState<FunnelListItem[]>([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [pagination, setPagination] = useState<PaginationInfo>({
    current: 1,
    total: 1,
    count: 0,
    totalItems: 0,
  });
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const loadFunnels = useCallback(
    async (page: number = 1) => {
      try {
        setLoading(true);
        setError(null);

        const params = new URLSearchParams({
          page: page.toString(),
          limit: limit.toString(),
          sortBy,
          sortOrder,
          ...(search && { search }),
          ...(status !== 'all' && { status }),
        });

        const response = await fetch(`/api/funnels?${params}`);
        if (!response.ok) {
          throw new Error('Failed to fetch funnels');
        }

        const data = await response.json();
        setFunnels(data.funnels);
        setPagination(data.pagination);
        setCurrentPage(data.pagination.current);
      } catch (err) {
        setError(err instanceof Error ? err.message : 'Unknown error');
      } finally {
        setLoading(false);
      }
    },
    [search, status, sortBy, sortOrder, limit]
  );

  const refresh = useCallback(() => {
    loadFunnels(currentPage);
  }, [loadFunnels, currentPage]);

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

  return {
    funnels,
    pagination,
    loading,
    error,
    loadFunnels,
    refresh,
  };
}
