'use client';

import { useState } from 'react';
import { useQuery, useQueryClient, useMutation } from '@tanstack/react-query';

import { apiFetch } from '@/lib/api/client';
import type { SavedView } from '@/lib/db/schema/system';

export function useSavedViews(entityType: string) {
  const queryClient = useQueryClient();
  const [activeViewId, setActiveViewId] = useState<string | null>(null);

  const queryKey = ['savedViews', entityType];

  const { data: views = [] } = useQuery<SavedView[]>({
    queryKey,
    queryFn: () =>
      apiFetch<{ data: SavedView[] }>(`/api/v1/saved-views?entityType=${entityType}`).then(
        (r) => r.data,
      ),
  });

  const saveMutation = useMutation({
    mutationFn: (params: {
      name: string;
      filters: Record<string, unknown>;
      sortConfig?: unknown;
    }) =>
      apiFetch<{ data: SavedView }>('/api/v1/saved-views', {
        method: 'POST',
        body: { ...params, entityType },
      }),
    onSuccess: () => queryClient.invalidateQueries({ queryKey }),
  });

  const deleteMutation = useMutation({
    mutationFn: (viewId: string) => apiFetch(`/api/v1/saved-views/${viewId}`, { method: 'DELETE' }),
    onSuccess: () => queryClient.invalidateQueries({ queryKey }),
  });

  async function saveCurrentView(
    name: string,
    filters: Record<string, unknown>,
    sortConfig?: unknown,
  ) {
    await saveMutation.mutateAsync({ name, filters, sortConfig });
  }

  function deleteView(viewId: string) {
    if (activeViewId === viewId) setActiveViewId(null);
    deleteMutation.mutate(viewId);
  }

  function applyView(viewId: string) {
    setActiveViewId(viewId);
  }

  return {
    views,
    activeViewId,
    saveCurrentView,
    deleteView,
    applyView,
  };
}
