import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import {
  fetchDashboardWidgets,
  createDashboardWidget,
  updateDashboardWidget,
  deleteDashboardWidget,
  reorderDashboardWidgets,
  type DashboardWidget,
  type DashboardWidgetKind,
} from '../api';

const QK = ['dashboard', 'widgets'] as const;

export function useDashboardWidgets() {
  const qc = useQueryClient();

  const list = useQuery({
    queryKey: QK,
    queryFn: fetchDashboardWidgets,
    staleTime: 10_000,
  });

  const create = useMutation({
    mutationFn: (input: { slug: string; title: string; content?: string; kind?: DashboardWidgetKind }) =>
      createDashboardWidget(input),
    onSuccess: () => qc.invalidateQueries({ queryKey: QK }),
  });

  const update = useMutation({
    mutationFn: ({ id, patch }: { id: number; patch: { title?: string; content?: string } }) =>
      updateDashboardWidget(id, patch),
    onSuccess: () => qc.invalidateQueries({ queryKey: QK }),
  });

  const remove = useMutation({
    mutationFn: (id: number) => deleteDashboardWidget(id),
    onSuccess: () => qc.invalidateQueries({ queryKey: QK }),
  });

  const reorder = useMutation({
    mutationFn: (ids: number[]) => reorderDashboardWidgets(ids),
    onSuccess: () => qc.invalidateQueries({ queryKey: QK }),
  });

  return {
    widgets: list.data ?? [],
    isLoading: list.isLoading,
    isError: list.isError,
    create,
    update,
    remove,
    reorder,
  };
}

export type { DashboardWidget };
