import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useGlobalContext } from "app/components/providers/global-context";
import { useToast } from "app/components/providers/use-toast";
import axios from "axios";
import { queryClient } from "./queryClient";
import { SubscriptionPlansResponse, UpdateAgentPayload } from "app/types";

const BASE_URL = "https://dev.qixs.ai:3003"
// const BASE_URL = "https://georgianne-unblindfolded-crashingly.ngrok-free.dev"
const api = axios.create({
  baseURL: BASE_URL,
});

api.interceptors.request.use(async (config) => {
  try {
    if (typeof window !== 'undefined' && window.shopify) {
      const shopifyToken = await window.shopify.idToken();
      if (shopifyToken) {
        config.headers.Authorization = `Bearer ${shopifyToken}`;
        config.headers["ngrok-skip-browser-warning"] = "true";
        return config;
      }
    }
  } catch (e) {
    console.warn("Interceptor: Error fetching App Bridge idToken", e);
  }

  const token = typeof window !== 'undefined' ? localStorage.getItem("qixs-token") : null;
  if (token) {
    // Standard JWT Bearer token format
    config.headers.Authorization = `Bearer ${token}`;
  }
  config.headers["ngrok-skip-browser-warning"] = "true";
  return config;
});



const requests = {
  get: (url: string, config?: any) => api.get(url, config).then((res) => res.data),

  getDirect: (url: string) => axios.get(url).then((res) => res.data),

  post: (url: string, body?: any) => api.post(url, body).then((res) => res.data),

  put: (url: string, body?: any) => api.put(url, body).then((res) => res.data),

  patch: (url: string, body?: any) => api.patch(url, body).then((res) => res.data),

  del: (url: string) => api.delete(url).then((res) => res.data),

  file: (url: string, key: string, file: any) => {
    const formData = new FormData();
    formData.append(key, file);

    return api
      .post(url, formData, {
        headers: { "Content-Type": "multipart/form-data" },
      })
      .then((res) => res.data);
  },
};

const Subscriptions = {
  getPlanList: (q?: string) => requests.get(`subscription/all/plan${q ? `?${q}` : ""}`),
  createPlan: (body: any) => requests.post("subscription/plan", body),
  updatePlan: (id: string, body: any) => requests.put(`subscription/plan/${id}`, body),
  getPlanDetails: (id: string, interval: "monthly" | "yearly") => requests.get(`subscription/plan/${id}/workspace?interval=${interval}`),
  getActiveSubscription: (workspaceId: string) => requests.get(`subscription/${workspaceId}/active`),
  getAllPlans: () => requests.get("subscription/all/plan"),
  purchaseSubscription: (body: any) => requests.post("subscription/purchase", body),
  confirmBilling: () => requests.get("subscription/billing/confirm"),
  updatePayment: (subscriptionId: string) => requests.patch(`subscription/${subscriptionId}/payment`),
};
const allApis = {
  Subscriptions,
  api
}

export default allApis;

//authorize vendor api
interface IAuthorizeVendorPayload {
  locale?: string;
  clientVersion?: string;
}

export function useAuthorizeVendor(payload?: IAuthorizeVendorPayload) {
  const { setUser } = useGlobalContext();

  return useQuery({
    queryKey: ["authorize-user", payload],
    queryFn: async () => {
      // The Authorization: Bearer <session_token> is added automatically by the axios interceptor
      const response = await api.post(`/vendor/shopify/login`, {
        locale: payload?.locale || (typeof window !== 'undefined' ? navigator.language : "en-US"),
        clientVersion: payload?.clientVersion || "1.0.0",
      });

      const body = response.data;

      // Navigate the nested response structure: body.data.access_token
      const token = body.data?.access_token || body.accessToken || body.data?.data?.access_token;
      if (token) {
        localStorage.setItem("qixs-token", token);
      }
      const userData = body.data || body;
      setUser(userData);
      return userData;
    },
  });
}

interface CreateAgentMutation {
  name: string | undefined;
}

export function useCreateAgent() {
  return useMutation({
    mutationFn: async (payload: CreateAgentMutation) => {
      const body = {
        name: payload.name || "default",
        type: "Agent",
        voice: "aura-zeus-en",
        image: "",
        chat_first_message: "TestAgentWithStoreAndRAG",
        chat_prompt: "TestAgentWithStoreAndRAG",
        call_first_message: "TestAgentWithStoreAndRAG",
        call_prompt: "TestAgentWithStoreAndRAG",
        ai_model: "gemini",
        idle_reminder: false,
        call_cut_ability: false,
        call_limit_duration: 30,
        call_transfer: false,
        send_message: false,
        real_time_booking: false,
      };

      await api.post("/agent", body);
      return null;
    },
  });
}

export async function useInstallUrl() {
  return useQuery({
    queryKey: ["install-url"],
    queryFn: async () => {
      const { data } = await api.get("/shopify/install-url", {
        params: {
          shop: "dashboard-store-2.myshopify.com",
          userId: "68a450185f89c7296aaa1e47",
          agentId: "69087de529deeeed2841fcef",
          storeName: "dashboard-store-2",
        },
      });
    },
  });
}

//Dashboard APIs
export function useGetDashboardStats(params: { type: string }) {
  const { type } = params;

  return useQuery({
    queryKey: ["get-dashboard-stats", params],
    queryFn: async () => {
      const { data } = await api.get("/vendor/dashboard", {
        params: {
          type,
        },
      });
      return data; // Added missing return statement
    },
  });
}

interface ShopifyStore {
  accessToken: string;
  domain: string;
  storeId: string;
}

export function useSyncStore() {
  const { showSuccess, showError } = useToast();
  return useMutation({
    mutationFn: async (body: ShopifyStore) => {
      await api.post("/shopify/sync-products", body);
    },
    onError: () => {
      showError("Store sync failed!");
    },
    onSuccess: () => {
      showSuccess("Store synced successfully!");
    },
  });
}

export interface FAQPoint {
  pointId: string;
  question: string;
  answer: string;
}

export interface FAQResponse {
  point: FAQPoint[];
}

export function useGetFAQ(agentId: string) {
  return useQuery<FAQResponse>({
    queryKey: ["get-faq"],
    queryFn: async () => {
      const { data } = await api.get("/knowledge-base/retrieveFAQs", {
        params: {
          agentId,
        },
      });
      return data as FAQResponse;
    },
    enabled: !!agentId,
  });
}

interface AddFAQPayload {
  question: string;
  answer: string;
  agentId: string;
}

export function useAddFAQ() {
  const { showSuccess, showError } = useToast();
  return useMutation({
    mutationFn: async (body: AddFAQPayload) => {
      await api.post("/knowledge-base/AddFAQ", body);
    },
    onError: () => {
      showError("Failed to add FAQ!");
    },
    onSuccess: () => {
      showSuccess("FAQ added successfully!");
    },
  });
}

export function useDeleteFAQ() {
  const { showSuccess, showError } = useToast();
  return useMutation({
    mutationFn: async (pontId: string) => {
      await api.delete(`/knowledge-base/delete_faq/${pontId}`);
    },
    onError: () => {
      showError("Failed to delete FAQ!");
    },
    onSuccess: () => {
      showSuccess("FAQ deleted successfully!");
    },
  });
}

// Knowledge base apis
export function useGetKB() {
  return useQuery({
    queryKey: ["knowledge-bases"],
    queryFn: async () => {
      const res = await api.get("knowledge-base");
      return res.data as { count: number; data: Array<any> };
    },
  });
}

export function useGetKBDocuments(kbId: string | null) {
  return useQuery({
    queryKey: ["kb-docs", kbId],
    queryFn: async () => {
      if (!kbId) return { count: 0, data: [] };
      const res = await api.get(`/knowledge-base/${kbId}/documents`, {
        params: { pagination: 0, limit: 10 },
      });
      return res.data as { count: number; data: Array<any> };
    },
    enabled: !!kbId,
  });
}

// Upload PDF (or file) to a knowledge base using multipart/form-data
interface UploadPayload {
  knowledge_base_id: string;
  file: File;
}

export function useUploadKBPdf() {
  const { showSuccess, showError } = useToast();
  return useMutation({
    mutationFn: async (payload: UploadPayload) => {
      const fd = new FormData();
      fd.append("knowledge_base_id", payload.knowledge_base_id);
      fd.append("file", payload.file);
      const res = await api.post("/knowledge-base/pdf-upload", fd, {
        headers: {
          "Content-Type": "multipart/form-data",
        },
      });
      return res.data;
    },
    onSuccess: (_data, payload) => {
      showSuccess("File uploaded successfully");
      // invalidate the documents for this KB if provided, otherwise refresh all kb-docs
      if (payload && (payload as any).knowledge_base_id) {
        (queryClient as any).invalidateQueries(["kb-docs", (payload as any).knowledge_base_id]);
      } else {
        (queryClient as any).invalidateQueries(["kb-docs"]);
      }
    },
    onError: () => {
      showError("Failed to upload file");
    },
  });
}

// Delete a document by id
interface DeleteDocumentPayload {
  id: string;
  kbId?: string;
}

export function useDeleteDocument() {
  const { showSuccess, showError } = useToast();
  return useMutation({
    mutationFn: async (payload: DeleteDocumentPayload) => {
      await api.delete(`/knowledge-base/documents/${payload.id}`);
      return payload;
    },
    onSuccess: (_data, payload) => {
      showSuccess("Document deleted");
      if (payload && payload.kbId) {
        (queryClient as any).invalidateQueries(["kb-docs", payload.kbId]);
      } else {
        (queryClient as any).invalidateQueries(["kb-docs"]);
      }
    },
    onError: () => {
      showError("Failed to delete document");
    },
  });
}

// Upload URL to knowledge base
interface UploadUrlPayload {
  url: string;
  knowledge_base_id: string;
  depth?: number;
}

export function useUploadKBUrl() {
  const { showSuccess, showError } = useToast();
  return useMutation({
    mutationFn: async (payload: UploadUrlPayload) => {
      const res = await api.post(`/knowledge-base/url-upload`, {
        url: payload.url,
        title: payload.url,
        knowledge_base_id: payload.knowledge_base_id,
        depth: payload.depth || 1,
      });
      return res.data;
    },
    onSuccess: (_data, payload) => {
      showSuccess("URL added successfully");
      // Invalidate the documents list for this knowledge base
      (queryClient as any).invalidateQueries(["kb-docs", payload.knowledge_base_id]);
    },
    onError: () => {
      showError("Failed to add URL");
    },
  });
}

// Create a new knowledge base
interface CreateKBPayload {
  name: string;
}

export function useCreateKB() {
  const { showSuccess, showError } = useToast();
  return useMutation({
    mutationFn: async (payload: CreateKBPayload) => {
      const res = await api.post(`/knowledge-base`, { name: payload.name });
      return res.data;
    },
    onSuccess: (data) => {
      showSuccess("Knowledge base created");
      // invalidate the KB list so UI refreshes
      (queryClient as any).invalidateQueries(["knowledge-bases"]);
    },
    onError: () => {
      showError("Failed to create knowledge base");
    },
  });
}

export function useAgentDetails(agentId: string) {
  const { setAgent } = useGlobalContext();
  return useQuery({
    queryKey: ["agent-details", agentId],
    queryFn: async () => {
      const { data } = await api.get(`/agent/${agentId}`);
      if (data?.data) {
        setAgent(data?.data);
      }
      return null
    },
    enabled: !!agentId && agentId !== "undefined" && typeof agentId === "string",
  });
}

export function useUpdateAgentDetails() {
  const { showError, showSuccess } = useToast();
  return useMutation({
    mutationFn: async ({ payload, _id }: { _id: string; payload: UpdateAgentPayload }) => {
      await api.put(`/agent/${_id}`, payload);
    },
    onSuccess: (data, data1) => {
      showSuccess("Agent updated successfully!");
      (queryClient as any).invalidateQueries(["agent-details", data1?._id]);
    },
    onError: () => {
      showError("Failed to update agent!");
    },
  });
}

// Chatbot Settings APIs
export function useGetChatbotSettings(section: string = 'all') {
  return useQuery({
    queryKey: ["chatbot-settings", section],
    queryFn: async () => {
      const { data } = await api.get(`/chatbots`, {
        params: { section },
      });
      return data;
    },
  });
}

export function useUpdateChatbotSettings() {
  const { showSuccess, showError } = useToast();
  return useMutation({
    mutationFn: async (payload: any) => {
      const { data } = await api.post(`/chatbots`, payload);
      return data;
    },
    onSuccess: () => {
      showSuccess("Settings saved successfully!");
      (queryClient as any).invalidateQueries(["chatbot-settings"]);
    },
    onError: () => {
      showError("Failed to save settings!");
    },
  });
}

export function useUpdateChatbotSection() {
  const { showSuccess, showError } = useToast();
  return useMutation({
    mutationFn: async ({ section, payload }: { section: string; payload: any }) => {
      const { data } = await api.patch(`/chatbots/${section}`, payload);
      return data;
    },
    onSuccess: (data, { section }) => {
      showSuccess(`${section.charAt(0).toUpperCase() + section.slice(1)} settings updated!`);
      (queryClient as any).invalidateQueries(["chatbot-settings", section]);
    },
    onError: () => {
      showError("Failed to update settings!");
    },
  });
}

// Training Data APIs
export function useGetProducts(params: { page: number; limit: number }) {
  return useQuery({
    queryKey: ["training-products", params],
    queryFn: async () => {
      const { data } = await api.get("/traningdata/products", { params });
      return data;
    },
  });
}

export function useGetProductDetail(productId: string) {
  return useQuery({
    queryKey: ["product-detail", productId],
    queryFn: async () => {
      const { data } = await api.get(`/traningdata/products/${productId}`);
      return data;
    },
    enabled: !!productId,
  });
}

export function useGetDiscounts(params: { page: number; limit: number }) {
  return useQuery({
    queryKey: ["training-discounts", params],
    queryFn: async () => {
      const { data } = await api.get("/traningdata/discounts", { params });
      return data;
    },
  });
}

// Custom Knowledge APIs
export function useUploadPDF() {
  const { showSuccess, showError } = useToast();
  return useMutation({
    mutationFn: async (file: File) => {
      const fd = new FormData();
      fd.append("file", file);
      const { data } = await api.post("/traningdata/pdf-upload", fd, {
        headers: { "Content-Type": "multipart/form-data" },
      });
      return data;
    },
    onSuccess: () => {
      showSuccess("PDF uploaded successfully!");
      (queryClient as any).invalidateQueries(["custom-knowledge"]);
    },
    onError: () => showError("Failed to upload PDF"),
  });
}

export function useUploadURL() {
  const { showSuccess, showError } = useToast();
  return useMutation({
    mutationFn: async (payload: { url: string; title: string; depth: number }) => {
      const { data } = await api.post("/traningdata/url-upload", payload);
      return data;
    },
    onSuccess: () => {
      showSuccess("URL learned successfully!");
      (queryClient as any).invalidateQueries(["custom-knowledge"]);
    },
    onError: () => showError("Failed to learn URL"),
  });
}

export function useUploadText() {
  const { showSuccess, showError } = useToast();
  return useMutation({
    mutationFn: async (payload: { text: string; title: string }) => {
      const { data } = await api.post("/traningdata/text-upload", payload);
      return data;
    },
    onSuccess: () => {
      showSuccess("Q&A added successfully!");
      (queryClient as any).invalidateQueries(["custom-knowledge"]);
    },
    onError: () => showError("Failed to add Q&A"),
  });
}

export function useGetCustomKnowledge(type: string = 'all') {
  return useQuery({
    queryKey: ["custom-knowledge", type],
    queryFn: async () => {
      const endpoint = `/traningdata/${type === 'all' ? 'all' : type === 'Questions' ? 'files' : type === 'URLs' ? 'urls' : 'files'}`;
      const { data } = await api.get(endpoint);
      return data;
    },
  });
}

export function useDeleteCustomKnowledge() {
  const { showSuccess, showError } = useToast();
  return useMutation({
    mutationFn: async (ids: string[]) => {
      // Assuming a bulk delete endpoint or single delete loop
      // For now, mapping to a single delete or as specified by backend
      const { data } = await api.delete("/traningdata/delete", { data: { ids } });
      return data;
    },
    onSuccess: () => {
      showSuccess("Items deleted successfully!");
      (queryClient as any).invalidateQueries(["custom-knowledge"]);
    },
    onError: () => showError("Failed to delete items"),
  });
}

export function useUpdateKnowledgeStatus() {
  const { showSuccess, showError } = useToast();
  return useMutation({
    mutationFn: async ({ ids, status }: { ids: string[]; status: string }) => {
      const { data } = await api.patch("/traningdata/status", { ids, status });
      return data;
    },
    onSuccess: () => {
      showSuccess("Status updated successfully!");
      (queryClient as any).invalidateQueries(["custom-knowledge"]);
    },
    onError: () => showError("Failed to update status"),
  });
}





// trainingdata hooks -----------------------------------------------------------------
export const useGetTrainingAll = () => {
  return useQuery({
    queryKey: ['training-data-all'],
    queryFn: async () => {
      const response = await api.get('/traningdata/all');
      return response.data;
    }
  });
};

export const useGetTrainingURLs = () => {
  return useQuery({
    queryKey: ['training-data-urls'],
    queryFn: async () => {
      const response = await api.get('/traningdata/urls');
      return response.data;
    }
  });
};

export const useGetTrainingFiles = () => {
  return useQuery({
    queryKey: ['training-data-files'],
    queryFn: async () => {
      const response = await api.get('/traningdata/files');
      return response.data;
    }
  });
};

// trainingdata/faqs -------------------------------------------------------------
export const useGetFAQs = () => {
  return useQuery({
    queryKey: ['custom-knowledge-faqs'],
    queryFn: async () => {
      const response = await api.get('/traningdata/faqs');
      return response.data;
    }
  });
};

export const useUploadFAQ = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: async (data: { question: string; answer: string; topic: string; status: string }) => {
      const response = await api.post('/traningdata/faqs', data);
      return response.data;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['custom-knowledge-faqs'] });
      queryClient.invalidateQueries({ queryKey: ['custom-knowledge-all'] });
    }
  });
};



export const useDeleteTrainingFAQ = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: async (id: string) => {
      const response = await api.delete(`/traningdata/faqs/${id}`);
      return response.data;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['custom-knowledge-faqs'] });
      queryClient.invalidateQueries({ queryKey: ['custom-knowledge-all'] });
    }
  });
};


















































// import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
// import { useGlobalContext } from "app/components/providers/global-context";
// import { useToast } from "app/components/providers/use-toast";
// import axios from "axios";
// import { queryClient } from "./queryClient";
// import { UpdateAgentPayload } from "app/types";

// const BASE_URL = "https://dev.qixs.ai:3003";
// // const BUCKET_ROOT = process.env.NEXT_PUBLIC_BUCKET_ROOT;

// const encode = encodeURIComponent;

// /* -------------------- AXIOS INSTANCE -------------------- */

// const api = axios.create({
//   baseURL: BASE_URL,
// });

// api.interceptors.request.use((config) => {
//   const token = localStorage.getItem("qixs-token");

//   if (token) {
//     config.headers.Authorization = `Bearer ${token}`;
//   }

//   config.headers["ngrok-skip-browser-warning"] = "true";

//   return config;
// });

// /* -------------------- REQUEST HELPERS -------------------- */

// const requests = {
//   get: (url: string, config?: any) => api.get(url, config).then((res) => res.data),

//   getDirect: (url: string) => axios.get(url).then((res) => res.data),

//   post: (url: string, body: any) => api.post(url, body).then((res) => res.data),

//   put: (url: string, body: any) => api.put(url, body).then((res) => res.data),

//   patch: (url: string, body: any) => api.patch(url, body).then((res) => res.data),

//   del: (url: string) => api.delete(url).then((res) => res.data),

//   file: (url: string, key: string, file: any) => {
//     const formData = new FormData();
//     formData.append(key, file);

//     return api
//       .post(url, formData, {
//         headers: { "Content-Type": "multipart/form-data" },
//       })
//       .then((res) => res.data);
//   },
// };

// /* -------------------- AUTH -------------------- */

// const Auth = {
//   getProfile: () => requests.get(`v1/auth/profile`),
// };

// /* -------------------- FILE HELPERS -------------------- */

// // const FILES = {
// //   audio: (filename: string) =>
// //     filename?.startsWith("http")
// //       ? filename
// //       : `${BUCKET_ROOT}audio/${encode(filename)}`,

// //   video: (filename: string) =>
// //     filename?.startsWith("http")
// //       ? filename
// //       : `${BUCKET_ROOT}video/${encode(filename)}`,

// //   document: (filename: string) =>
// //     filename?.startsWith("http")
// //       ? filename
// //       : `${BUCKET_ROOT}documents/${encode(filename)}`,

// //   imageOriginal: (filename: string, placeholder: any) =>
// //     filename
// //       ? filename.startsWith("http")
// //         ? filename
// //         : `${BUCKET_ROOT}${encode(filename)}`
// //       : placeholder,

// //   imageMedium: (filename: string, placeholder?: any) =>
// //     filename
// //       ? filename.startsWith("http")
// //         ? filename
// //         : `${BUCKET_ROOT}image/medium/${encode(filename)}`
// //       : placeholder,

// //   imageSmall: (filename?: string, placeholder?: any) =>
// //     filename
// //       ? filename.startsWith("http")
// //         ? filename
// //         : `${BUCKET_ROOT}${encode(filename)}`
// //       : placeholder,
// // };

// /* -------------------- TOOL APIs -------------------- */

// const Tool = {
//   addTool: (info: any) => requests.post(`v1/listing-tool`, info),

//   getInventory: (q: any) => requests.get(`v1/inventory${q ? `?${q}` : ""}`),

//   getAllListingsTool: (q: any) =>
//     requests.get(`v1/listing-tool${q ? `?${q}` : ""}`),

//   MyListings: (q: any) =>
//     requests.get(`v1/listing-tool/my${q ? `?${q}` : ""}`),

//   getToolById: (id: string) => requests.get(`v1/listing-tool/${id}`),

//   deleteToolById: (id: string) => requests.del(`v1/listing-tool/${id}`),

//   updateToolById: (id: string, info: any) =>
//     requests.put(`v1/listing-tool/${id}`, info),
// };

// /* -------------------- COMMON -------------------- */

// const Common = {
//   uploadFile: (key: string, file: any) =>
//     requests.file(`v1/uploads/profile`, key, file),

//   uploadFileMultiple: (key: string, file: any) =>
//     requests.file(`v1/uploads/tools`, key, file),

//   headerData: () => requests.get(`v1/cart/cartCount`),
// };

// /* -------------------- EXPORT API -------------------- */

// const Api = {
//   Auth,
//   Tool,
//   Common,
//   // FILES,
//   encode,
// };

// export default Api;

// interface IAuthorizeVendorPayload {
//   store: string;
//   accessToken: string;
// }

// export function useAuthorizeVendor({
//   store,
//   accessToken,
// }: IAuthorizeVendorPayload) {
//   const { setUser } = useGlobalContext();

//   return useQuery({
//     queryKey: ["authorize-user"],
//     queryFn: async () => {
//       const res = await axios.post(`${BASE_URL}/vendor/shopify/login`, {
//         storeDomain: store,
//         accessToken,
//       });

//       const data = res.data.data;

//       localStorage.setItem("qixs-token", data.access_token);

//       setUser(data);

//       return data;
//     },
//   });
// }

// /* -------------------- CREATE AGENT -------------------- */

// interface CreateAgentMutation {
//   name?: string;
// }

// export function useCreateAgent() {
//   return useMutation({
//     mutationFn: async (payload: CreateAgentMutation) => {
//       const body = {
//         name: payload.name || "default",
//         type: "Agent",
//         voice: "aura-zeus-en",
//         image: "",
//         chat_first_message: "TestAgentWithStoreAndRAG",
//         chat_prompt: "TestAgentWithStoreAndRAG",
//         call_first_message: "TestAgentWithStoreAndRAG",
//         call_prompt: "TestAgentWithStoreAndRAG",
//         ai_model: "gemini",
//         idle_reminder: false,
//         call_cut_ability: false,
//         call_limit_duration: 30,
//         call_transfer: false,
//         send_message: false,
//         real_time_booking: false,
//       };

//       await api.post("/agent", body);
//     },
//   });
// }

// /* -------------------- DASHBOARD -------------------- */

// export function useGetDashboardStats(params: { type: string }) {
//   const { type } = params;

//   return useQuery({
//     queryKey: ["dashboard-stats", type],
//     queryFn: async () => {
//       const data = await requests.get("/vendor/dashboard", {
//         params: { type },
//       });

//       return data;
//     },
//   });
// }

// /* -------------------- SYNC STORE -------------------- */

// interface ShopifyStore {
//   accessToken: string;
//   domain: string;
//   storeId: string;
// }

// export function useSyncStore() {
//   const { showSuccess, showError } = useToast();

//   return useMutation({
//     mutationFn: async (body: ShopifyStore) => {
//       await api.post("/shopify/sync-products", body);
//     },

//     onSuccess: () => {
//       showSuccess("Store synced successfully!");
//     },

//     onError: () => {
//       showError("Store sync failed!");
//     },
//   });
// }

// /* -------------------- FAQ -------------------- */

// export interface FAQPoint {
//   pointId: string;
//   question: string;
//   answer: string;
// }

// export interface FAQResponse {
//   point: FAQPoint[];
// }

// export function useGetFAQ(agentId: string) {
//   return useQuery<FAQResponse>({
//     queryKey: ["faq", agentId],

//     queryFn: async () => {
//       const data = await requests.get("/knowledge-base/retrieveFAQs", {
//         params: { agentId },
//       });

//       return data;
//     },

//     enabled: !!agentId,
//   });
// }

// interface AddFAQPayload {
//   question: string;
//   answer: string;
//   agentId: string;
// }

// export function useAddFAQ() {
//   const { showSuccess, showError } = useToast();

//   return useMutation({
//     mutationFn: async (body: AddFAQPayload) => {
//       await api.post("/knowledge-base/AddFAQ", body);
//     },

//     onSuccess: () => {
//       showSuccess("FAQ added successfully!");
//       queryClient.invalidateQueries({ queryKey: ["faq"] });
//     },

//     onError: () => {
//       showError("Failed to add FAQ!");
//     },
//   });
// }

// export function useDeleteFAQ() {
//   const { showSuccess, showError } = useToast();

//   return useMutation({
//     mutationFn: async (pointId: string) => {
//       await api.delete(`/knowledge-base/delete_faq/${pointId}`);
//     },

//     onSuccess: () => {
//       showSuccess("FAQ deleted successfully!");
//       queryClient.invalidateQueries({ queryKey: ["faq"] });
//     },

//     onError: () => {
//       showError("Failed to delete FAQ!");
//     },
//   });
// }

// /* -------------------- KNOWLEDGE BASE -------------------- */

// export function useGetKB() {
//   return useQuery({
//     queryKey: ["knowledge-bases"],

//     queryFn: async () => {
//       const data = await requests.get("knowledge-base");

//       return data as { count: number; data: Array<any> };
//     },
//   });
// }

// export function useGetKBDocuments(kbId: string | null) {
//   return useQuery({
//     queryKey: ["kb-docs", kbId],

//     queryFn: async () => {
//       if (!kbId) return { count: 0, data: [] };

//       const data = await requests.get(`/knowledge-base/${kbId}/documents`, {
//         params: { pagination: 0, limit: 10 },
//       });

//       return data;
//     },

//     enabled: !!kbId,
//   });
// }

// /* -------------------- UPLOAD PDF -------------------- */

// interface UploadPayload {
//   knowledge_base_id: string;
//   file: File;
// }

// export function useUploadKBPdf() {
//   const { showSuccess, showError } = useToast();

//   return useMutation({
//     mutationFn: async (payload: UploadPayload) => {
//       const fd = new FormData();
//       fd.append("knowledge_base_id", payload.knowledge_base_id);
//       fd.append("file", payload.file);

//       const res = await api.post("/knowledge-base/pdf-upload", fd);

//       return res.data;
//     },

//     onSuccess: (_data, payload) => {
//       showSuccess("File uploaded successfully");

//       queryClient.invalidateQueries({
//         queryKey: ["kb-docs", payload.knowledge_base_id],
//       });
//     },

//     onError: () => {
//       showError("Failed to upload file");
//     },
//   });
// }

// /* -------------------- DELETE DOCUMENT -------------------- */

// interface DeleteDocumentPayload {
//   id: string;
//   kbId?: string;
// }

// export function useDeleteDocument() {
//   const { showSuccess, showError } = useToast();

//   return useMutation({
//     mutationFn: async (payload: DeleteDocumentPayload) => {
//       await api.delete(`/knowledge-base/documents/${payload.id}`);
//       return payload;
//     },

//     onSuccess: (_data, payload) => {
//       showSuccess("Document deleted");

//       queryClient.invalidateQueries({
//         queryKey: ["kb-docs", payload.kbId],
//       });
//     },

//     onError: () => {
//       showError("Failed to delete document");
//     },
//   });
// }

// /* -------------------- AGENT DETAILS -------------------- */

// export function useAgentDetails(agentId: string) {
//   const { setAgent } = useGlobalContext();

//   return useQuery({
//     queryKey: ["agent-details", agentId],

//     queryFn: async () => {
//       const res = await api.get(`/agent/${agentId}`);

//       if (res.data?.data) {
//         setAgent(res.data.data);
//       }

//       return res.data;
//     },

//     enabled: !!agentId,
//   });
// }

// /* -------------------- UPDATE AGENT -------------------- */

// export function useUpdateAgentDetails() {
//   const { showError, showSuccess } = useToast();

//   return useMutation({
//     mutationFn: async ({
//       payload,
//       _id,
//     }: {
//       _id: string;
//       payload: UpdateAgentPayload;
//     }) => {
//       await api.put(`/agent/${_id}`, payload);
//     },

//     onSuccess: (_data, variables) => {
//       showSuccess("Agent updated successfully!");

//       queryClient.invalidateQueries({
//         queryKey: ["agent-details", variables._id],
//       });
//     },

//     onError: () => {
//       showError("Failed to update agent!");
//     },
//   });
// }










// }

/* -------------------- ASSISTANT MANAGEMENT -------------------- */
export const useGetAssistant = () => {
  return useQuery({
    queryKey: ['assistant-data'],
    queryFn: async () => {
      const response = await api.get('/assistants');
      return response.data;
    }
  });
};

export const useCreateAssistant = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: async (data: any) => {
      const response = await api.post('/assistants', data);
      return response.data;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['assistant-data'] });
    }
  });
};

export const useUpdateAssistant = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: async (data: any) => {
      const response = await api.patch('/assistants', data);
      return response.data;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['assistant-data'] });
    }
  });
};

export const useUpdateGeneralInstructions = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: async (data: any) => {
      const response = await api.patch('/assistants/general-instructions', data);
      return response.data;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['assistant-data'] });
    }
  });
};

export const useUpdateShoppingSkills = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: async (data: any) => {
      const response = await api.patch('/assistants/shopping-skills', data);
      return response.data;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['assistant-data'] });
    }
  });
};

export const useUpdateCustomerSupportSkills = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: async (data: any) => {
      const response = await api.patch('/assistants/customer-support-skills', data);
      return response.data;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['assistant-data'] });
    }
  });
}; export const useSyncProducts = () => {
  const { showSuccess, showError } = useToast();
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: async () => {
      const response = await api.post('/shopify/sync-products', {});
      return response.data;
    },
    onSuccess: () => {
      showSuccess("Product synchronization started.");
      queryClient.invalidateQueries({ queryKey: ['products'] });
    },
    onError: () => {
      showError("Failed to sync products.");
    }
  });
};

export const useSyncDiscounts = () => {
  const { showSuccess, showError } = useToast();
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: async () => {
      const response = await api.post('/shopify/sync-discounts', {});
      return response.data;
    },
    onSuccess: () => {
      showSuccess("Discount synchronization started.");
      queryClient.invalidateQueries({ queryKey: ['discounts'] });
    },
    onError: () => {
      showError("Failed to sync discounts.");
    }
  });
};

export const useGetFAQSystem = () => {
  return useQuery({
    queryKey: ['faq-system'],
    queryFn: async () => {
      const response = await api.get('/faq-system');
      return response.data;
    }
  });
};

export const useUpdateFAQSystem = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: async (data: any) => {
      const response = await api.patch('/faq-system/content', data);
      return response.data;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['faq-system'] });
    }
  });
};

export const useUpdateFAQPageSettings = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: async (data: any) => {
      const response = await api.patch('/faq-system/page-settings', data);
      return response.data;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['faq-system'] });
    }
  });
};

export const useUpdateFAQBlocks = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: async (data: any) => {
      const response = await api.patch('/faq-system/blocks', data);
      return response.data;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['faq-system'] });
    }
  });
};

export const useCreateFAQBlock = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: async (data: any) => {
      const response = await api.post('/faq-system/blocks', data);
      return response.data;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['faq-system'] });
    }
  });
};

export const useDeleteFAQBlock = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: async (blockId: string) => {
      const response = await api.delete(`/faq-system/blocks/${blockId}`);
      return response.data;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['faq-system'] });
    }
  });
};

export const useGetProactiveChats = () => {
  return useQuery({
    queryKey: ['proactive-chats'],
    queryFn: async () => {
      const response = await api.get('/proactive-chat');
      return response.data;
    }
  });
};

export const useGetProactiveChatAnalytics = () => {
  return useQuery({
    queryKey: ['proactive-chat-analytics'],
    queryFn: async () => {
      const response = await api.get('/proactive-chat/chat/analytics');
      return response.data;
    }
  });
};

export const useCreateProactiveChat = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: async (data: any) => {
      const response = await api.post('/proactive-chat', data);
      return response.data;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['proactive-chats'] });
    }
  });
};

export const useUpdateProactiveChat = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: async (data: any) => {
      const response = await api.patch('/proactive-chat', data);
      return response.data;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['proactive-chats'] });
    }
  });
};

export const useUpdateProactiveChatStatus = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: async ({ _id, ...statusData }: any) => {
      const response = await api.patch(`/proactive-chat/status/${_id}`, statusData);
      return response.data;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['proactive-chats'] });
    }
  });
};

export const useDeleteProactiveChat = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: async (_id: string) => {
      const response = await api.delete(`/proactive-chat/${_id}`);
      return response.data;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['proactive-chats'] });
    }
  });
};

// General Settings Hooks
export const useGetGeneralSettings = () => {
  return useQuery({
    queryKey: ['settings'],
    queryFn: async () => {
      const response = await api.get('/settings');
      return {
        ...response.data,
        data: response.data.data?.general
      };
    }
  });
};

export const useUpdateGeneralSettings = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: async (data: any) => {
      const response = await api.patch('/settings/general', data);
      return response.data;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['settings-general'] });
    }
  });
};

// Chat Availability Settings Hooks
export const useGetChatAvailability = () => {
  return useQuery({
    queryKey: ['settings-chat-availability'],
    queryFn: async () => {
      const response = await api.get('/settings/chat-availability');
      return response.data;
    }
  });
};

export const useUpdateChatAvailability = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: async (data: any) => {
      const response = await api.patch('/settings/chat-availability', data);
      return response.data;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['settings-chat-availability'] });
    }
  });
};

// Reports Settings Hooks
export const useGetReportsSettings = () => {
  return useQuery({
    queryKey: ['settings-reports'],
    queryFn: async () => {
      const response = await api.get('/settings/reports');
      return response.data;
    }
  });
};

export const useUpdateReportsSettings = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: async (data: any) => {
      const response = await api.patch('/settings/reports', data);
      return response.data;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['settings-reports'] });
    }
  });
};

// Inbox Settings Hooks
export const useGetInboxSettings = () => {
  return useQuery({
    queryKey: ['settings-inbox'],
    queryFn: async () => {
      const response = await api.get('/settings/inbox');
      return response.data;
    }
  });
};

export const useUpdateInboxSettings = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: async (data: any) => {
      const response = await api.patch('/settings/inbox', data);
      return response.data;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['settings-inbox'] });
    }
  });
};

// Automation Settings Hooks
export const useGetAutomationSettings = () => {
  return useQuery({
    queryKey: ['settings-automation'],
    queryFn: async () => {
      const response = await api.get('/settings/automation');
      return response.data;
    }
  });
};

export const useUpdateAutomationSettings = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: async (data: any) => {
      const response = await api.patch('/settings/automation', data);
      return response.data;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['settings-automation'] });
    }
  });
};

// Notification Settings Hooks
export const useGetNotificationSettings = () => {
  return useQuery({
    queryKey: ['settings-notifications'],
    queryFn: async () => {
      const response = await api.get('/settings/notifications');
      return response.data;
    }
  });
};

export const useUpdateNotificationSettings = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: async (data: any) => {
      const response = await api.patch('/settings/notifications', data);
      return response.data;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['settings-notifications'] });
    }
  });
};

/* -------------------- INBOX CONVERSATIONS & MESSAGES -------------------- */

export const useGetConversations = (params?: any) => {
  return useQuery({
    queryKey: ['inbox-conversations', params],
    queryFn: async () => {
      const response = await api.get('/inbox/conversations', { params });
      return response.data;
    }
  });
};

export const useGetConversationDetail = (id: string | null) => {
  return useQuery({
    queryKey: ['inbox-conversation-detail', id],
    queryFn: async () => {
      if (!id) return null;
      const response = await api.get(`/inbox/conversations/${id}`);
      return response.data;
    },
    enabled: !!id
  });
};

export const useUpdateConversation = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: async ({ id, data }: { id: string; data: any }) => {
      const response = await api.patch(`/inbox/conversations/${id}`, data);
      return response.data;
    },
    onSuccess: (_, { id }) => {
      queryClient.invalidateQueries({ queryKey: ['inbox-conversations'] });
      queryClient.invalidateQueries({ queryKey: ['inbox-conversation-detail', id] });
    }
  });
};

export interface SendMessagePayload {
  conversationId: string;
  sender_type: string;
  sender_id: string;
  content: string;
  status: string;
  is_internal_note: boolean;
  products?: any[];
  discounts?: any[];
  files?: File[];
}


export const useSendMessage = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: async (data: SendMessagePayload) => {
      if (data.files && data.files.length > 0) {
        const formData = new FormData();
        formData.append("conversationId", data.conversationId);
        formData.append("sender_type", data.sender_type);
        formData.append("sender_id", data.sender_id);
        formData.append("content", data.content);
        formData.append("status", data.status);
        formData.append("is_internal_note", String(data.is_internal_note));

        if (data.products) formData.append("products", JSON.stringify(data.products));
        if (data.discounts) formData.append("discounts", JSON.stringify(data.discounts));

        data.files.forEach((file) => {
          formData.append("files", file);
        });

        const response = await api.post('/inbox/messages', formData, {
          headers: { "Content-Type": "multipart/form-data" }
        });
        return response.data;
      } else {
        const payload = { ...data };
        delete payload.files;
        const response = await api.post('/inbox/messages', payload);
        return response.data;
      }
    },

    onSuccess: (_, { conversationId }) => {
      queryClient.invalidateQueries({ queryKey: ['inbox-conversation-messages', conversationId] });
      queryClient.invalidateQueries({ queryKey: ['inbox-conversations'] });
    }
  });
};


export const useGetConversationMessages = (id: string | null) => {
  return useQuery({
    queryKey: ['inbox-conversation-messages', id],
    queryFn: async () => {
      if (!id) return [];
      const response = await api.get(`/inbox/conversations/${id}/messages`);
      return response.data;
    },
    enabled: !!id,
    refetchInterval: 5000 // Poll for new messages every 5 seconds
  });
};

