import { computed, watch } from "vue";
import { useNuxtApp, useRoute, useState } from "#app";
import useLocalAuth from "./useLocalAuth";

export default function useOrg() {
  function getOrgs({
    page = 1,
    search = "",
    user = "",
    limit = 20,
    type = "organization",
  } = {}) {
    return useNuxtApp().$api<Record<string, any>>(
      `/api/organizations/user/${user}`,
      {
        method: "GET",
        query: {
          page,
          search,
          limit,
          type,
        },
      }
    );
  }

  const org = useState("org", (): TOrg => {
    return {
      _id: "",
      name: "",
      email: "",
      contact: "",
      busInst: "",
      type: "",
      status: "",
    };
  });

  function reset() {
    org.value._id = "";
    org.value.name = "";
    org.value.email = "";
    org.value.contact = "";
    org.value.busInst = "";
    org.value.type = "";
    org.value.status = "";
  }

  function set({
    _id = "",
    name = "",
    email = "",
    contact = "",
    busInst = "",
    type = "",
    status = "",
  } = {}) {
    org.value._id = _id;
    org.value.name = name;
    org.value.email = email;
    org.value.contact = contact;
    org.value.busInst = busInst;
    org.value.type = type;
    org.value.status = status;
  }

  const perSeatPrice = 8;
  const seats = useState("seats", () => 0);
  const total = computed(() => seats.value * perSeatPrice);

  function getByName(name = "") {
    return useNuxtApp().$api<TOrg>(`/api/organizations/name/${name}`, {
      method: "GET",
    });
  }

  function getById(id = "") {
    return useNuxtApp().$api<TOrg>(`/api/organizations/id/${id}`, {
      method: "GET",
    });
  }

  function getOrgById(id = "") {
    return useNuxtApp().$api<TOrg>(`/api/organizations/org/id/${id}`, {
      method: "GET",
    });
  }

  const { currentUser } = useLocalAuth();

  const currentOrg = useState("currentOrg", () => "");

  currentOrg.value =
    (useRoute().params.organization as string) ??
    currentUser.value?.defaultOrg ??
    "unknown";

  watch(currentUser, () => {
    if (!currentOrg.value) {
      currentOrg.value = currentUser.value?.defaultOrg ?? "unknown";
    }
  });

  function getAll({ page = 1, search = "", limit = 20, nature = "" } = {}) {
    return useNuxtApp().$api<Record<string, any>>("/api/organizations", {
      method: "GET",
      query: {
        page,
        search,
        limit,
        nature,
      },
    });
  }


  function add(
    value: Partial<Pick<TOrg, "name" | "email" | "nature" | "contact">>
  ) {
    return useNuxtApp().$api<TOrg>("/api/organizations", {
      method: "POST",
      body: value,
    });
  }

  function addOnboardingOrg(
    value: Partial<Pick<TOrg, "name" | "type" | "email" | "nature" | "contact">>
  ) {
    return useNuxtApp()
      .$api<Record<string, any>>("/api/organizations/onboarding", {
        method: "POST",
        body: value,
      })
      .then((response: Record<string, any>) => {
        return (
          response?.organization ?? response?.org ?? response?.data ?? response
        ) as TOrg;
      });
  }

  function completeOnboarding(id: string) {
    return useNuxtApp()
      .$api<Record<string, any>>(
        `/api/organizations/onboarding/complete/${id}`,
        {
          method: "POST",
        }
      )
      .then((response: Record<string, any>) => {
        return (response?.data ?? response?.organization ?? response) as TOrg;
      });
  }

  function updateOrg(
    id: string,
    value: Partial<Pick<TOrg, "name" | "type" | "email" | "nature" | "contact">>
  ) {
    return useNuxtApp()
      .$api<Record<string, any>>(`/api/organizations/${id}`, {
        method: "PUT",
        body: value,
      })
      .then((response: Record<string, any>) => {
        return (
          response?.data ?? response?.organization ?? response
        ) as TOrg;
      });
  }
  function getOrgsByEmail(email = "") {
    return useNuxtApp().$api<TOrg[]>(
      `/api/organizations/orgs/${email}`,
      {
        method: "GET",
      }
    );
  }
  function getAllV2({
    page = 1,
    search = "",
    limit = 20,
    nature = "",
    status = "active",

  }: {
    page?: number;
    search?: string;
    limit?: number;
    nature?: string;
    status?: "active" | "suspended" | "deleted";
  } = {}) {
    return useNuxtApp().$api<Record<string, any>>("/api/organizations/v2", {
      method: "GET",
      query: {
        page,
        search,
        limit,
        nature,
        status,
      },
    });
  }

  function getOrganizationsWithSubscription({
    page = 1,
    search = "",
    limit = 20,
    status = "active",
    type = "",
    billingCycle = "",
  }: {
    page?: number
    search?: string
    limit?: number
    status?: "active" | "suspended" | "deleted"
    type?: string
    billingCycle?: string
  } = {}) {
    return useNuxtApp().$api<Record<string, any>>(
      "/api/organizations/v2/orgs/subscriptions",
      {
        method: "GET",

        query: {
          page,
          search,
          limit,
          status,
          type,
          billingCycle,
        },
      }
    )
  }


  return {
    org,
    getOrgs,
    reset,
    set,
    perSeatPrice,
    seats,
    total,
    getByName,
    currentOrg,
    getById,
    getOrgById,
    getAll,
    getAllV2,
    add,
    addOnboardingOrg,
    updateOrg,
    getOrgsByEmail,
    getOrganizationsWithSubscription,
    completeOnboarding
  };
}
