import { API_BASE_URL } from "../config/api";

const getAuthToken = (): string | null => {
  const accessToken = localStorage.getItem("accessToken");
  if (accessToken) return accessToken;
  return localStorage.getItem("authToken");
};

interface ApiResponse<T> {
  message: string;
  data: string;
  state: number;
  time: number;
  errorCode: number;
  resultType: number;
}

// Chat List Item
export interface ChatListItem {
  user_id: string;
  title: string;
  chatlist_workflowID: string;
  datetime1: string;
}

// Chat Message
export interface PublicChatMessage {
  question: string;
  answer: string;
  user_id: string;
  chat_list: string;
  datetime1: string;
}

// Load chat list (history)
export const loadChatList = async (): Promise<{
  success: boolean;
  data: ChatListItem[];
  message?: string;
}> => {
  console.log("loadChatList: Function called");
  const token = getAuthToken();
  console.log("loadChatList: Token:", token ? token.substring(0, 20) + "..." : "null");

  if (!token) {
    console.error("loadChatList: No token found");
    return { success: false, data: [], message: "توکن احراز هویت یافت نشد" };
  }

  try {
    console.log("loadChatList: Sending request to:", `${API_BASE_URL}/api/call`);
    const response = await fetch(`${API_BASE_URL}/api/call`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json;charset=UTF-8",
        Authorization: `Bearer ${token}`,
      },
      body: JSON.stringify({
        chat_list_load_function: {},
      }),
    });

    console.log("loadChatList: Response status:", response.status);
    const result: ApiResponse<string> = await response.json();
    console.log("loadChatList: Response data:", JSON.stringify(result));

    if (result.state === 0) {
      // Parse the nested JSON string
      console.log("loadChatList: Parsing result.data");
      const parsedData = JSON.parse(result.data);
      console.log("loadChatList: Parsed data:", parsedData);

      const chatList = JSON.parse(parsedData.chat_list);
      console.log("loadChatList: Chat list:", chatList);

      return {
        success: true,
        data: chatList,
      };
    } else {
      console.error("loadChatList: API returned error state:", result.state, result.message);
      return {
        success: false,
        data: [],
        message: result.message,
      };
    }
  } catch (error) {
    console.error("loadChatList: Exception caught:", error);
    return {
      success: false,
      data: [],
      message: "خطا در بارگذاری لیست چت‌ها",
    };
  }
};

// Load specific chat messages
export const loadChat = async (
  chatlistWorkflowID: string
): Promise<{
  success: boolean;
  data: PublicChatMessage[];
  message?: string;
}> => {
  const token = getAuthToken();

  if (!token) {
    return { success: false, data: [], message: "توکن احراز هویت یافت نشد" };
  }

  try {
    const response = await fetch(`${API_BASE_URL}/api/call`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json;charset=UTF-8",
        Authorization: `Bearer ${token}`,
      },
      body: JSON.stringify({
        chat_load_function: {
          chatlist_workflowID: chatlistWorkflowID,
        },
      }),
    });

    const result: ApiResponse<string> = await response.json();

    if (result.state === 0) {
      // Parse the nested JSON string
      const parsedData = JSON.parse(result.data);
      const chats = JSON.parse(parsedData.chats);

      return {
        success: true,
        data: chats,
      };
    } else {
      return {
        success: false,
        data: [],
        message: result.message,
      };
    }
  } catch (error) {
    console.error("Error loading chat:", error);
    return {
      success: false,
      data: [],
      message: "خطا در بارگذاری چت",
    };
  }
};

// Send message to public chat
export const sendPublicChatMessage = async (
  question: string,
  chatlistWorkflowID: string = ""
): Promise<{
  success: boolean;
  answer?: string;
  newChatlistWorkflowID?: string;
  message?: string;
}> => {
  const token = getAuthToken();

  if (!token) {
    return { success: false, message: "توکن احراز هویت یافت نشد" };
  }

  try {
    const response = await fetch(`${API_BASE_URL}/api/call`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json;charset=UTF-8",
        Authorization: `Bearer ${token}`,
      },
      body: JSON.stringify({
        public_caht_function: {
          chatlist_workflowID: chatlistWorkflowID,
          question: question,
        },
      }),
    });

    const result: ApiResponse<string> = await response.json();

    if (result.state === 0) {
      // Parse the nested JSON string
      const parsedData = JSON.parse(result.data);
      const messageData = JSON.parse(parsedData.message);

      return {
        success: true,
        answer: messageData.answer,
        newChatlistWorkflowID: messageData.chatlist_workflowID2,
      };
    } else {
      return {
        success: false,
        message: result.message,
      };
    }
  } catch (error) {
    console.error("Error sending public chat message:", error);
    return {
      success: false,
      message: "خطا در ارسال پیام",
    };
  }
};
