<script setup>
import axios from 'axios';
import { onMounted, ref, computed } from "vue";
import NavbarDefault from "../../../examples/navbars/NavbarDefault.vue";
import { useRouter } from "vue-router";




const isAuthenticated = computed(() => !!sessionStorage.getItem('access_token'));
const userId = computed(() => sessionStorage.getItem('user_id'));
const loggedUserName = computed(() => sessionStorage.getItem('username'));
const token = computed(() => sessionStorage.getItem('access_token'));

const profileData = ref([]);
const router = useRouter();

const debugText = ref('');


const getProfile = async () => {
    const profileDataRecieved = await axios.get(`http://somebodyhire.me/api/profile/${userId.value}/`);
    profileData.value = processProfileData(profileDataRecieved.data);
};

const processProfileData = (data) => {
    return {
        ...data,
        name: data.name || '🤷 No Name Provided',
        location: data.location || '🌍 No Location Provided',
        short_intro: data.short_intro || '📝 No Short Intro Provided',
        bio: data.bio || '📘 No Bio Provided',
        profile_image: data.profile_image || '📷 No Image Provided',
        social_github: data.social_github || '👨‍💻 No Github Provided',
        social_twitter: data.social_twitter || '🐦 No Twitter Provided',
        social_vk: data.social_vk || '🔵 No VK Provided',
        social_youtube: data.social_youtube || '▶️ No YouTube Provided',
        social_website: data.social_website || '🌐 No Website Provided',
    };
};

// Axios request and response interceptors
axios.interceptors.request.use((request) => {
  debugText.value += '\n\nRequest:\n' + JSON.stringify(request, null, 2);
  return request;
});

axios.interceptors.response.use((response) => {
  debugText.value += '\n\nResponse:\n' + JSON.stringify(response, null, 2);
  return response;
}, (error) => {
  debugText.value += '\n\nResponse Error:\n' + JSON.stringify(error.toJSON(), null, 2);
  return Promise.reject(error);
});

const updateProfile = async () => {
    try {
        const token = computed(() => sessionStorage.getItem('access_token'));
        debugText.value = `Type of token: ${typeof token.value}, Value of token: ${token.value}`;
        const headers = { 'Authorization': `Bearer ${token.value}` };
        await axios.put(`http://somebodyhire.me/api/profile/${userId.value}/`, profileData.value, { headers });
        router.push('/ViewMyProfile');
    } catch (error) {
        debugText.value = `Error: ${JSON.stringify(error, null, 2)}`;
        console.error(error);
    }
};


const cancelUpdate = () => {
    router.push('/ViewMyProfile');
};

onMounted(async() => {
    await getProfile();
});


</script>

<script>



</script>


<template>
    <NavbarDefault />
    <div class="profile-container">
      <h1>Профиль пользователя {{ loggedUserName }}</h1>
        <textarea readonly v-model="debugText"></textarea>
        <input type="text" v-model="profileData.username" placeholder="Username">
        <input type="email" v-model="profileData.email" placeholder="Email">
        <input type="text" v-model="profileData.name" placeholder="Имя">
        <input type="text" v-model="profileData.short_intro" placeholder="Краткое описание">
        <textarea v-model="profileData.bio" placeholder="Биография"></textarea>
        <textarea v-model="profileData.profile_image" placeholder="Ссылка на изображение"></textarea>
        <textarea v-model="profileData.social_github" placeholder="Ссылка на GitHub"></textarea>
        <textarea v-model="profileData.social_twitter" placeholder="Ссылка на Twitter"></textarea>
        <textarea v-model="profileData.social_vk" placeholder="Ссылка на VK"></textarea>
        <textarea v-model="profileData.social_youtube" placeholder="Ссылка на YouTube"></textarea>
        <textarea v-model="profileData.social_website" placeholder="Ссылка на сайт"></textarea>
        <button @click="updateProfile" class="btn-submit">Submit</button>
        <button @click="cancelUpdate" class="btn-cancel">Cancel</button>
    </div>


</template>



<style scoped>
.profile-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 80%;
  margin: auto;
  padding: 20px;
  box-shadow: 0px 0px 10px 0px rgba(0,0,0,0.1);
}

.profile-container img {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  object-fit: cover;
  margin-bottom: 20px;
}


.profile-container input, .profile-container textarea {
  width: 100%; /* Make inputs and textareas take up the full width of the container */
  padding: 10px; /* Add some padding */
  margin-bottom: 15px; /* Add some margin */
  box-sizing: border-box; /* Ensure padding doesn't affect final dimensions */
  border: 1px solid #ccc; /* Add a border */
  border-radius: 5px; /* Add rounded corners */
}

/* Style for smaller screens */
@media (max-width: 768px) {
  .profile-container {
    width: 95%;
  }
}


.btn-submit {
    color: #fff;
    background-color: #4CAF50;
    border: none;
    padding: 15px 32px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 16px;
    margin: 4px 2px;
    cursor: pointer;
    border-radius: 5px;
}

.btn-cancel {
    color: #fff;
    background-color: #f44336;
    border: none;
    padding: 15px 32px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 16px;
    margin: 4px 2px;
    cursor: pointer;
    border-radius: 5px;
}
</style>