import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import {
  ClientDetailSchema,
  ClientListResponseSchema,
  ClientNovoResultSchema,
  ContatoResultSchema,
  ContatoSchema,
  CtrSummarySchema,
  CtrTituloSchema,
  NotaFiscalSchema,
  PedidoSummarySchema,
  TopProdutoSchema,
  type ClientDetail,
  type ClientListQuery,
  type ClientListResponse,
  type ClientNovoResult,
  type Contato,
  type ContatoResult,
  type CtrSummary,
  type CtrTitulo,
  type CreateClientNovo,
  type CreateContato,
  type NotaFiscal,
  type PedidoSummary,
  type TopProduto,
} from '@sar/api-interface';
import { z } from 'zod';
import { apiFetch } from '../api-client';

export const CLIENT_KEYS = {
  all: ['clients'] as const,
  list: (params: Partial<ClientListQuery>) => ['clients', 'list', params] as const,
  detail: (id: number) => ['clients', 'detail', id] as const,
};

export function useClientList(params: Partial<ClientListQuery> = {}) {
  const qs = new URLSearchParams();
  if (params.q) qs.set('q', params.q);
  if (params.status) qs.set('status', params.status);
  if (params.page) qs.set('page', String(params.page));
  if (params.limit) qs.set('limit', String(params.limit));

  const query = qs.toString();

  return useQuery<ClientListResponse, Error>({
    queryKey: CLIENT_KEYS.list(params),
    queryFn: async () => {
      const res = await apiFetch(`/clients${query ? `?${query}` : ''}`);
      return ClientListResponseSchema.parse(res);
    },
  });
}

export function useClientDetail(id: number | string | undefined) {
  return useQuery<ClientDetail, Error>({
    queryKey: CLIENT_KEYS.detail(Number(id)),
    queryFn: async () => {
      const res = await apiFetch(`/clients/${id}`);
      return ClientDetailSchema.parse(res);
    },
    enabled: !!id,
  });
}

export function useClientTopProdutos(idCliente: number | undefined, limit = 30) {
  return useQuery<TopProduto[]>({
    queryKey: ['clients', 'top-produtos', idCliente, limit],
    queryFn: async () => {
      const res = await apiFetch(`/clients/${idCliente}/top-produtos?limit=${limit}`);
      return z.array(TopProdutoSchema).parse(res);
    },
    enabled: !!idCliente,
  });
}

export function useClientOrdersHistory(idCliente: number | undefined, limit = 50) {
  return useQuery<PedidoSummary[]>({
    queryKey: ['clients', 'orders-history', idCliente, limit],
    queryFn: async () => {
      const res = await apiFetch(`/clients/${idCliente}/orders-history?limit=${limit}`);
      return z.array(PedidoSummarySchema).parse(res);
    },
    enabled: !!idCliente,
  });
}

export function useClientCtrList(idCliente: number | undefined, limit = 60) {
  return useQuery<CtrTitulo[]>({
    queryKey: ['clients', 'ctr-list', idCliente, limit],
    queryFn: async () => {
      const res = await apiFetch(`/clients/${idCliente}/ctr-list?limit=${limit}`);
      return z.array(CtrTituloSchema).parse(res);
    },
    enabled: !!idCliente,
  });
}

export function useClientNotasFiscais(idCliente: number | undefined, limit = 30) {
  return useQuery<NotaFiscal[]>({
    queryKey: ['clients', 'notas', idCliente, limit],
    queryFn: async () => {
      const res = await apiFetch(`/clients/${idCliente}/notas?limit=${limit}`);
      return z.array(NotaFiscalSchema).parse(res);
    },
    enabled: !!idCliente,
  });
}

export function useClientCtr(idCliente: number | undefined) {
  return useQuery<CtrSummary>({
    queryKey: ['clients', 'ctr', idCliente],
    queryFn: async () => {
      const res = await apiFetch(`/clients/${idCliente}/ctr`);
      return CtrSummarySchema.parse(res);
    },
    enabled: !!idCliente,
  });
}

export function useClientContacts(idCliente: number | undefined) {
  return useQuery<Contato[]>({
    queryKey: ['clients', 'contacts', idCliente],
    queryFn: async () => {
      const res = await apiFetch(`/clients/${idCliente}/contacts`);
      return z.array(ContatoSchema).parse(res);
    },
    enabled: !!idCliente,
  });
}

export function useCreateContato(idCliente: number | undefined) {
  const queryClient = useQueryClient();
  return useMutation<ContatoResult, Error, CreateContato>({
    mutationFn: async (data) => {
      const res = await apiFetch(`/clients/${idCliente}/contacts`, {
        method: 'POST',
        body: data,
      });
      return ContatoResultSchema.parse(res);
    },
    onSuccess: () => {
      void queryClient.invalidateQueries({ queryKey: ['clients', 'contacts', idCliente] });
    },
  });
}

export function useCreateClientNovo() {
  const queryClient = useQueryClient();
  return useMutation<ClientNovoResult, Error, CreateClientNovo>({
    mutationFn: async (data) => {
      const res = await apiFetch('/clients/novo', {
        method: 'POST',
        body: data,
      });
      return ClientNovoResultSchema.parse(res);
    },
    onSuccess: () => {
      void queryClient.invalidateQueries({ queryKey: CLIENT_KEYS.all });
    },
  });
}
