import { useState, useEffect, useCallback } from 'react';
import { useApiRequest } from './useApi';

interface PaginationParams {
  page?: number;
  pageSize?: number;
  sort?: Array<{ field: string; direction: 'asc' | 'desc' }>;
  filters?: Record<string, any>;
  search?: string;
}

interface PaginationState {
  currentPage: number;
  pageSize: number;
  totalItems: number;
  totalPages: number;
}

const _STATUS_LABELS: Record<string, string> = {
  PENDING: 'Ausstehend',
  SCHEDULED: 'Geplant',
  TRIALING: 'Testphase',
  ACTIVE: 'Aktiv',
  PAST_DUE: 'Überfällig',
  EXPIRED: 'Abgelaufen',
};

export function useAdminSubscriptions() {
  const [subscriptions, setSubscriptions] = useState<any[]>([]);
  const [pagination, setPagination] = useState<PaginationState | null>(null);
  const { request, isLoading: loading, error } = useApiRequest();

  const refetch = useCallback(async (params?: PaginationParams) => {
    try {
      const requestParams: Record<string, string> = {};

      if (params) {
        const paginationObj: any = {};
        if (params.page !== undefined) paginationObj.page = params.page;
        if (params.pageSize !== undefined) paginationObj.pageSize = params.pageSize;
        if (params.sort) paginationObj.sort = params.sort;
        if (params.filters) paginationObj.filters = params.filters;
        if (params.search) paginationObj.search = params.search;

        if (Object.keys(paginationObj).length > 0) {
          requestParams.pagination = JSON.stringify(paginationObj);
        }
      }

      const data = await request({
        url: '/api/subscription/admin/all',
        method: 'get',
        params: requestParams,
      });

      if (data && typeof data === 'object' && 'items' in data) {
        const items = Array.isArray(data.items) ? data.items : [];
        setSubscriptions(items.map(_enrichRow));
        if (data.pagination) {
          setPagination(data.pagination);
        }
      } else {
        const items = Array.isArray(data) ? data : [];
        setSubscriptions(items.map(_enrichRow));
        setPagination(null);
      }
    } catch {
      setSubscriptions([]);
      setPagination(null);
    }
  }, [request]);

  useEffect(() => { refetch(); }, [refetch]);

  return { data: subscriptions, pagination, loading, error, refetch };
}

function _enrichRow(row: any): any {
  return {
    ...row,
    _rawStatus: row.status,
    status: _STATUS_LABELS[row.status] || row.status,
  };
}
