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

// GraphQL Mutations
const CREATE_CUSTOMER_MUTATION = gql`
  mutation CreateCustomer($input: CreateCustomerInput!) {
    createCustomer(input: $input) {
      id
      companyId
      customerNumber
      customerType
      name
      cvr
      address
      postalCode
      city
      country
      email
      phone
      paymentTermsDays
      defaultRevenueAccountId
      subLedgerAccountId
      isActive
      createdAt
      updatedAt
    }
  }
`;

const UPDATE_CUSTOMER_MUTATION = gql`
  mutation UpdateCustomer($input: UpdateCustomerInput!) {
    updateCustomer(input: $input) {
      id
      companyId
      customerNumber
      customerType
      name
      cvr
      address
      postalCode
      city
      country
      email
      phone
      paymentTermsDays
      defaultRevenueAccountId
      subLedgerAccountId
      isActive
      createdAt
      updatedAt
    }
  }
`;

const DEACTIVATE_CUSTOMER_MUTATION = gql`
  mutation DeactivateCustomer($id: ID!) {
    deactivateCustomer(id: $id) {
      id
      companyId
      isActive
      updatedAt
    }
  }
`;

const REACTIVATE_CUSTOMER_MUTATION = gql`
  mutation ReactivateCustomer($id: ID!) {
    reactivateCustomer(id: $id) {
      id
      companyId
      isActive
      updatedAt
    }
  }
`;

// Input types
export interface CreateCustomerInput {
  companyId: string;
  customerType: 'BUSINESS' | 'PRIVATE';
  name: string;
  cvr?: string;
  address?: string;
  postalCode?: string;
  city?: string;
  country?: string;
  email?: string;
  phone?: string;
  paymentTermsDays?: number;
  defaultRevenueAccountId?: string;
}

export interface UpdateCustomerInput {
  id: string;
  name?: string;
  cvr?: string;
  address?: string;
  postalCode?: string;
  city?: string;
  country?: string;
  email?: string;
  phone?: string;
  paymentTermsDays?: number;
  defaultRevenueAccountId?: string;
}

// Response types
interface CreateCustomerResponse {
  createCustomer: Customer;
}

interface UpdateCustomerResponse {
  updateCustomer: Customer;
}

interface DeactivateCustomerResponse {
  deactivateCustomer: Customer;
}

interface ReactivateCustomerResponse {
  reactivateCustomer: Customer;
}

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

  return useMutation({
    mutationFn: async (input: CreateCustomerInput) => {
      const data = await fetchGraphQL<CreateCustomerResponse>(CREATE_CUSTOMER_MUTATION, { input });
      return data.createCustomer;
    },
    onSuccess: (data) => {
      // Invalidate customers list for this company
      queryClient.invalidateQueries({
        queryKey: createQueryKey('customers', { companyId: data.companyId }),
      });
      queryClient.invalidateQueries({
        queryKey: createQueryKey('activeCustomers', { companyId: data.companyId }),
      });
    },
  });
}

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

  return useMutation({
    mutationFn: async (input: UpdateCustomerInput) => {
      const data = await fetchGraphQL<UpdateCustomerResponse>(UPDATE_CUSTOMER_MUTATION, { input });
      return data.updateCustomer;
    },
    onSuccess: (data) => {
      // Update the specific customer in cache
      queryClient.setQueryData(createQueryKey('customer', { id: data.id }), data);
      // Invalidate lists
      queryClient.invalidateQueries({
        queryKey: createQueryKey('customers', { companyId: data.companyId }),
      });
      queryClient.invalidateQueries({
        queryKey: createQueryKey('activeCustomers', { companyId: data.companyId }),
      });
    },
  });
}

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

  return useMutation({
    mutationFn: async (id: string) => {
      const data = await fetchGraphQL<DeactivateCustomerResponse>(DEACTIVATE_CUSTOMER_MUTATION, { id });
      return data.deactivateCustomer;
    },
    onSuccess: (data) => {
      queryClient.invalidateQueries({
        queryKey: createQueryKey('customers', { companyId: data.companyId }),
      });
      queryClient.invalidateQueries({
        queryKey: createQueryKey('activeCustomers', { companyId: data.companyId }),
      });
      queryClient.invalidateQueries({
        queryKey: createQueryKey('customer', { id: data.id }),
      });
    },
  });
}

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

  return useMutation({
    mutationFn: async (id: string) => {
      const data = await fetchGraphQL<ReactivateCustomerResponse>(REACTIVATE_CUSTOMER_MUTATION, { id });
      return data.reactivateCustomer;
    },
    onSuccess: (data) => {
      queryClient.invalidateQueries({
        queryKey: createQueryKey('customers', { companyId: data.companyId }),
      });
      queryClient.invalidateQueries({
        queryKey: createQueryKey('activeCustomers', { companyId: data.companyId }),
      });
      queryClient.invalidateQueries({
        queryKey: createQueryKey('customer', { id: data.id }),
      });
    },
  });
}
