import axios from "axios";
import { toast } from "react-toastify";

// Types for profile actions
export interface ProfileData {
  first_name?: string;
  last_name?: string;
  username?: string;
  email?: string;
  phone_number?: string;
  country_code?: string;
  address?: {
    address_line_1?: string;
    address_line_2?: string;
    city?: { _id: number; name: string };
    state?: { _id: number; name: string };
    country?: { _id: number; name: string };
    postal_code?: string;
    country_code?: string;
    contact_number?: string;
    short_address?: string;
    building_name?: string;
    street?: string;
    secondary_number?: string;
    district?: string;
  };
  profile?: {
    file_path?: string;
  };
  createdAt?: string;
}

export interface FollowData {
  following: any[];
  followers: any[];
  totalFollowing: number;
  totalFollowers: number;
}

// Fetch user profile data
export const fetchUserProfile = async (token: string,locale: string): Promise<{ userData: ProfileData }> => {
  try {
    const response = await axios.get(`${process.env.NEXT_PUBLIC_API_URL}/profile`, {
        headers: {
          Authorization: `Bearer ${token}`,
          "Accept-Language": locale,
        },
      });

    if (response.data.status) {
      return { userData: response.data };
    } else {
      throw new Error(response.data.message || "Failed to fetch profile");
    }
  } catch (error: any) {
    if (error.response?.status === 401) {
      throw { isAuthError: true, status: 401, originalError: error };
    }
    throw error;
  }
};

// Update profile data
export const updateProfile = async (
  token: string,
  profileData: any,
  locale: string,
): Promise<{ success: boolean; data?: any; message?: string }> => {
  try {
    const response = await axios.post(
      `${process.env.NEXT_PUBLIC_API_URL}/profile`,
      profileData,
      {
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`,
          "Accept-Language": locale,
        },
      },
    );

    if (response.data.status) {
      return { success: true, data: response.data };
    } else {
      return { success: false, message: response.data.message };
    }
  } catch (error: any) {
    if (error.response?.status === 401) {
      throw { isAuthError: true, status: 401, originalError: error };
    }
    throw error;
  }
};

// Update profile image
export const updateProfileImage = async (
  token: string,
  file: File,
  locale: string,
): Promise<{ success: boolean; data?: any; message?: string }> => {
  try {
    const formData = new FormData();
    formData.append("profile", file);

    const response = await axios.post(
      `${process.env.NEXT_PUBLIC_API_URL}/profile/file`,
      formData,
      {
        headers: {
          "Content-Type": "multipart/form-data",
          Authorization: `Bearer ${token}`,
          "Accept-Language": locale,
        },
      },
    );

    if (response.data.status) {
      return { success: true, data: response.data };
    } else {
      return { success: false, message: response.data.message };
    }
  } catch (error: any) {
    if (error.response?.status === 401) {
      throw { isAuthError: true, status: 401, originalError: error };
    }
    throw error;
  }
};

// Fetch follow data
export const fetchFollowData = async (
  token: string,
  page: number = 1,
  searchTerm: string = "",
  locale: string,
): Promise<{ success: boolean; data?: any; message?: string }> => {
  try {
    const response = await axios.get(
      `${process.env.NEXT_PUBLIC_API_URL}/follow?page=${page}&limit=20&search=${searchTerm}`,
      {
        headers: {
          Authorization: `Bearer ${token}`,
          "Accept-Language": locale,
        },
      },
    );

    if (response.data.status) {
      return { success: true, data: response.data.data };
    } else {
      return { success: false, message: response.data.message };
    }
  } catch (error: any) {
    if (error.response?.status === 401) {
      throw { isAuthError: true, status: 401, originalError: error };
    }
    throw error;
  }
};

// Follow user
export const followUser = async (
  token: string,
  userId: string,
): Promise<{ success: boolean; message?: string }> => {
  try {
    const response = await axios.post(
      `${process.env.NEXT_PUBLIC_API_URL}/follow`,
      { followingId: userId },
      {
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`,
        },
      },
    );

    if (response.data.status) {
      return { success: true };
    } else {
      return { success: false, message: response.data.message };
    }
  } catch (error: any) {
    if (error.response?.status === 401) {
      throw { isAuthError: true, status: 401, originalError: error };
    }
    throw error;
  }
};

// Unfollow user
export const unfollowUser = async (
  token: string,
  userId: string,
): Promise<{ success: boolean; message?: string }> => {
  try {
    const response = await axios.delete(
      `${process.env.NEXT_PUBLIC_API_URL}/follow/${userId}`,
      {
        headers: {
          Authorization: `Bearer ${token}`,
        },
      },
    );

    if (response.data.status) {
      return { success: true };
    } else {
      return { success: false, message: response.data.message };
    }
  } catch (error: any) {
    if (error.response?.status === 401) {
      throw { isAuthError: true, status: 401, originalError: error };
    }
    throw error;
  }
};

// Helper function to populate form data
export const populateFormData = (userProfile: any) => {
  if (!userProfile) return null;

  const userData = userProfile?.data?.data || userProfile?.data || userProfile;
  const address = userData?.address || {};
  const longitude = userData?.location?.coordinates?.[0];
  const latitude = userData?.location?.coordinates?.[1];
  return {
    first_name: userData?.first_name || "",
    last_name: userData?.last_name || "",
    username: userData?.username || "",
    email: userData?.email || "",
    latitude: latitude !== undefined ? latitude.toString() : "",
    longitude: longitude !== undefined ? longitude.toString() : "",
    phone:
      userData?.country_code && userData?.phone_number
        ? `${userData.country_code}${userData.phone_number}`
        : userData?.phone_number || "",
    address_phone:
      address?.country_code && address?.contact_number
        ? `${address.country_code}${address.contact_number}`
        : address?.contact_number || "",
    short_address: address?.short_address || "",
    building_name: address?.building_name || "",
    street: address?.street || "",
    secondary_number: address?.secondary_number || "",
    district: address?.district || "",
    address_line_1: address?.address_line_1 || "",
    address_line_2: address?.address_line_2 || "",
    state: address?.state
      ? {
          value: address.state._id?.toString() || "",
          label: address.state.name || "",
        }
      : { value: "", label: "" },
    city: address?.city
      ? {
          value: address.city._id?.toString() || "",
          label: address.city.name || "",
        }
      : { value: "", label: "" },
    postal_code: address?.postal_code || "",
    profileCanUpdate: userData?.profileCanUpdate,
  };
};

// Helper function to extract user data
export const extractUserData = (userProfile: any) => {
  return userProfile?.data?.data || userProfile?.data || userProfile;
};

// Helper function to filter follow data
export const filterFollowData = (
  data: any[],
  searchTerm: string,
  type: "following" | "followers",
): any[] => {
  if (!searchTerm.trim()) return data;

  const searchLower = searchTerm.toLowerCase().trim();

  return data.filter((item) => {
    const user = type === "followers" ? item.followerId : item.followingId;

    if (!user || typeof user === "string") return false;

    const firstName = (user.first_name || "").toLowerCase();
    const lastName = (user.last_name || "").toLowerCase();
    const username = (user.username || "").toLowerCase();
    const email = (user.email || "").toLowerCase();

    const matches =
      firstName.includes(searchLower) ||
      lastName.includes(searchLower) ||
      username.includes(searchLower) ||
      email.includes(searchLower);

    return matches;
  });
};
