export type ProtocolStatus =
  | 'Criado'
  | 'Tramitado'
  | 'Recebido'
  | 'Finalizado'
  | 'Cancelado'
  | 'Arquivado'
  | 'Enviado'
  | 'Aguardando';

export type Protocol = {
  id: string;
  title: string;
  date: string;
  sender: string;
  location: string;
  status: ProtocolStatus;
};

const statuses: ProtocolStatus[] = [
  'Criado',
  'Tramitado',
  'Recebido',
  'Finalizado',
  'Cancelado',
  'Arquivado',
  'Enviado',
  'Aguardando',
];

// generate mock data
const protocols: Protocol[] = Array.from({ length: 120 }).map((_, i) => {
  const status = statuses[i % statuses.length];
  return {
    id: String(1000 + i),
    title: `NOTA FISCAL ${1000 + i}`,
    date: new Date(Date.now() - i * 1000 * 60 * 60 * 24)
      .toISOString()
      .split('T')[0],
    sender: `PREFEITURA ${i % 10}`,
    location: ['Sala do financeiro', 'Protocolo Central', 'Expediente'][i % 3],
    status,
  };
});

export type ProtocolsPage = {
  items: Protocol[];
  total: number;
};

export function getProtocols({
  status,
  page = 1,
  pageSize = 10,
  search = '',
}: {
  status?: ProtocolStatus | 'Todos';
  page?: number;
  pageSize?: number;
  search?: string;
}): Promise<ProtocolsPage> {
  return new Promise((resolve) => {
    setTimeout(() => {
      let items = protocols.slice();
      if (status && status !== 'Todos') {
        items = items.filter((p) => p.status === status);
      }
      if (search) {
        const q = search.toLowerCase();
        items = items.filter(
          (p) =>
            p.title.toLowerCase().includes(q) ||
            p.sender.toLowerCase().includes(q),
        );
      }
      const total = items.length;
      const start = (page - 1) * pageSize;
      const paged = items.slice(start, start + pageSize);
      resolve({ items: paged, total });
    }, 250);
  });
}

export function getCounts() {
  const counts: Record<string, number> = { Todos: protocols.length };
  for (const s of statuses) {
    counts[s] = protocols.filter((p) => p.status === s).length;
  }
  return counts;
}
