import { useMutation, useQueryClient } from '@tanstack/react-query';
import { gql } from 'graphql-request';
import { fetchGraphQL, createQueryKey } from '../client';
import type { Product } from '../queries/productQueries';

// GraphQL Mutations
const CREATE_PRODUCT_MUTATION = gql`
  mutation CreateProduct($input: CreateProductInput!) {
    createProduct(input: $input) {
      id
      companyId
      productNumber
      name
      description
      unitPrice
      vatCode
      unit
      defaultAccountId
      ean
      manufacturer
      isActive
      createdAt
      updatedAt
    }
  }
`;

const UPDATE_PRODUCT_MUTATION = gql`
  mutation UpdateProduct($input: UpdateProductInput!) {
    updateProduct(input: $input) {
      id
      companyId
      productNumber
      name
      description
      unitPrice
      vatCode
      unit
      defaultAccountId
      ean
      manufacturer
      isActive
      createdAt
      updatedAt
    }
  }
`;

const DEACTIVATE_PRODUCT_MUTATION = gql`
  mutation DeactivateProduct($id: ID!) {
    deactivateProduct(id: $id) {
      id
      companyId
      isActive
      updatedAt
    }
  }
`;

const REACTIVATE_PRODUCT_MUTATION = gql`
  mutation ReactivateProduct($id: ID!) {
    reactivateProduct(id: $id) {
      id
      companyId
      isActive
      updatedAt
    }
  }
`;

// Input types
export interface CreateProductInput {
  companyId: string;
  productNumber?: string;
  name: string;
  description?: string;
  unitPrice: number;
  vatCode: string;
  unit?: string;
  defaultAccountId?: string;
  ean?: string;
  manufacturer?: string;
}

export interface UpdateProductInput {
  id: string;
  productNumber?: string;
  name: string;
  description?: string;
  unitPrice: number;
  vatCode: string;
  unit?: string;
  defaultAccountId?: string;
  ean?: string;
  manufacturer?: string;
}

// Response types
interface CreateProductResponse {
  createProduct: Product;
}

interface UpdateProductResponse {
  updateProduct: Product;
}

interface DeactivateProductResponse {
  deactivateProduct: Product;
}

interface ReactivateProductResponse {
  reactivateProduct: Product;
}

/**
 * Hook to create a new product.
 */
export function useCreateProduct() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async (input: CreateProductInput) => {
      const data = await fetchGraphQL<CreateProductResponse>(CREATE_PRODUCT_MUTATION, { input });
      return data.createProduct;
    },
    onSuccess: (data) => {
      // Invalidate products list for this company
      queryClient.invalidateQueries({
        queryKey: createQueryKey('products', { companyId: data.companyId }),
      });
      queryClient.invalidateQueries({
        queryKey: createQueryKey('activeProducts', { companyId: data.companyId }),
      });
    },
  });
}

/**
 * Hook to update an existing product.
 */
export function useUpdateProduct() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async (input: UpdateProductInput) => {
      const data = await fetchGraphQL<UpdateProductResponse>(UPDATE_PRODUCT_MUTATION, { input });
      return data.updateProduct;
    },
    onSuccess: (data) => {
      // Update the specific product in cache
      queryClient.setQueryData(createQueryKey('product', { id: data.id }), data);
      // Invalidate lists
      queryClient.invalidateQueries({
        queryKey: createQueryKey('products', { companyId: data.companyId }),
      });
      queryClient.invalidateQueries({
        queryKey: createQueryKey('activeProducts', { companyId: data.companyId }),
      });
    },
  });
}

/**
 * Hook to deactivate a product.
 */
export function useDeactivateProduct() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async (id: string) => {
      const data = await fetchGraphQL<DeactivateProductResponse>(DEACTIVATE_PRODUCT_MUTATION, { id });
      return data.deactivateProduct;
    },
    onSuccess: (data) => {
      queryClient.invalidateQueries({
        queryKey: createQueryKey('products', { companyId: data.companyId }),
      });
      queryClient.invalidateQueries({
        queryKey: createQueryKey('activeProducts', { companyId: data.companyId }),
      });
      queryClient.invalidateQueries({
        queryKey: createQueryKey('product', { id: data.id }),
      });
    },
  });
}

/**
 * Hook to reactivate a product.
 */
export function useReactivateProduct() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async (id: string) => {
      const data = await fetchGraphQL<ReactivateProductResponse>(REACTIVATE_PRODUCT_MUTATION, { id });
      return data.reactivateProduct;
    },
    onSuccess: (data) => {
      queryClient.invalidateQueries({
        queryKey: createQueryKey('products', { companyId: data.companyId }),
      });
      queryClient.invalidateQueries({
        queryKey: createQueryKey('activeProducts', { companyId: data.companyId }),
      });
      queryClient.invalidateQueries({
        queryKey: createQueryKey('product', { id: data.id }),
      });
    },
  });
}
