<script setup>
import MediaPickerModal from "@/components/MediaPickerModal.vue";
import PublishDraftActions from "@/components/PublishDraftActions.vue";
import { useActivityStore } from "@/stores/activityStore";
import SlugConflictDialog from "@/components/SlugConflictDialog.vue";
import { getSlugConflictPayload } from "@/composables/useStoreHelpers";
import { computed, provide, ref } from "vue";
import { useRouter } from "vue-router";
import AccordionSection from "@/components/AccordionSection.vue";
import AccordionExpandToggle from "@/components/AccordionExpandToggle.vue";
import {
  createAccordionGroup,
  usePanelIn,
} from "@/composables/useAccordionGroup";
import SeoFields from "@/components/SeoFields.vue";
import BasicActivityForm from "./BasicActivityForm.vue";
import WorkshopDetailsForm from "./WorkshopDetailsForm.vue";
import AiFeatureForm from "@/components/AiFeatureForm.vue";

const router = useRouter();
const activityStore = useActivityStore();
const saving = computed(() => activityStore.saving);
const saveAction = ref(null);

const normalizeSlug = (s) =>
  (s ? s.toString().toUpperCase().replace(/[^A-Z0-9]/g, "") : "");
// Workshops that show the AI section on the public site (by normalized slug).
const AI_SECTION_SLUGS = ["CODING_CAMPS"].map(normalizeSlug);

const activityFormRef = ref(null);
const workshopFormRef = ref(null);
const aiFeatureFormRef = ref(null);

// Show the AI editor only when the entered slug is an AI-enabled workshop.
const showAiSection = computed(() =>
  AI_SECTION_SLUGS.includes(
    normalizeSlug(
      activityFormRef.value?.values?.slug ||
        activityFormRef.value?.computedSlug ||
        "",
    ),
  ),
);
const showSlugConflictDialog = ref(false);
const slugConflict = ref(null);
const pendingPayload = ref(null);

// Shared state for accordion panels
// No seed key: every section starts collapsed.
const activityAccordion = createAccordionGroup();
provide("activeActivityPanel", activityAccordion);

// SEO title/meta live on the translation. Owned here so the panel renders last,
// after every other form section, coordinating with the shared accordion state.
const seo = ref({ seo_title: "", seo_description: "" });
const SEO_PANEL_KEY = "seo-0";
const seoPanel = usePanelIn(activityAccordion, SEO_PANEL_KEY);

// Media picker state
const showMediaPicker = ref(false);
const currentImageField = ref({
  fieldKey: null,
  mediaCategory: "workshop_sliders",
  multiple: true,
  index: null,
});

// Media picker handlers
const handleMediaPickerOpen = (payload) => {
  currentImageField.value = {
    fieldKey: payload.fieldKey,
    mediaCategory: payload.mediaCategory || "workshop_sliders",
    multiple: !!payload.multiple,
    index: payload.index ?? null,
  };
  showMediaPicker.value = true;
};

const handleMediaSelect = (selectedMedia) => {
  const { fieldKey, multiple, index } = currentImageField.value;

  if (!fieldKey) {
    showMediaPicker.value = false;
    return;
  }

  let imageUrls = [];
  if (multiple) {
    const mediaArray = Array.isArray(selectedMedia)
      ? selectedMedia
      : [selectedMedia];
    imageUrls = mediaArray.filter((m) => m?.url).map((m) => m.url);
  } else if (selectedMedia?.url) {
    imageUrls = [selectedMedia.url];
  }

  if (!workshopFormRef.value) {
    showMediaPicker.value = false;
    return;
  }

  // Update form data directly inside the ref
  if (fieldKey === "sliderImages") {
    workshopFormRef.value.formData.sliders.sliderImages = imageUrls;
  } else if (fieldKey === "reverseSliderImages") {
    workshopFormRef.value.formData.sliders.reverseSliderImages = imageUrls;
  } else if (fieldKey === "gallery_slide_robot") {
    const slide = workshopFormRef.value.formData.gallery_slides?.[index];
    if (slide) slide.robot_image = imageUrls[0] || "";
  }

  showMediaPicker.value = false;
  currentImageField.value = {
    fieldKey: null,
    mediaCategory: "workshop_sliders",
    multiple: true,
    index: null,
  };
};

async function handleSave(asDraft = false) {
  if (saving.value) return;
  saveAction.value = asDraft ? "draft" : "publish";
  const activityFormValues = activityFormRef.value?.values;
  const workshopFormValues = workshopFormRef.value?.values;

  if (!activityFormValues) {
    saveAction.value = null;
    alert("Please fill in the Basic Information");
    return;
  }

  const activityValidation = await activityFormRef.value?.validateForm?.();
  if (activityValidation && Object.keys(activityValidation).length > 0) {
    saveAction.value = null;
    return;
  }

  let payload = null;

  try {
    const workshopData = workshopFormValues?.value || workshopFormValues || {};

    // Construct payload with tag and separated text fields included
    payload = {
      title: activityFormValues.title || "",
      slug: activityFormValues.slug || "",
      cw_program_id: activityFormValues.cw_program_id || "",
      status: asDraft ? "draft" : "publish",
      seo_title: seo.value.seo_title || "",
      seo_description: seo.value.seo_description || "",
      is_enabled: !!activityFormValues.is_enabled,
      is_required_for_translation:
        !!activityFormValues.is_required_for_translation,
      activity_icon: activityFormRef.value?.getLogo?.() || "",
      activity_details: {
        tag: activityFormValues.tag || "", // ✅ Added tag here
        activity_name: activityFormValues.activity_name || "",
        activity_heading: activityFormValues.activity_heading || "",
        activity_description: activityFormValues.activity_description || "",
        created_for: activityFormValues.created_for || "",
        ideal_for_text: activityFormValues.ideal_for_text || "",

        age: activityFormValues.age || null,
        age_text: activityFormValues.age_text || "",

        grade: activityFormValues.grade || "",
        grade_text: activityFormValues.grade_text || "",

        duration_heading: activityFormValues.duration_heading || "",
        duration: activityFormValues.duration || "",
        duration_text: activityFormValues.duration_text || "", // ✅ Kept this

        image: activityFormValues.image || "",
        cta_button: activityFormValues.cta_button || { text: "", url: "" },
        workshop_details: workshopData,
        feature_section: aiFeatureFormRef.value?.getValues?.() ?? null,
      },
    };

    await submitActivity(payload);
  } catch (err) {
    const conflict = getSlugConflictPayload(err);
    if (conflict?.code === "slug_restorable") {
      slugConflict.value = conflict;
      pendingPayload.value = payload;
      showSlugConflictDialog.value = true;
      return;
    }
  } finally {
    saveAction.value = null;
  }
}

async function submitActivity(payload, restoreDeleted = false) {
  const body = { ...payload };
  if (restoreDeleted) {
    body.restore_deleted = true;
  }
  await activityStore.createActivity(body);
  router.push("/activity");
}

async function confirmSlugRestore() {
  if (!pendingPayload.value) return;
  saveAction.value = "restore";
  try {
    await submitActivity(pendingPayload.value, true);
  } catch (err) {
    const conflict = getSlugConflictPayload(err);
    if (conflict) {
      slugConflict.value = conflict;
      showSlugConflictDialog.value = true;
    }
  } finally {
    saveAction.value = null;
    pendingPayload.value = null;
    slugConflict.value = null;
  }
}

function handleCancel() {
  router.push("/activity");
}
</script>

<template>
  <div class="activity-page-layout">
    <div class="page-header">
      <div>
        <h1 class="page-title">Add New Activity</h1>
        <p class="page-subtitle">Create a new learning activity and workshop</p>
      </div>
      <VBtn
        variant="text"
        color="primary"
        prepend-icon="bx-arrow-back"
        :disabled="saving"
        @click="handleCancel"
      >
        Back
      </VBtn>
    </div>

    <div class="content-grid">
      <div class="main-content">
        <AccordionExpandToggle :group="activityAccordion" />

        <BasicActivityForm
          ref="activityFormRef"
          :loading="saving"
          mode="create"
          @cancel="handleCancel"
        />

        <div class="spacer"></div>

        <WorkshopDetailsForm
          ref="workshopFormRef"
          :loading="saving"
          mode="create"
          :slug="activityFormRef?.values?.slug || ''"
          @cancel="handleCancel"
          @open-media-picker="handleMediaPickerOpen"
        />

        <AiFeatureForm
          v-if="showAiSection"
          ref="aiFeatureFormRef"
          :loading="saving"
          mode="create"
          record-key="activity_details"
        />

        <VExpansionPanels
          v-model="seoPanel"
          variant="accordion"
          class="custom-accordion-panels seo-panels"
          style="margin-top: 8px"
          elevation="0"
        >
          <AccordionSection
            title="SEO Meta Tags"
            subtitle="Search engine title & description"
            icon="bx-search-alt"
            iconColorClass="icon-teal"
          >
            <SeoFields
              v-model:seo-title="seo.seo_title"
              v-model:seo-description="seo.seo_description"
              :disabled="saving"
            />
          </AccordionSection>
        </VExpansionPanels>
      </div>

      <div class="side-content">
        <div class="sticky-wrapper">
          <div class="sidebar-card">
            <h3 class="sidebar-title">Publish</h3>
            <p class="sidebar-text">Review and save your changes.</p>

            <PublishDraftActions
              :loading="saving"
              :loading-action="saveAction"
              @publish="handleSave(false)"
              @draft="handleSave(true)"
            />
          </div>
        </div>
      </div>
    </div>

    <MediaPickerModal
      v-model="showMediaPicker"
      :multiple="currentImageField.multiple"
      filter-type="image"
      :media-category="currentImageField.mediaCategory"
      @select="handleMediaSelect"
    />

    <SlugConflictDialog
      v-model:visible="showSlugConflictDialog"
      :conflict="slugConflict?.conflict"
      mode="restore_deleted"
      resource-label="activity"
      @confirm="confirmSlugRestore"
    />
  </div>
</template>

<style scoped>
.activity-page-layout {
  padding: 32px;
  max-width: 1300px;
  margin: 0 auto;
}
.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 24px;
}
.page-title {
  font-size: 28px;
  font-weight: 700;
  color: rgb(var(--v-theme-on-surface));
  margin: 0 0 4px 0;
  letter-spacing: -0.5px;
}
.page-subtitle {
  font-size: 15px;
  color: rgb(var(--v-theme-on-surface), 0.7);
  margin: 0;
}
.content-grid {
  display: grid;
  grid-template-columns: 1fr 320px;
  gap: 32px;
}
.main-content {
  display: flex;
  flex-direction: column;
}
.spacer {
  height: 24px;
}
.side-content {
  height: 100%;
}

.sticky-wrapper {
  position: sticky;
  top: 105px;
  z-index: 10;
}
.sidebar-card {
  background: rgb(var(--v-theme-surface));
  border: 1px solid rgba(var(--v-border-color), var(--v-border-opacity));
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 16px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}
.sidebar-title {
  font-size: 16px;
  font-weight: 700;
  color: rgb(var(--v-theme-on-surface));
  margin: 0 0 8px 0;
}
.sidebar-text {
  font-size: 13px;
  color: rgb(var(--v-theme-on-surface), 0.7);
  margin-bottom: 16px;
}
.info-card.sidebar-card {
  background-color: #003b6f !important;
  border-color: #002b55 !important;
  color: #ffffff !important;
  display: flex !important;
  gap: 12px;
}
.info-icon,
.info-icon .v-icon,
.info-icon i {
  color: #ffffff !important;
  margin-top: 2px;
}
.info-content p,
.info-content p * {
  font-size: 12px !important;
  color: #ffffff !important;
  margin: 0 !important;
  line-height: 1.4 !important;
}
@media (max-width: 960px) {
  .content-grid {
    grid-template-columns: 1fr;
  }
  .sticky-wrapper {
    position: static;
  }
  .side-content {
    order: -1;
  }
  .activity-page-layout {
    padding: 16px;
  }
}
</style>
