<script setup>
import { ref, onBeforeMount } from 'vue';
import { getUserInfo, uploadDocument } from '../api';
import { useRouter } from 'vue-router';
import BottomNav from '@/components/BottomNav.vue'

const router = useRouter();
const user = ref({
  firstName: '',
  lastName: '',
  phone: '',
  passport: '',
  prava: '',
  avatar: ''
});

const isLoaded = ref(false);
const avatar = ref('');
const passportInput = ref(null);
const pravaInput = ref(null);
const avatarInput = ref(null);

const handleFileChange = async (event, filename) => {
  const file = event.target.files[0];
  const fileUpload = new File([file], filename, { type: file.type })
  if (!file) return;

  try {
    const formData = new FormData();
    formData.append('file', fileUpload);
   
    const response = await uploadDocument(formData);
    if (response.status === 200) {
      alert('Файл успешно загружен');
      const userResponse = await getUserInfo();
      user.value = userResponse.data;
    }
  } catch (error) {
    console.error('Ошибка при загрузке файла:', error);
    alert('Ошибка при загрузке файла');
  }
};

onBeforeMount(async () => {
  try {
    const response = await getUserInfo();
    user.value = response.data;
    if (!user.value.avatar) {
      avatar.value = "../assets/car.png"
      console.log(avatar.value)
    }
    console.log(user.value)
    isLoaded.value = true;
  } catch (error) {
    console.error('Failed to load user info:', error);
  }
  
});


const handleLogout = () => {
  localStorage.removeItem('bearerToken');
  router.push({ name: 'signin' });
};
</script>

<template>
  <body v-if="isLoaded">
    <div class="profile-container">
      <div class="profile-header">
        <div class="avatar-section">
          
              <img :style="{border: user.valid ? '5px solid green' : '5px solid yellow'}" :src="`https://carsharing.kolei.ru/images/${user.avatar}`"
              class = "avatar">
          
          <div class="edit-icon">
            <i class="material-icons" @click="avatarInput.click()">edit </i>
          </div>
        </div>
        <div class="user-name">{{ user.firstName }} {{ user.lastName }}</div>
        <div class="user-email">{{ user.phone }}</div>
      </div>

      <div class="menu-section">
        <input 
          type="file" 
          ref="passportInput" 
          @change="(event) => handleFileChange(event, 'passport.jpg')" 
          accept=".jpg, .jpeg"
          hidden
        >
        <input 
          type="file" 
          ref="pravaInput" 
          @change="(event) => handleFileChange(event, 'prava.jpg')" 
          accept=".jpg, .jpeg"
          hidden
        >
        <input 
          type="file" 
          ref="avatarInput" 
          @change="(event) => handleFileChange(event, 'avatar.jpg')" 
          accept=".jpg, .jpeg"
          hidden
        >
        <h1 v-if="user.valid">Вы молодец у вас всё есть!</h1>
        <div v-if="!user.passport" class="menu-item" @click="passportInput.click()" :class="{ 'disabled': isUploading }">
          <i class="material-icons">add_photo_alternate</i>
          <span>Загрузить фото паспорта</span>
          <i class="material-icons chevron">chevron_right</i>
        </div>

        <div v-if="!user.prava" class="menu-item" @click="pravaInput.click()">
          <i class="material-icons">add_photo_alternate</i>
          <span>Загрузить фото водительских прав</span>
          <i class="material-icons chevron">chevron_right</i>
        </div>
        <div class="logout-button" @click="handleLogout">
        <i class="material-icons">logout</i>
        <span>Выход</span>
      </div>
      </div>
    </div>
  </body>
  <BottomNav/>
</template>

<style scoped>
.profile-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  padding: 20px;
  color: black;
}

.profile-header {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 40px;
}
.logout-button {
  width: 100%;
  display: flex;
  align-items: center;
  padding: 16px;
  background: #2196F3;
  align-items: center;
  justify-content: center;
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 8px;
  color: #2c74a4;
  cursor: pointer;
}
.avatar-section {
  position: relative;
  margin-bottom: 16px;
}

.avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  background-color: #f0f0f0;
  margin-bottom: 8px;
  object-fit: cover;
}

.edit-icon {
  position: absolute;
  right: -8px;
  bottom: 0;
  background-color: white;
  border-radius: 50%;
  padding: 4px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.user-name {
  font-size: 18px;
  font-weight: 500;
  margin-bottom: 4px;
  color: black;
}

.user-email {
  font-size: 14px;
  color: black;
}

.menu-section {
  flex: 1;
}

.menu-item {
  display: flex;
  align-items: center;
  padding: 16px 0;
  border-bottom: 1px solid rgba(0,0,0,0.1);
  color: black;
  cursor: pointer;
}

.menu-item i {
  margin-right: 16px;
  color: black;
}

.menu-item span {
  flex: 1;
  color: black;
}

.chevron {
  color: black;
}

.logout-button {
  display: flex;
  align-items: center;
  padding: 16px 0;
  color: black;
  cursor: pointer;
}

.logout-button i {
  margin-right: 16px;
  color: black;
}

.logout-button span {
  color: black;
}

.menu-item.disabled {
  opacity: 0.5;
  pointer-events: none;
}

.back-button {
  display: flex;
  align-items: center;
  padding: 16px 0;
  margin-bottom: 20px;
  cursor: pointer;
  color: black;
}

.back-button i {
  margin-right: 8px;
}

.back-button span {
  font-size: 16px;
}
</style>