<script setup>
import { useSettingStore } from "@/stores/settingStore";
import { storeToRefs } from "pinia";
import { useToast } from "primevue/usetoast";
import { useField, useForm } from "vee-validate";
import { watch, ref } from "vue";
import * as yup from "yup";

const settingStore = useSettingStore();
const { setting } = storeToRefs(settingStore);
const toast = useToast();

// ✅ Add loading state
const isSubmitting = ref(false);

// ✅ Validation schema (not required, but must be valid if present)
const schema = yup.object({
  containerId: yup
    .string()
    .nullable()
    .matches(/^GTM-[A-Z0-9]+$/, "Invalid GTM Container ID (e.g. GTM-XXXXXX)")
    .transform((val) => (val === "" ? null : val)),
  customCode: yup.string().nullable(),
  enableTracking: yup.boolean().required(),
});

// ✅ Vee-validate form
const { handleSubmit, setValues, resetForm, errors } = useForm({
  validationSchema: schema,
});

const { value: containerId } = useField("containerId");
const { value: customCode } = useField("customCode");
const { value: enableTracking } = useField("enableTracking");

// ✅ Prefill values from store
watch(
  setting,
  (val) => {
    if (val?.google_tag_manager) {
      setValues({
        containerId: val.google_tag_manager.container_id || "",
        customCode: val.google_tag_manager.custom_code || "",
        enableTracking: val.google_tag_manager.enable_tracking || false,
      });
    }
  },
  { immediate: true },
);

// ✅ Save handler
const saveGoogleTagSettings = handleSubmit(async (values) => {
  isSubmitting.value = true;
  try {
    const payload = {
      gtm: {
        container_id: values.containerId,
        custom_code: values.customCode,
        enable_tracking: values.enableTracking,
      },
    };

    const response = await settingStore.saveSettings(payload);
  } catch (error) {
    console.error("Save settings error:", error);
  } finally {
    isSubmitting.value = false;
  }
});

// ✅ Reset form
const resetGTMForm = () => {
  resetForm({
    values: {
      containerId: "",
      customCode: "",
      enableTracking: false,
    },
  });
};
</script>

<template>
  <VCard title="Google Tag Manager">
    <VCardText>
      <VForm @submit.prevent="saveGoogleTagSettings">
        <VRow>
          <!-- GTM Container ID -->
          <VCol cols="12" md="6">
            <VTextField
              v-model="containerId"
              label="GTM Container ID"
              placeholder="GTM-XXXXXXX"
              hint="Enter your Google Tag Manager Container ID"
              persistent-hint
              prepend-inner-icon="bx-code-alt"
              :error-messages="errors.containerId"
            />
          </VCol>

          <!-- Custom GTM Code -->
          <VCol cols="12">
            <VTextarea
              v-model="customCode"
              label="Custom GTM Code"
              placeholder="<!-- Custom GTM code here -->"
              rows="6"
              hint="Optional: Add custom GTM tracking code"
              persistent-hint
              :error-messages="errors.customCode"
            />
          </VCol>

          <!-- Tracking Toggle -->
          <VCol cols="12" md="6">
            <VSwitch
              v-model="enableTracking"
              label="Enable GTM Tracking"
              color="primary"
              inset
            />
          </VCol>

          <!-- Action Buttons -->
          <VCol cols="12">
            <div class="d-flex flex-wrap gap-4">
              <VBtn
                type="submit"
                color="primary"
                :loading="isSubmitting"
                :disabled="isSubmitting"
              >
                <VIcon icon="bx-save" class="me-2" />
                Save GTM Settings
              </VBtn>

              <VBtn
                color="secondary"
                variant="tonal"
                @click="resetGTMForm"
                :disabled="isSubmitting"
              >
                <VIcon icon="bx-refresh" class="me-2" />
                Reset
              </VBtn>
            </div>
          </VCol>
        </VRow>
      </VForm>
    </VCardText>

    <!-- ✅ GTM Preview -->
    <VDivider />
    <VCardText v-if="containerId">
      <h6 class="text-h6 mb-4">GTM Configuration</h6>
      <div class="gtm-preview pa-4 border rounded">
        <div class="d-flex align-center justify-space-between">
          <div class="d-flex align-center">
            <VIcon icon="bx-code-alt" color="primary" class="me-2" />
            <div>
              <span class="text-body-1 font-weight-medium"
                >Container ID: {{ containerId }}</span
              >
              <br />
              <span class="text-body-2 text-medium-emphasis">
                Status: {{ enableTracking ? "Active" : "Inactive" }}
              </span>
            </div>
          </div>
          <VChip
            :color="enableTracking ? 'success' : 'warning'"
            size="small"
            label
          >
            {{ enableTracking ? "Tracking Enabled" : "Tracking Disabled" }}
          </VChip>
        </div>

        <div v-if="customCode" class="mt-3">
          <h6 class="text-subtitle-2">Custom Code:</h6>
          <pre class="pa-2 bg-grey-lighten-4 rounded">{{ customCode }}</pre>
        </div>
      </div>
    </VCardText>
  </VCard>
</template>

<style scoped>
.gtm-preview {
  background-color: rgb(var(--v-theme-surface));
  min-height: 80px;
  display: flex;
  flex-direction: column;
}
.v-text-field .v-input__details {
    padding-inline: 0!important;
}
</style>
