import { ref, computed } from "vue";
import { useAreasStore } from "../stores/areas";

export function useAreaAssign() {
  const areasStore = useAreasStore();
  const excludeId = ref("");

  const areaOptions = computed(() =>
    areasStore.areas
      .filter((a) => String(a.id) !== String(excludeId.value))
      .map((a) => ({
        value: String(a.id),
        label: `${a.display_name} (${a.type})`,
      }))
  );

  const showAssignModal = ref(false);
  const selectedAreaId = ref("");
  const assignLoading = ref(false);
  const assignError = ref("");

  function openAssign(currentAreaId) {
    selectedAreaId.value = currentAreaId ? String(currentAreaId) : "";
    excludeId.value = currentAreaId ? String(currentAreaId) : "";
    assignError.value = "";
    showAssignModal.value = true;
  }

  async function submitAssignCore(itemId, assignFn) {
    if (!itemId || !assignFn) {
      return;
    }
    assignLoading.value = true;
    assignError.value = "";

    const result = await assignFn(itemId, selectedAreaId.value);
    assignLoading.value = false;

    if (!result.ok) {
      assignError.value = result.error?.message || "Failed to assign area";
      return result;
    }

    showAssignModal.value = false;
    return result;
  }

  return {
    areaOptions,
    showAssignModal,
    selectedAreaId,
    assignLoading,
    assignError,
    openAssign,
    submitAssignCore,
  };
}
