<template>
  <div class="add-to-group-wrapper">
    <ReusableModal
      :visible="visible"
      title="Add Franchisees to Groups"
      :fields="modalFields"
      :model-value="formData"
      :loading="loading"
      :validation-schema="validationSchema"
      submit-label="Add to Groups"
      cancel-label="Cancel"
      @update:visible="handleClose"
      @update:model-value="handleFormUpdate"
      @submit="handleSubmit"
      @cancel="handleClose"
    >
      <!-- Custom content slot for selected franchisees display -->
      <template #custom-content>
        <div class="selected-franchisees-section">
          <div class="franchisees-list">
            <div
              v-for="franchisee in selectedFranchisees"
              :key="franchisee.id"
              class="franchisee-item"
            >
              <i class="bx bx-building-house"></i>
              <span>{{ franchisee.name }}</span>
            </div>
          </div>
        </div>
      </template>
    </ReusableModal>
  </div>
</template>

<script setup>
import { ref, computed, watch } from "vue";
import * as yup from "yup";
import ReusableModal from "@/components/ReusableModal.vue";

const props = defineProps({
  visible: {
    type: Boolean,
    required: true,
  },
  selectedFranchisees: {
    type: Array,
    required: true,
    default: () => [],
  },
  groups: {
    type: Array,
    required: true,
    default: () => [],
  },
  loading: {
    type: Boolean,
    default: false,
  },
});

const emit = defineEmits(["update:visible", "submit"]);

const formData = ref({
  group_ids: [],
});

// ✅ Validation schema - Accept UUID strings
const validationSchema = yup.object({
  group_ids: yup
    .array()
    .of(yup.string().uuid("Invalid group ID"))
    .min(1, "Please select at least one group")
    .required("Please select at least one group"),
});

// ✅ NEW: Get already assigned group IDs for selected franchisees
const getAlreadyAssignedGroupIds = () => {
  if (props.selectedFranchisees.length === 0) {
    return [];
  }

  // If selecting multiple franchisees, get groups that ALL of them have
  // (intersection of all groups)
  if (props.selectedFranchisees.length === 1) {
    // For single franchisee, return their groups
    const franchisee = props.selectedFranchisees[0];
    return (franchisee.groups || []).map((g) => g.id);
  } else {
    // For multiple franchisees, find common groups
    const franchiseeIds = props.selectedFranchisees.map((f) => f.id);

    // Get all group IDs from the first franchisee
    const firstFranchiseeGroups = new Set(
      (props.selectedFranchisees[0].groups || []).map((g) => g.id),
    );

    // Find groups that exist in all franchisees
    const commonGroupIds = Array.from(firstFranchiseeGroups).filter((groupId) =>
      props.selectedFranchisees.every((f) =>
        (f.groups || []).some((g) => g.id === groupId),
      ),
    );

    return commonGroupIds;
  }
};

// ✅ NEW: Filter groups to exclude already assigned ones
const groupOptions = computed(() => {
  const assignedGroupIds = getAlreadyAssignedGroupIds();

  return props.groups
    .filter((group) => !assignedGroupIds.includes(group.id))
    .map((group) => ({
      value: group.id,
      title: group.name,
    }));
});

// Modal fields configuration
const modalFields = computed(() => [
  {
    name: "group_ids",
    label: "Select Groups",
    type: "multiselect",
    placeholder: "Choose one or more groups",
    options: groupOptions.value,
    optionLabel: "title",
    optionValue: "value",
    required: true,
    disabled: props.loading || groupOptions.value.length === 0,
  },
]);

// Handle form data updates
const handleFormUpdate = (data) => {
  formData.value = { ...data };
};

// Reset state when modal opens
watch(
  () => props.visible,
  (newVal) => {
    if (newVal) {
      formData.value = {
        group_ids: [],
      };
    }
  },
);

const handleClose = () => {
  emit("update:visible", false);
};

const handleSubmit = async (data) => {
  try {
    // Ensure group_ids are strings
    const submitData = {
      group_ids: Array.isArray(data.group_ids)
        ? data.group_ids.map((id) => String(id))
        : [],
    };

    await emit("submit", submitData);

    // Reset on success
    formData.value = {
      group_ids: [],
    };
  } catch (error) {
    console.error("Error adding to groups:", error);
  }
};
</script>

<style scoped>
.selected-franchisees-section {
  margin-bottom: 1.25rem;
  padding: 1rem;
  background: #f8fafc;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
}

.franchisees-list {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
  max-height: 120px;
  overflow-y: auto;
}

.franchisees-list::-webkit-scrollbar {
  width: 4px;
}

.franchisees-list::-webkit-scrollbar-track {
  background: #f1f5f9;
  border-radius: 2px;
}

.franchisees-list::-webkit-scrollbar-thumb {
  background: #003b6f;
  border-radius: 2px;
}

.franchisee-item {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.5rem 0.75rem;
  background: #ffffff;
  border: 1px solid #e2e8f0;
  border-radius: 6px;
  font-size: 0.875rem;
  color: #1e293b;
  transition: all 0.2s ease;
}

.franchisee-item:hover {
  border-color: #003b6f;
  background: #f8fafc;
}

.franchisee-item i {
  font-size: 1rem;
  color: #003b6f;
  flex-shrink: 0;
}

.franchisee-item span {
  flex: 1;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* Override ReusableModal styles */
:deep(.compact-modal-card) {
  max-width: 500px !important;
}

:deep(.modal-header) {
  background: linear-gradient(135deg, #003b6f 0%, #0055a0 100%) !important;
}

:deep(.modal-title) {
  font-size: 1.25rem !important;
}

:deep(.submit-btn) {
  background: linear-gradient(135deg, #003b6f 0%, #0055a0 100%) !important;
  min-width: 130px !important;
  font-weight: 600 !important;
}

:deep(.v-select) {
  margin-bottom: 0 !important;
}

:deep(.v-field) {
  border-radius: 6px !important;
  border: 1px solid #cbd5e1 !important;
  min-height: 48px !important;
}

:deep(.v-field--focused) {
  border-color: #003b6f !important;
  box-shadow: 0 0 0 2px rgba(0, 59, 111, 0.1) !important;
}

:deep(.v-select__selections) {
  padding: 0.25rem 0.5rem !important;
  gap: 0.25rem !important;
  display: flex !important;
  flex-wrap: wrap !important;
  align-items: center !important;
}

:deep(.v-chip) {
  background: #003b6f !important;
  color: #ffffff !important;
  font-weight: 500 !important;
  border-radius: 4px !important;
  padding: 0 0.5rem !important;
  height: 22px !important;
  font-size: 0.75rem !important;
  line-height: 22px !important;
  margin: 2px !important;
}

:deep(.v-chip .v-chip__content) {
  padding: 0 !important;
}

:deep(.v-chip .v-chip__close) {
  color: rgba(255, 255, 255, 0.9) !important;
  margin-left: 0.25rem !important;
  font-size: 14px !important;
  width: 16px !important;
  height: 16px !important;
}

:deep(.v-overlay) {
  contain: layout style paint !important;
}

:deep(.v-overlay--active) {
  z-index: 9999 !important;
}

:deep(.v-menu > .v-overlay__content) {
  top: 100% !important;
  bottom: auto !important;
  margin-top: 4px !important;
}

:deep(.v-select__menu-content) {
  border-radius: 6px !important;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15) !important;
  max-height: 280px !important;
  overflow-y: auto !important;
}

:deep(.v-list) {
  padding: 0.25rem !important;
  max-height: 270px !important;
}

:deep(.v-list-item) {
  padding: 0.625rem 1rem !important;
  min-height: 40px !important;
}

@media (max-width: 768px) {
  :deep(.compact-modal-card) {
    max-width: 100% !important;
    margin: 0.75rem !important;
  }
}
</style>
