import useSWR from "swr";

export interface Mapel {
  id: string;
  no: number;
  kodeMapel: string;
  namaMapel: string;
  createdAt: string;
  updatedAt: string;
}

export interface CreateMapelData {
  kodeMapel: string;
  namaMapel: string;
}

export type UpdateMapelData = CreateMapelData;

// Fetcher function
const fetcher = async (url: string) => {
  const headers: Record<string, string> = {
    "Content-Type": "application/json",
  };

  // Add authorization header if token exists in localStorage
  const localToken = localStorage.getItem("token");
  if (localToken) {
    headers.Authorization = `Bearer ${localToken}`;
  }

  const response = await fetch(url, {
    credentials: "include",
    headers,
  });

  if (!response.ok) {
    throw new Error("Failed to fetch");
  }

  const result = await response.json();
  return result.data;
};

export function useMapel(searchTerm?: string) {
  const url = searchTerm ? `/api/mapel?search=${encodeURIComponent(searchTerm)}` : "/api/mapel";

  const { data, error, mutate } = useSWR<Mapel[]>(url, fetcher, {
    refreshInterval: 0,
    revalidateOnFocus: false,
  });

  return {
    mapel: data || [],
    isLoading: !error && !data,
    isError: error,
    mutate,
  };
}

export async function createMapel(data: CreateMapelData): Promise<{ success: boolean; message?: string }> {
  try {
    const headers: Record<string, string> = {
      "Content-Type": "application/json",
    };

    // Add authorization header if token exists in localStorage
    const localToken = localStorage.getItem("token");
    if (localToken) {
      headers.Authorization = `Bearer ${localToken}`;
    }

    const response = await fetch("/api/mapel", {
      method: "POST",
      credentials: "include",
      headers,
      body: JSON.stringify(data),
    });

    const result = await response.json();

    if (response.ok) {
      return { success: true, message: result.message };
    } else {
      return { success: false, message: result.message };
    }
  } catch (error) {
    console.error("Error creating mapel:", error);
    return { success: false, message: "Terjadi kesalahan saat menambah mata pelajaran" };
  }
}

export async function updateMapel(id: string, data: UpdateMapelData): Promise<{ success: boolean; message?: string }> {
  try {
    const headers: Record<string, string> = {
      "Content-Type": "application/json",
    };

    // Add authorization header if token exists in localStorage
    const localToken = localStorage.getItem("token");
    if (localToken) {
      headers.Authorization = `Bearer ${localToken}`;
    }

    const response = await fetch(`/api/mapel/${id}`, {
      method: "PUT",
      credentials: "include",
      headers,
      body: JSON.stringify(data),
    });

    const result = await response.json();

    if (response.ok) {
      return { success: true, message: result.message };
    } else {
      return { success: false, message: result.message };
    }
  } catch (error) {
    console.error("Error updating mapel:", error);
    return { success: false, message: "Terjadi kesalahan saat memperbarui mata pelajaran" };
  }
}

export async function deleteMapel(id: string): Promise<{ success: boolean; message?: string }> {
  try {
    const headers: Record<string, string> = {};

    // Add authorization header if token exists in localStorage
    const localToken = localStorage.getItem("token");
    if (localToken) {
      headers.Authorization = `Bearer ${localToken}`;
    }

    const response = await fetch(`/api/mapel/${id}`, {
      method: "DELETE",
      credentials: "include",
      headers,
    });

    const result = await response.json();

    if (response.ok) {
      return { success: true, message: result.message };
    } else {
      return { success: false, message: result.message };
    }
  } catch (error) {
    console.error("Error deleting mapel:", error);
    return { success: false, message: "Terjadi kesalahan saat menghapus mata pelajaran" };
  }
}
