import { ref, computed, type Ref } from "vue";

export function useSortablePaginated(dataRef: Ref<any[]>, itemsPerPage = 10) {
  const sortKey = ref<string | null>(null);
  const sortOrder = ref<"asc" | "desc">("asc");
  const currentPage = ref(1);

  const toggleSort = (key: string) => {
    if (sortKey.value === key) {
      sortOrder.value = sortOrder.value === "asc" ? "desc" : "asc";
    } else {
      sortKey.value = key;
      sortOrder.value = "asc";
    }
    currentPage.value = 1;
  };

  const sortedData = computed(() => {
    if (!sortKey.value) return dataRef.value;

    return [...dataRef.value].sort((a, b) => {
      const valA = a[sortKey.value!] ?? "";
      const valB = b[sortKey.value!] ?? "";

      if (valA < valB) return sortOrder.value === "asc" ? -1 : 1;
      if (valA > valB) return sortOrder.value === "asc" ? 1 : -1;
      return 0;
    });
  });

  const totalPages = computed(() => {
    const length = Array.isArray(sortedData.value) ? sortedData.value.length : 0;
    return Math.ceil(length / itemsPerPage);
  });


  const paginatedData = computed(() => {
    const data = sortedData.value ?? [];
    console.log(data);
    const start = (currentPage.value - 1) * itemsPerPage;
    return data.slice(start, start + itemsPerPage);
  });


  const visiblePages = computed(() => {
    const total = totalPages.value;
    const current = currentPage.value;
    const pages: { number: number | string; isDots: boolean; key: string | number }[] = [];

    if (total <= 5) {
      for (let i = 1; i <= total; i++) {
        pages.push({ number: i, isDots: false, key: i });
      }
    } else {
      pages.push({ number: 1, isDots: false, key: 1 });

      if (current > 3) {
        pages.push({ number: "...", isDots: true, key: "dots-start" });
      }

      const start = Math.max(2, current - 1);
      const end = Math.min(total - 1, current + 1);

      for (let i = start; i <= end; i++) {
        pages.push({ number: i, isDots: false, key: i });
      }

      if (current < total - 2) {
        pages.push({ number: "...", isDots: true, key: "dots-end" });
      }

      pages.push({ number: total, isDots: false, key: total });
    }

    return pages;
  });

  const goToPage = (page: number) => {
    if (page >= 1 && page <= totalPages.value) {
      currentPage.value = page;
    }
  };

  const negaraList = ref<string[]>([])

  const fetchNegara = async () => {
    const response = await fetch('https://restcountries.com/v3.1/all')
    const data = await response.json()
    negaraList.value = data.map((n: any) => n.name.common).sort()
  }

  const provinsiList = ref([])
  const fetchProvinsi = async () => {
    const res = await fetch('https://www.emsifa.com/api-wilayah-indonesia/api/provinces.json')
    provinsiList.value = await res.json()
  }


  return {
    sortKey,
    sortOrder,
    toggleSort,
    sortedData,
    paginatedData,
    totalPages,
    currentPage,
    visiblePages,
    itemsPerPage,
    negaraList,
    goToPage,
    fetchNegara,
    fetchProvinsi

  };
}
