import { ref, reactive, computed } from "vue";
import type { Ref, ComputedRef } from "vue";
import { router } from "@inertiajs/vue3";
import type { FieldDefinition } from "../components/fields/types";

export type BulkEditState = {
  bulkEditSheetOpen: Ref<boolean>;
  editableFields: ComputedRef<FieldDefinition[]>;
  bulkEditForm: Record<string, unknown>;
  openBulkEdit(): void;
  executeBulkEdit(): void;
};

export function useBulkEdit(
  resourceSlug: string,
  resourceFields: ComputedRef<FieldDefinition[]>,
  selectedIds: Ref<Set<unknown>>,
  isSelectAllRecords: Ref<boolean>,
  searchQuery: Ref<string>,
  activeFilters: Ref<Record<string, string>>,
  currentLocale: string | null,
  prefix: string,
  clearSelection: () => void,
): BulkEditState {
  const bulkEditSheetOpen = ref(false);

  const editableFields = computed<FieldDefinition[]>(() =>
    resourceFields.value.filter(
      (f) =>
        !f.readonly &&
        f.component !== "HiddenInput" &&
        f.component !== "PasswordInput",
    ),
  );

  const bulkEditForm = reactive<Record<string, unknown>>(
    Object.fromEntries(
      resourceFields.value
        .filter(
          (f) =>
            !f.readonly &&
            f.component !== "HiddenInput" &&
            f.component !== "PasswordInput",
        )
        .map((f) => [f.name, null]),
    ),
  );

  function openBulkEdit(): void {
    for (const key of Object.keys(bulkEditForm)) {
      bulkEditForm[key] = null;
    }
    bulkEditSheetOpen.value = true;
  }

  function executeBulkEdit(): void {
    const data: Record<string, unknown> = {};
    for (const [k, v] of Object.entries(bulkEditForm)) {
      if (v !== null && v !== "" && v !== undefined) {
        data[k] = v;
      }
    }

    const payload: Record<string, unknown> = { action: "bulk_update", data };
    if (currentLocale) payload.locale = currentLocale;

    if (isSelectAllRecords.value) {
      payload.select_all = true;
      if (searchQuery.value) payload.search = searchQuery.value;
      if (Object.keys(activeFilters.value).length > 0) {
        payload.filters = activeFilters.value;
      }
    } else {
      payload.ids = Array.from(selectedIds.value);
    }

    router.post(`/${prefix}/${resourceSlug}/bulk`, payload);
    clearSelection();
    bulkEditSheetOpen.value = false;
  }

  return {
    bulkEditSheetOpen,
    editableFields,
    bulkEditForm,
    openBulkEdit,
    executeBulkEdit,
  };
}
