<script setup>
import { usePanel } from "@/composables/useAccordionGroup";
import { computed, ref, watch } from "vue";

const props = defineProps({
  mode: { type: String, default: "create" },
  record: { type: Object, default: null },
  recordKey: { type: String, default: "activity_details" },
  loading: Boolean,
  panelKey: { type: String, default: "bottom-slider-0" },
  panelInjectionKey: {
    type: String,
    default: "activeActivityPanel",
  },
});

const emit = defineEmits(["open-media-picker"]);

const MAX_ITEMS = 10;

const items = ref([]);

const ensureItems = (raw) => {
  const list = Array.isArray(raw) ? raw : [];
  return list.slice(0, MAX_ITEMS).map((item) => ({
    tag: item?.tag ?? "",
    title: item?.title ?? "",
    robot_image: item?.robot_image ?? "",
  }));
};

const panel = usePanel(props.panelInjectionKey, props.panelKey);

// Only (re)load items when a DIFFERENT record is loaded (id + language change),
// NOT on every nested mutation. A deep watch here would reset the local list on
// each keystroke elsewhere, wiping newly added/removed slider items.
watch(
  () =>
    props.record
      ? `${props.record.id ?? ""}|${props.record.language ?? ""}`
      : "",
  () => {
    if (props.mode !== "edit" || !props.record) return;
    const details = props.record?.[props.recordKey] || {};
    items.value = ensureItems(
      details.bottom_sliders ?? props.record?.bottom_sliders ?? [],
    );
  },
  { immediate: true },
);

const canAddMore = computed(() => items.value.length < MAX_ITEMS);

const addItem = () => {
  if (!canAddMore.value) return;
  items.value = [...items.value, { tag: "", title: "", robot_image: "" }];
};

const removeItem = (index) => {
  items.value = items.value.filter((_, i) => i !== index);
};

const updateField = (index, key, value) => {
  const next = [...items.value];
  next[index] = { ...next[index], [key]: value };
  items.value = next;
};

// Ask the parent (EditProgram) to open its media picker for this row.
// Scope robots to this program: programrobot_<SLUG> (falls back to generic).
const openRobotImagePicker = (index) => {
  const slug = props.record?.slug;
  emit("open-media-picker", {
    fieldKey: "bottom_slider_robot",
    index,
    mediaCategory: slug ? `programrobot_${slug}` : "program_sliders",
    multiple: false,
  });
};

// Called back by the parent once an image is chosen.
const setRobotImage = (index, url) => {
  if (index == null || index < 0 || index >= items.value.length) return;
  updateField(index, "robot_image", url || "");
};

const sanitizedItems = computed(() =>
  items.value
    .map((item) => ({
      tag: (item.tag || "").trim(),
      title: (item.title || "").trim(),
      robot_image: (item.robot_image || "").trim(),
    }))
    .filter((item) => item.tag || item.title || item.robot_image),
);

defineExpose({
  getValues: () => sanitizedItems.value,
  setRobotImage,
});
</script>

<template>
  <div class="bottom-slider-form-container">
    <VExpansionPanels
      v-model="panel"
      variant="accordion"
      class="custom-accordion-panels"
      elevation="0"
    >
      <VExpansionPanel class="form-panel-card" elevation="0">
        <VExpansionPanelTitle class="section-header" hide-actions>
          <div class="section-header-content">
            <div class="section-left">
              <div class="section-icon-wrapper">
                <VIcon color="white" size="20">bx-slider-alt</VIcon>
              </div>
              <div class="section-text">
                <h3 class="section-name">Bottom Slider</h3>
                <div class="subtitle-row">
                  <p class="section-subtitle">
                    Tag + line shown in the page footer carousel
                  </p>
                  <span class="badge-count">
                    {{ items.length }} / {{ MAX_ITEMS }} items
                  </span>
                </div>
              </div>
            </div>
            <div class="section-right">
              <div class="chevron-wrapper">
                <VIcon size="24" class="custom-chevron">bx-chevron-down</VIcon>
              </div>
            </div>
          </div>
        </VExpansionPanelTitle>

        <VExpansionPanelText>
          <div class="panel-body-content">
            <div v-if="items.length === 0" class="empty-state">
              No slider items yet. Add up to {{ MAX_ITEMS }} items below.
            </div>

            <div
              v-for="(item, index) in items"
              :key="index"
              class="slider-row"
            >
              <div class="slider-row-index">{{ index + 1 }}</div>
              <div class="slider-row-fields">
                <div class="robot-image-field">
                  <span class="robot-image-label">Robot Image</span>
                  <div class="robot-image-row">
                    <div class="robot-image-box">
                      <img
                        v-if="item.robot_image"
                        :src="item.robot_image"
                        alt="Robot"
                        class="robot-image-img"
                      />
                      <VIcon v-else size="22" color="#94a3b8">bx-image</VIcon>
                    </div>
                    <div class="robot-image-actions">
                      <VBtn
                        variant="tonal"
                        color="primary"
                        size="small"
                        prepend-icon="bx-image-add"
                        :disabled="loading"
                        @click="openRobotImagePicker(index)"
                      >
                        {{ item.robot_image ? "Change Image" : "Select Image" }}
                      </VBtn>
                      <VBtn
                        v-if="item.robot_image"
                        variant="text"
                        color="error"
                        size="small"
                        icon="bx-x"
                        :disabled="loading"
                        @click="updateField(index, 'robot_image', '')"
                      />
                    </div>
                  </div>
                </div>
                <VTextField
                  :model-value="item.tag"
                  @update:model-value="updateField(index, 'tag', $event)"
                  label="Tag"
                  placeholder="e.g. FORTUNE CAROUSEL"
                  variant="outlined"
                  density="comfortable"
                  prepend-inner-icon="bx-purchase-tag"
                  :counter="50"
                  :maxlength="50"
                  :disabled="loading"
                  hide-details="auto"
                />
                <VTextarea
                  :model-value="item.title"
                  @update:model-value="updateField(index, 'title', $event)"
                  label="Line"
                  placeholder="Slide description text"
                  variant="outlined"
                  density="comfortable"
                  rows="2"
                  auto-grow
                  :counter="300"
                  :maxlength="300"
                  :disabled="loading"
                  hide-details="auto"
                />
              </div>
              <VBtn
                icon
                variant="text"
                color="error"
                :disabled="loading"
                @click="removeItem(index)"
                class="slider-row-remove"
              >
                <VIcon>bx-trash</VIcon>
                <VTooltip activator="parent" location="top">
                  Remove item
                </VTooltip>
              </VBtn>
            </div>

            <div class="add-row">
              <VBtn
                color="primary"
                variant="tonal"
                prepend-icon="bx-plus"
                :disabled="!canAddMore || loading"
                @click="addItem"
              >
                Add Slider Item
              </VBtn>
              <span v-if="!canAddMore" class="limit-note">
                Maximum {{ MAX_ITEMS }} items reached
              </span>
            </div>
          </div>
        </VExpansionPanelText>
      </VExpansionPanel>
    </VExpansionPanels>
  </div>
</template>

<style scoped>
.bottom-slider-form-container {
  width: 100%;
}
.bottom-slider-form-container.bottom-slider-attached {
  margin-top: 8px;
}

.form-panel-card {
  border-radius: 8px !important;
  border: 1px solid #e2e8f0;
  background: #ffffff;
  transition: all 0.2s ease;
  overflow: hidden;
  margin-bottom: 0;
}
.form-panel-card::before {
  box-shadow: none !important;
}
.form-panel-card.v-expansion-panel--active {
  border-color: #2196f3;
  box-shadow: 0 4px 12px rgba(33, 150, 243, 0.1) !important;
}

.section-header {
  padding: 8px 16px !important;
  min-height: 56px !important;
  background-color: #fff;
}
.form-panel-card.v-expansion-panel--active .section-header {
  background-color: #f8fbff;
}

.section-header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}
.section-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.section-icon-wrapper {
  width: 40px;
  height: 40px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #003b6f, #00569e);
  box-shadow: 0 4px 10px rgba(0, 59, 111, 0.2);
}

.section-text {
  display: flex;
  flex-direction: column;
  justify-content: center;
}
.section-name {
  margin: 0;
  font-size: 15px;
  font-weight: 700;
  color: #1e293b;
  line-height: 1.2;
}

.subtitle-row {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-top: 2px;
}
.section-subtitle {
  margin: 0;
  font-size: 12px;
  color: #64748b;
}
.badge-count {
  font-size: 10px;
  font-weight: 600;
  color: #64748b;
  background: #f1f5f9;
  padding: 1px 6px;
  border-radius: 4px;
  border: 1px solid #e2e8f0;
}

.section-right {
  display: flex;
  align-items: center;
}

.chevron-wrapper {
  transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  display: flex;
}
.form-panel-card.v-expansion-panel--active .chevron-wrapper {
  transform: rotate(180deg);
}
.custom-chevron {
  color: #94a3b8;
}
.form-panel-card.v-expansion-panel--active .custom-chevron {
  color: #2196f3;
}

.panel-body-content {
  padding: 20px 4px 4px;
}

.empty-state {
  font-size: 13px;
  color: #64748b;
  background: #f8fafc;
  border: 1px dashed #cbd5e1;
  border-radius: 8px;
  padding: 16px;
  text-align: center;
  margin-bottom: 16px;
}

.slider-row {
  display: flex;
  gap: 12px;
  align-items: flex-start;
  background: #f8fafc;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  padding: 12px;
  margin-bottom: 12px;
}

.slider-row-index {
  width: 28px;
  height: 28px;
  border-radius: 50%;
  background: #e2e8f0;
  color: #475569;
  font-size: 12px;
  font-weight: 700;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  margin-top: 6px;
}

.slider-row-fields {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.robot-image-field {
  display: flex;
  flex-direction: column;
  gap: 6px;
}
.robot-image-label {
  font-size: 12px;
  font-weight: 600;
  color: #475569;
}
.robot-image-row {
  display: flex;
  align-items: center;
  gap: 12px;
}
.robot-image-box {
  width: 84px;
  height: 64px;
  border-radius: 8px;
  background: #ffffff;
  border: 1px solid #e2e8f0;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  flex-shrink: 0;
}
.robot-image-img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}
.robot-image-actions {
  display: flex;
  align-items: center;
  gap: 6px;
}

.slider-row-remove {
  margin-top: 4px;
  flex-shrink: 0;
}

.add-row {
  display: flex;
  align-items: center;
  gap: 12px;
  padding-top: 4px;
}
.limit-note {
  font-size: 12px;
  color: #94a3b8;
}
</style>
