import React, { createContext, useState, useEffect } from "react";
import axios from "axios";

export const AuthContext = createContext();

const API_URL = "/api";
const BASE_URL = import.meta.env.VITE_API_URL ? import.meta.env.VITE_API_URL.replace('/api', '') : "http://localhost:3000";

function AuthProvider({ children }) {
  const [userLogin, setUserLogin] = useState(null);
  const [token, setToken] = useState(localStorage.getItem("token") || null);
  const [daftarKursus, setDaftarKursus] = useState([]);

  useEffect(function() {
    let savedUser = localStorage.getItem("userLogin");
    if (savedUser) {
      setUserLogin(JSON.parse(savedUser));
    }
    
    ambilSemuaKursus();
  }, []);

  async function ambilSemuaKursus() {
    try {
      let respon = await axios.get(API_URL + "/products");
      if (respon.data.status === "berhasil") {
        let rawData = respon.data.data;
        
        let dataMapped = [];
        for (let i = 0; i < rawData.length; i++) {
          let urlGambar = rawData[i].image;
          if (urlGambar && !urlGambar.startsWith("http")) {
            urlGambar = BASE_URL + "/public/uploads/" + urlGambar;
          } else if (!urlGambar) {
            urlGambar = "https://placehold.co/400x220?text=No+Image";
          }

          dataMapped.push({
            id: rawData[i].id,
            judul: rawData[i].name,
            kategori: rawData[i].category,
            harga: rawData[i].price,
            instruktur: "Admin Pendidikan",
            thumbnail: urlGambar,
            deskripsi: rawData[i].description,
            video: rawData[i].video
          });
        }
        setDaftarKursus(dataMapped);
      }
    } catch (error) {
      console.log("Gagal ambil kursus:", error);
    }
  }

  async function login(email, password) {
    try {
      let respon = await axios.post(API_URL + "/auth/login", {
        email: email,
        password: password
      });

      if (respon.data.status === "sukses") {
        let dataApi = respon.data.data;
        
        let dataUser = {
          id: dataApi.id,
          nama: dataApi.nama,
          role: dataApi.peran
        };
        
        let dataToken = dataApi.token;

        setUserLogin(dataUser);
        setToken(dataToken);

        localStorage.setItem("userLogin", JSON.stringify(dataUser));
        localStorage.setItem("token", dataToken);

        return { sukses: true, user: dataUser };
      } else {
        return { sukses: false, pesan: respon.data.message || "Login gagal!" };
      }
    } catch (error) {
      let pesanError = "Email atau Password salah!";
      if (error.response && error.response.data) {
        pesanError = error.response.data.message;
      }
      return { sukses: false, pesan: pesanError };
    }
  }

  function logout() {
    setUserLogin(null);
    setToken(null);
    localStorage.removeItem("userLogin");
    localStorage.removeItem("token");
  }

  async function register(nama, email, password, province, city, district) {
    try {
      let respon = await axios.post(API_URL + "/auth/register", {
        name: nama,
        email: email,
        password: password,
        province: province,
        city: city,
        district: district
      });

      if (respon.data.status === "sukses") {
        return { sukses: true };
      } else {
        return { sukses: false, pesan: respon.data.message || "Pendaftaran gagal!" };
      }
    } catch (error) {
      let pesanError = "Gagal mendaftar, coba lagi nanti";
      if (error.response && error.response.data) {
        pesanError = error.response.data.message;
      }
      return { sukses: false, pesan: pesanError };
    }
  }

  async function tambahKursus(formData) {
    try {
      let respon = await axios.post(API_URL + "/products", formData, {
        headers: { 
          Authorization: "Bearer " + token,
          "Content-Type": "multipart/form-data"
        }
      });
      if (respon.data.status === "sukses") {
        ambilSemuaKursus();
        return true;
      }
    } catch (error) {
      console.log("Gagal tambah kursus:", error);
      return false;
    }
  }

  async function editKursus(id, formData) {
    try {
      let respon = await axios.put(API_URL + "/products/" + id, formData, {
        headers: { 
          Authorization: "Bearer " + token,
          "Content-Type": "multipart/form-data"
        }
      });
      if (respon.data.status === "sukses") {
        ambilSemuaKursus();
        return true;
      }
    } catch (error) {
      console.log("Gagal edit kursus:", error);
      return false;
    }
  }

  async function hapusKursus(id) {
    try {
      let respon = await axios.delete(API_URL + "/products/" + id, {
        headers: { Authorization: "Bearer " + token }
      });
      if (respon.data.status === "sukses") {
        ambilSemuaKursus();
        return true;
      }
    } catch (error) {
      console.log("Gagal hapus kursus:", error);
      return false;
    }
  }

  return (
    <AuthContext.Provider
      value={{
        userLogin: userLogin,
        token: token,
        daftarKursus: daftarKursus,
        login: login,
        logout: logout,
        register: register,
        tambahKursus: tambahKursus,
        editKursus: editKursus,
        hapusKursus: hapusKursus,
        ambilSemuaKursus: ambilSemuaKursus
      }}
    >
      {children}
    </AuthContext.Provider>
  );
}

export default AuthProvider;
