import { useQuery, UseQueryOptions } from '@tanstack/react-query';
import { gql } from 'graphql-request';
import { fetchGraphQL, createQueryKey } from '../client';
import type { Product } from '@/types/product';

// Re-export Product type for backwards compatibility
export type { Product } from '@/types/product';

// GraphQL Queries
const PRODUCTS_QUERY = gql`
  query Products($companyId: ID!) {
    products(companyId: $companyId) {
      id
      companyId
      productNumber
      name
      description
      unitPrice
      vatCode
      unit
      defaultAccountId
      ean
      manufacturer
      isActive
      createdAt
      updatedAt
    }
  }
`;

const PRODUCT_QUERY = gql`
  query Product($id: ID!) {
    product(id: $id) {
      id
      companyId
      productNumber
      name
      description
      unitPrice
      vatCode
      unit
      defaultAccountId
      ean
      manufacturer
      isActive
      createdAt
      updatedAt
    }
  }
`;

// Response types
interface ProductsResponse {
  products: Product[];
}

interface ProductResponse {
  product: Product | null;
}

/**
 * Hook to fetch all products for a company.
 */
export function useProducts(
  companyId: string | undefined,
  options?: Omit<UseQueryOptions<Product[], Error>, 'queryKey' | 'queryFn'>
) {
  return useQuery({
    queryKey: createQueryKey('products', { companyId }),
    queryFn: async () => {
      if (!companyId) return [];
      const data = await fetchGraphQL<ProductsResponse>(PRODUCTS_QUERY, { companyId });
      return data.products;
    },
    enabled: !!companyId,
    ...options,
  });
}

/**
 * Hook to fetch active products for a company.
 */
export function useActiveProducts(
  companyId: string | undefined,
  options?: Omit<UseQueryOptions<Product[], Error>, 'queryKey' | 'queryFn'>
) {
  return useQuery({
    queryKey: createQueryKey('activeProducts', { companyId }),
    queryFn: async () => {
      if (!companyId) return [];
      const data = await fetchGraphQL<ProductsResponse>(PRODUCTS_QUERY, { companyId });
      return data.products.filter((p) => p.isActive);
    },
    enabled: !!companyId,
    ...options,
  });
}

/**
 * Hook to fetch a single product by ID.
 */
export function useProduct(
  id: string | undefined,
  options?: Omit<UseQueryOptions<Product | null, Error>, 'queryKey' | 'queryFn'>
) {
  return useQuery({
    queryKey: createQueryKey('product', { id }),
    queryFn: async () => {
      if (!id) return null;
      const data = await fetchGraphQL<ProductResponse>(PRODUCT_QUERY, { id });
      return data.product;
    },
    enabled: !!id,
    ...options,
  });
}

// GraphQL Query for manufacturers autocomplete
const MANUFACTURERS_QUERY = gql`
  query Manufacturers($companyId: ID!, $searchTerm: String) {
    manufacturers(companyId: $companyId, searchTerm: $searchTerm)
  }
`;

interface ManufacturersResponse {
  manufacturers: string[];
}

/**
 * Hook to fetch manufacturers for autocomplete.
 */
export function useManufacturers(
  companyId: string | undefined,
  searchTerm?: string,
  options?: Omit<UseQueryOptions<string[], Error>, 'queryKey' | 'queryFn'>
) {
  return useQuery({
    queryKey: createQueryKey('manufacturers', { companyId, searchTerm }),
    queryFn: async () => {
      if (!companyId) return [];
      const data = await fetchGraphQL<ManufacturersResponse>(MANUFACTURERS_QUERY, {
        companyId,
        searchTerm: searchTerm || undefined,
      });
      return data.manufacturers;
    },
    enabled: !!companyId,
    ...options,
  });
}
