<template>
  <client-detail-template>
    <template #button-return>
      <div class="col-12">
        <router-link
          to="/crm/clients"
          class="btn btn-outline-secondary btn-sm mb-3"
        >
          <i class="fas fa-arrow-left me-2"></i>Retour aux clients
        </router-link>
      </div>
    </template>
    <template #loading-state>
      <div v-if="isLoading" class="text-center p-5">
        <div class="spinner-border text-primary" role="status">
          <span class="visually-hidden">Chargement...</span>
        </div>
      </div>
    </template>
    <template #client-detail-sidebar>
      <ClientDetailSidebar
        :avatar-url="clientAvatar"
        :initials="getInitials(client.name)"
        :client-name="client.name"
        :client-type="client.type_label || 'Client'"
        :contacts-count="contacts.length"
        :locations-count="locations.length"
        :is-active="client.is_active"
        :active-tab="activeTab"
        @edit-avatar="triggerFileInput"
        @change-tab="activeTab = $event"
      />
    </template>
    <template #file-input>
      <input
        :ref="fileInput"
        type="file"
        class="d-none"
        accept="image/*"
        @change="handleAvatarUpload"
      />
    </template>
    <template #client-detail-content>
      <ClientDetailContent
        :active-tab="activeTab"
        :client="client"
        :contacts="contacts"
        :locations="locations"
        :formatted-address="formatAddress(client)"
        :client-id="client.id"
        :contact-is-loading="contactLoading"
        :location-is-loading="locationLoading"
        @change-tab="activeTab = $event"
        @updating-client="handleUpdateClient"
        @create-contact="handleAddContact"
        @create-location="handleAddLocation"
        @modify-location="handleModifyLocation"
        @remove-location="handleRemoveLocation"
      />
    </template>
  </client-detail-template>
</template>
<script setup>
import { defineProps, defineEmits, ref } from "vue";
import ClientDetailTemplate from "@/components/templates/CRM/ClientDetailTemplate.vue";
import ClientDetailSidebar from "./client/ClientDetailSidebar.vue";
import ClientDetailContent from "./client/ClientDetailContent.vue";
import { RouterLink } from "vue-router";

const props = defineProps({
  client: {
    type: Object,
    required: true,
  },
  contacts: {
    type: Array,
    required: false,
    default: () => [],
  },
  locations: {
    type: Array,
    required: false,
    default: () => [],
  },
  isLoading: {
    type: Boolean,
    default: false,
  },
  clientAvatar: {
    type: String,
    default: "",
  },
  activeTab: {
    type: String,
    default: "overview",
  },
  fileInput: {
    type: Object,
    required: true,
  },
  contactLoading: {
    type: Boolean,
    default: false,
  },
  locationLoading: {
    type: Boolean,
    default: false,
  },
});

const localAvatar = ref(props.clientAvatar);

const emit = defineEmits([
  "updateTheClient",
  "handleFileInput",
  "add-new-contact",
  "add-new-location",
  "modify-location",
  "remove-location",
]);

const handleAvatarUpload = (event) => {
  const file = event.target.files[0];
  if (file) {
    const reader = new FileReader();
    reader.onload = (e) => {
      localAvatar.value = e.target.result;
      // TODO: Upload to server
      console.log("Upload avatar to server");
    };
    reader.readAsDataURL(file);
  }
};

const handleUpdateClient = (updateData) => {
  emit("updateTheClient", updateData);
};

const inputFile = () => {
  emit("handleFileInput");
};

const handleAddContact = (data) => {
  emit("add-new-contact", data);
};

const handleAddLocation = (data) => {
  emit("add-new-location", data);
};

const handleModifyLocation = (location) => {
  emit("modify-location", location);
};

const handleRemoveLocation = (locationId) => {
  emit("remove-location", locationId);
};

const getInitials = (name) => {
  if (!name) return "?";
  return name
    .split(" ")
    .map((word) => word[0])
    .join("")
    .toUpperCase()
    .substring(0, 2);
};

const formatAddress = (client) => {
  const parts = [
    client.billing_address_line1,
    client.billing_address_line2,
    client.billing_postal_code,
    client.billing_city,
    client.billing_country_code,
  ].filter(Boolean);

  return parts.length > 0 ? parts.join(", ") : "Aucune adresse renseignée";
};
</script>
