import { useQuery } from '@tanstack/react-query';
import { api } from '@/shared/lib/apiClient';
import { unwrapArray } from '@/shared/lib/apiShape';

/**
 * useKanban — Pipeline Pillar kanban board data
 * Returns leads grouped by stage.
 */
export function useKanban() {
  const query = useQuery({
    queryKey: ['kanban'],
    queryFn: async () => {
      const payload = await api.get<unknown>('/crm/pipeline/kanban?limit=250&offset=0');
      return unwrapArray<RawKanbanStage>(payload).map(normalizeStage);
    },
    staleTime: 30_000,
    refetchInterval: 60_000,
    refetchOnMount: 'always',
    refetchOnWindowFocus: true,
    retry: 1,
  });
  return {
    stages: query.data ?? [],
    isLoading: query.isLoading,
    isError: query.isError,
    error: query.error,
    refetch: query.refetch,
  };
}

export interface KanbanStage {
  id: string;
  label: string;
  emoji: string;
  leads: KanbanLead[];
}

export interface KanbanLead {
  id: string;
  name: string;
  location?: string;
  qdScore: number;
  qdDelta?: number;
  lastContactRelative: string;
  lastContactChannel: string;
  isVaultActive?: boolean;
}

interface RawKanbanStage {
  id?: string;
  stage?: string;
  status?: string;
  label?: string;
  emoji?: string;
  leads?: unknown;
  items?: unknown;
  data?: unknown;
}

function normalizeStage(stage: RawKanbanStage): KanbanStage {
  const id = String(stage.id ?? stage.stage ?? stage.status ?? 'new');
  const leads = unwrapArray<KanbanLead>(stage.leads ?? stage.items ?? stage.data).map(normalizeLead);
  return {
    id,
    label: String(stage.label ?? id.replace(/_/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase())),
    emoji: String(stage.emoji ?? id.slice(0, 1).toUpperCase()),
    leads,
  };
}

function normalizeLead(lead: Partial<KanbanLead>): KanbanLead {
  return {
    ...lead,
    id: String(lead.id),
    name: String(lead.name ?? 'Unnamed Client'),
    qdScore: Number.isFinite(Number(lead.qdScore)) ? Number(lead.qdScore) : 0,
    lastContactRelative: String(lead.lastContactRelative ?? 'No contact yet'),
    lastContactChannel: String(lead.lastContactChannel ?? 'crm'),
  };
}
