import axios from "axios";
import { apiUrl } from "@/env";
import type { IUserProfile, IUserProfileUpdate, IUserProfileCreate, Video, VideoCreate, ArticleCreate, ImageDownload, VideoUploaded, YTViewsUserData, PaymentData, VideoContent } from "@/interfaces";
import type { StringOptionsWithImporter } from "sass";

function authHeaders(token: string) {
  return {
    headers: {
      Authorization: `Bearer ${token}`,
    },
  };
}

export const api = {
  async logInGetToken(username: string, password: string) {
    const params = new URLSearchParams();
    params.append("username", username);
    params.append("password", password);
    return axios.post(`${apiUrl}/api/v1/login/access-token`, params);
  },
  async qrLogInGetToken(username: string, password: string, ser_no: string) {
    const params = new URLSearchParams();
    params.append("username", username);
    params.append("password", password);
    return axios.post(`${apiUrl}/api/v1/login/access-token?add_time_code=${ser_no}`, params);
  },
  async googleLogin(username: string) {
    const params = new URLSearchParams();
    params.append("username", username);
    params.append("password", "google");

    return axios.post(`${apiUrl}/api/v1/login/google/access-token`, params);
  },
  async qrGoogleLogin(username: string, ser_no: string) {
    const params = new URLSearchParams();
    params.append("username", username);
    params.append("password", "google");
    return axios.post(`${apiUrl}/api/v1/login/google/access-token?add_time_code=${ser_no}`, params);
  },
  async qrAddTime(token: string, code: string) {
    return axios.get(`${apiUrl}/api/v1/ser_nos/add-time?code=${code}`, authHeaders(token));
  },
  async getMe(token: string) {
    return axios.get<IUserProfile>(`${apiUrl}/api/v1/users/me`, authHeaders(token));
  },
  async updateMe(token: string, data: IUserProfileUpdate) {
    return axios.put<IUserProfile>(
      `${apiUrl}/api/v1/users/me`,
      data,
      authHeaders(token),
    );
  },
  async getUsers(token: string) {
    return axios.get<IUserProfile[]>(`${apiUrl}/api/v1/users/`, authHeaders(token));
  },
  async updateUser(token: string, userId: number, data: IUserProfileUpdate) {
    return axios.put(`${apiUrl}/api/v1/users/${userId}`, data, authHeaders(token));
  },
  async createUser(token: string, data: IUserProfileCreate) {
    return axios.post(`${apiUrl}/api/v1/users/create`, data, authHeaders(token));
  },
  async passwordRecovery(email: string) {
    return axios.post(`${apiUrl}/api/v1/password-recovery/${email}`);
  },
  async resetPassword(token: string, password: string) {
    return axios.post(`${apiUrl}/api/v1/reset-password/`, {
      token: token,
      new_password: password,
    });
  },
  async registerUser(data: IUserProfileCreate) {
    return axios.post(`${apiUrl}/api/v1/users/open`, data);
  },
  async testCeleryMsg(token: string, data: { msg: string }) {
    return axios.post<{ msg: string }>(`${apiUrl}/api/v1/utils/test-celery/msg`, data, authHeaders(token));
  },
  async testCeleryFile(token: string, file: File) {
    const formData = new FormData();
    formData.append("file", file)
    return axios.post<{ msg: string }>(`${apiUrl}/api/v1/utils/test-celery/file`, formData, authHeaders(token));
  },
  // 開發版本
  // async uploadPlot(token: string, video_data: VideoCreate, file: File) {
  //   const formData = new FormData();
  //   formData.append("upload_file", file)
  //   return axios.post<VideoUploaded>(`${apiUrl}/api/v1/videos/v1/?title=${video_data.title}&anchor=${video_data.anchor}&style=${video_data.style}&lang=${video_data.lang}`, formData, authHeaders(token));
  // },
  async uploadPlot(token: string, video_data: VideoCreate, file: File) {
    const formData = new FormData();
    formData.append("title", video_data.title)
    formData.append("anchor", video_data.anchor)
    formData.append("style", video_data.style)
    formData.append("lang", video_data.lang)
    formData.append("upload_file", file)
    return axios.post<VideoUploaded>(`${apiUrl}/api/v1/videos/`, formData, authHeaders(token));
  },
  async uploadImage(token: string, file: File[]) {
    const formData = new FormData();
    for (let i = 0; i < file.length; i++) {
      const element = file[i];
      formData.append("upload_files", element);
    }
    return axios.post<{ filenames: string[] }>(`${apiUrl}/api/v1/images/sr`, formData, authHeaders(token));
  },
  // async getImage(token: string, data: ImageDownload) {
  //   axios({
  //     url: `${apiUrl}/api/v1/images/sr?stored_file_name=${data.stored_file_name}&file_name=${data.file_name}`,
  //     method: 'GET',
  //     responseType: 'blob',
  //     headers: {
  //       'Authorization': `Bearer ${token}`
  //     },
  //   }).then((response) => {
  //     const href = URL.createObjectURL(response.data);
  //     const link = document.createElement('a');
  //     link.href = href;
  //     link.setAttribute('download', `${data.file_name}_hr.png`);
  //     document.body.appendChild(link);
  //     link.click();
  //     document.body.removeChild(link);
  //     URL.revokeObjectURL(href);
  //   });
  // },
  async downloadImage(token: string, data: ImageDownload) {
    return axios({
      url: `${apiUrl}/api/v1/images/sr?stored_file_name=${data.stored_file_name}&file_name=${data.file_name}`,
      method: 'GET',
      responseType: 'blob',
      headers: {
        'Authorization': `Bearer ${token}`
      },
    }).then((response) => {
      return response;
    });
  },
  async uploadArticle(token: string, article_data: ArticleCreate) {
    const formData = new FormData();
    formData.append("title", article_data.title)
    formData.append("link", article_data.link)
    formData.append("content", article_data.content)
    return axios.post<{ msg: string }>(`${apiUrl}/api/v1/reputations/`, formData, authHeaders(token));
  },
  async getVideos(token: string) {
    return axios.get<Video[]>(`${apiUrl}/api/v1/videos/`, authHeaders(token));
  },
  async ecpayPaymentHTML(token: string, amount: number) {
    const formData = new FormData();
    formData.append("amount", amount.toString());
    return axios.post<string>(`${apiUrl}/api/v1/payment/ecpayTestPay`, formData, authHeaders(token))
  },
  async YTViewsPayment(user_data: YTViewsUserData, lang: string) {
    const config = {
      params: {
        lang: lang
      }
    };
    return axios.post<string>(`${apiUrl}/api/v1/payment/ytviews-ecpay-payment?lang=${lang}`, user_data);
  },
  async YTViewsTestPayment(user_data: YTViewsUserData, lang: string) {
    return axios.post<string>(`${apiUrl}/api/v1/payment/ytviews-ecpay-test-payment?lang=${lang}`, user_data);
  },
  async getYTViewsList() {
    return axios.get(`${apiUrl}/api/v1/payment/ytviews-list-all`);
  },
  async Payment(payment_data: PaymentData, token: string, lang: string) {
    const config = {
      params: {
        lang: lang
      }
    };
    return axios.post<string>(`${apiUrl}/api/v1/payment/ecpay-payment?lang=${lang}`, payment_data, authHeaders(token));
  },
  async TestPayment(payment_data: PaymentData, token: string, lang: string) {
    return axios.post<string>(`${apiUrl}/api/v1/payment/ecpay-test-payment?lang=${lang}`, payment_data, authHeaders(token));
  },
  async getPaymentList() {
    return axios.get(`${apiUrl}/api/v1/payment/list-all`);
  },
  async uploadVideoContent(content: string, file: []) {
    // let content = "";
    console.log('api content',content);
    console.log('api file',file);
    
    const formData = new FormData();
    for (let index = 0; index < file.length; index++) {
      const element = file[index];
      formData.append("input_model", element)
    }
    return axios.post(`${apiUrl}/api/v1/videos/phone_input_json?text=${content}`, formData);
  },
};