import axios from "axios";
import FormData from "form-data";
import { useAuthStore } from "@/store/authStore";

const API_URL = "https://hopp.zikor.pl/api/v1";

export async function listNotices() {
  const { token } = useAuthStore.getState();
  const headers = token ? { Authorization: `Bearer ${token}` } : {};

  const response = await fetch(`${API_URL}/notices/get/all`, {
    headers: headers,
  });
  const data = await response.json();

  if (!response.ok) {
    throw new Error(response.toString());
  }
  // console.info("Notices fetched successfully:", data);
  return data;
}

export async function getNoticeById(noticeId) {
  const response = await fetch(`${API_URL}/notices/get/${noticeId}`);

  const data = await response.json();
  if (!response.ok) {
    throw new Error("Error");
  }
  return data;
}

export async function createNotice(notice) {
  const { token } = useAuthStore.getState();
  const headers = token ? { Authorization: `Bearer ${token}` } : {};
  try {
    const response = await axios.post(`${API_URL}/notices/add`, notice, {
      headers: headers,
    });

    if (response.data.noticeId !== null) {
      for (const image of notice.image) {
        if (notice.image.indexOf(image) === 0) {
          await uploadImage(response.data.noticeId, image, true);
        } else {
          await uploadImage(response.data.noticeId, image, false);
        }
        console.log("Image uploaded successfully");
      }
    }

    return response.data;
  } catch (error) {
    console.log("Error", error.response.data, error.response.status);
    return null;
  }
}

export async function getImageByNoticeId(noticeId) {
  let imageUrl;
  try {
    const listResponse = await axios.get(`${API_URL}/images/list/${noticeId}`);

    const imageName = listResponse.data[0];
    imageUrl = `${API_URL}/images/get/${imageName}`;

    return imageUrl;
  } catch (err) {
    imageUrl = "https://http.cat/404.jpg";
    return imageUrl;
  }
}

export async function getAllImagesByNoticeId(noticeId) {
  const { token } = useAuthStore.getState();
  const headers = token ? { Authorization: `Bearer ${token}` } : {};
  try {
    const listResponse = await axios.get(`${API_URL}/images/list/${noticeId}`, {
      headers: headers,
    });

    if (listResponse.data && listResponse.data.length > 0) {
      return listResponse.data.map((imageName) => ({
        uri: `${API_URL}/images/get/${imageName}`,
        headers: headers,
      }));
    }

    return [{ uri: "https://http.cat/404.jpg" }];
  } catch (err) {
    if (err.response.status === 404) {
      // console.info(`Ogłoszenie o id: ${noticeId} nie posiada zdjęć.`);
      return [{ uri: "https://http.cat/404.jpg" }];
    }
    console.warn(
      `Nie udało się pobrać listy zdjęć dla ogłoszenia o id: ${noticeId}`,
      err
    );
    return [{ uri: "https://http.cat/404.jpg" }];
  }
}

export const uploadImage = async (noticeId, imageObj, isFirst) => {
  const { token } = useAuthStore.getState();
  const headers = {
    ...(token ? { Authorization: `Bearer ${token}` } : {}),
    "Content-Type": "multipart/form-data",
  };
  const formData = new FormData();

  const filename = imageObj.split("/").pop();

  const match = /\.(\w+)$/.exec(filename);
  const type = match ? `image/${match[1]}` : "image/jpeg";

  formData.append("file", {
    uri: imageObj,
    name: filename,
    type: type,
  });

  try {
    const response = await axios.post(
      `${API_URL}/images/upload/${noticeId}?isMainImage=${isFirst}`,
      formData,
      {
        headers: headers,
      }
    );
    console.log("Upload successful:", response.data);
    return response.data;
  } catch (error) {
    console.error(
      "Error uploading image:",
      error.response.data,
      error.response.status
    );
    throw error;
  }
};

export const deleteNotice = async (noticeId) => {
  const { token } = useAuthStore.getState();
  const headers = token ? { Authorization: `Bearer ${token}` } : {};

  try {
    const response = await axios.delete(
      `${API_URL}/notices/delete/${noticeId}`,
      { headers: headers }
    );
    return response.data;
  } catch (error) {
    console.error(
      "Error deleting notice:",
      error.response?.data,
      error.response?.status
    );
    throw error;
  }
};

export const editNotice = async (noticeId, notice) => {
  const { token } = useAuthStore.getState();
  const headers = token ? { Authorization: `Bearer ${token}` } : {};

  try {
    const response = await axios.put(
      `${API_URL}/notices/edit/${noticeId}`,
      {
        title: notice.title,
        description: notice.description,
        price: notice.price,
        category: notice.category,
        status: notice.status,
        attributes: notice.attributes,
      },
      {
        headers: headers,
      }
    );

    if (response.data && notice.image && notice.image.length > 0) {
      for (let i = 0; i < notice.image.length; i++) {
        const image = notice.image[i];
        const isFirst = i === 0;

        if (typeof image === "string" && !image.startsWith("http")) {
          await uploadImage(noticeId, image, isFirst);
        }
      }
    }

    return response.data;
  } catch (error) {
    console.error(
      "Error editing notice:",
      error.response?.data,
      error.response?.status
    );
    throw error;
  }
};

export const deleteImage = async (filename) => {
  const { token } = useAuthStore.getState();
  const headers = token ? { Authorization: `Bearer ${token}` } : {};

  try {
    const response = await axios.delete(
      `${API_URL}/images/delete/${filename}`,
      { headers: headers }
    );
    return response.data;
  } catch (error) {
    console.error(
      "Error deleting image:",
      error.response?.data,
      error.response?.status
    );
    throw error;
  }
};
