<template>
  <div class="card h-100">
    <div class="card-header pb-0 p-3">
      <div class="row">
        <div class="col-md-8 d-flex align-items-center">
          <h6 class="mb-0">Gestion des sous-comptes</h6>
        </div>
        <div class="col-md-4 text-end">
          <!-- Toggle Is Parent -->
          <div class="form-check form-switch d-inline-block ms-auto">
            <input
              id="isParentToggle"
              class="form-check-input"
              type="checkbox"
              :checked="client.is_parent"
              @change="toggleParentStatus"
            />
            <label class="form-check-label" for="isParentToggle"
              >Compte Parent</label
            >
          </div>
          <!-- Add Child Button -->
          <soft-button
            v-if="client.is_parent"
            size="sm"
            variant="gradient"
            color="success"
            class="ms-3"
            @click="showAddModal = true"
          >
            <i class="fas fa-plus me-2"></i>Ajouter un sous-client
          </soft-button>
        </div>
      </div>
    </div>
    <div class="card-body p-3">
      <div v-if="!client.is_parent" class="text-center py-4">
        <p class="text-muted">
          Ce client n'est pas défini comme compte parent. Activez l'option
          ci-dessus pour gérer des sous-comptes.
        </p>
      </div>

      <div v-else>
        <div v-if="loading" class="text-center py-4">
          <div class="spinner-border text-primary" role="status">
            <span class="visually-hidden">Chargement...</span>
          </div>
        </div>

        <div v-else-if="children.length === 0" class="text-center py-4">
          <p class="text-muted">Aucun sous-compte associé.</p>
        </div>

        <ul v-else class="list-group">
          <li
            v-for="child in children"
            :key="child.id"
            class="list-group-item border-0 d-flex justify-content-between ps-0 mb-2 border-radius-lg"
          >
            <div class="d-flex align-items-center">
              <soft-avatar
                :img="getAvatar(child.name)"
                size="sm"
                border-radius="md"
                class="me-3"
                alt="child client"
              />
              <div class="d-flex flex-column">
                <h6 class="mb-1 text-dark text-sm">{{ child.name }}</h6>
                <span class="text-xs">{{ child.email }}</span>
              </div>
            </div>
            <div class="d-flex align-items-center text-sm">
              <button
                class="btn btn-link text-dark text-sm mb-0 px-0 ms-4"
                @click="goToClient(child.id)"
              >
                <i class="fas fa-eye text-lg me-1"></i> Voir
              </button>
              <button
                class="btn btn-link text-danger text-gradient px-3 mb-0"
                @click="confirmRemoveChild(child)"
              >
                <i class="far fa-trash-alt me-2"></i> Détacher
              </button>
            </div>
          </li>
        </ul>
      </div>
    </div>

    <AddChildClientModal
      :show="showAddModal"
      :exclude-ids="[client.id, client.parent_id, ...children.map((c) => c.id)]"
      @close="showAddModal = false"
      @add="handleAddChild"
    />
  </div>
</template>

<script setup>
import { computed, ref, onMounted, watch, defineProps, defineEmits } from "vue";
import SoftButton from "@/components/SoftButton.vue";
import SoftAvatar from "@/components/SoftAvatar.vue";
import AddChildClientModal from "@/components/Organism/CRM/client/AddChildClientModal.vue";
import { useClientStore } from "@/stores/clientStore";
import { useRouter } from "vue-router";
import Swal from "sweetalert2";

const props = defineProps({
  client: {
    type: Object,
    required: true,
  },
});

const emit = defineEmits(["update-client"]);
const clientStore = useClientStore();
const router = useRouter();
const children = ref([]);
const loading = ref(false);
const showAddModal = ref(false);

const fetchChildren = async () => {
  if (!props.client.is_parent) return;
  loading.value = true;
  try {
    const res = await clientStore.fetchChildClients(props.client.id);
    children.value = res.data || res; // handle potential array vs response structure
  } catch (e) {
    console.error("Failed to fetch children", e);
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  fetchChildren();
});

watch(
  () => props.client.is_parent,
  (newVal) => {
    if (newVal) fetchChildren();
  }
);

/* eslint-disable require-atomic-updates */
const toggleParentStatus = async (e) => {
  const isChecked = e.target.checked;

  // Optimistic update
  // emit('update-client', { ...props.client, is_parent: isChecked });

  try {
    // We'll update the client via store, passing just the id and field to update
    await clientStore.updateClient({
      id: props.client.id,
      name: props.client.name,
      is_parent: isChecked,
    });
    // The parent component should react to store changes if it watches it, or we emit updated
  } catch (err) {
    // Revert on error
    e.target.checked = !isChecked;
    Swal.fire(
      "Erreur",
      "Impossible de mettre à jour le statut parent.",
      "error"
    );
  }
};

const handleAddChild = async (selectedClient) => {
  try {
    await clientStore.addChildClient(props.client.id, selectedClient.id);
    Swal.fire("Succès", "Le client a été ajouté comme sous-compte.", "success");
    fetchChildren();
  } catch (e) {
    Swal.fire("Erreur", "Impossible d'ajouter le sous-compte.", "error");
  }
};

const confirmRemoveChild = async (child) => {
  const result = await Swal.fire({
    title: "Confirmer le détachement",
    text: `Voulez-vous vraiment détacher ${child.name} ?`,
    icon: "warning",
    showCancelButton: true,
    confirmButtonText: "Oui, détacher",
    cancelButtonText: "Annuler",
  });

  if (result.isConfirmed) {
    try {
      await clientStore.removeChildClient(props.client.id, child.id);
      Swal.fire("Détaché!", "Le client a été détaché.", "success");
      children.value = children.value.filter((c) => c.id !== child.id);
    } catch (e) {
      Swal.fire("Erreur", "Impossible de détacher le client.", "error");
    }
  }
};

const goToClient = (id) => {
  router.push(`/crm/clients/${id}`); // Adjust route as needed
};

// Helper for initials/avatar
const getAvatar = (name) => {
  // placeholder logic, replace with actual avatar logic or component usage
  return null;
};
</script>
