<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 entered)
const schema = yup.object({
  siteKey: yup
    .string()
    .nullable()
    .matches(/^6[0-9A-Za-z-_]+$/, "Invalid reCAPTCHA Site Key")
    .transform((val) => (val === "" ? null : val)),
  secretKey: yup
    .string()
    .nullable()
    .matches(/^6[0-9A-Za-z-_]+$/, "Invalid reCAPTCHA Secret Key")
    .transform((val) => (val === "" ? null : val)),
  version: yup.string().oneOf(["v2", "v3"]).default("v2"),
  theme: yup.string().oneOf(["light", "dark"]).default("light"),
  size: yup.string().oneOf(["normal", "compact"]).default("normal"),
  enableProtection: yup.boolean().required(),
});

// ✅ Form setup
const { handleSubmit, setValues, resetForm } = useForm({
  validationSchema: schema,
});

const { value: siteKey } = useField("siteKey");
const { value: secretKey } = useField("secretKey");
const { value: version } = useField("version");
const { value: theme } = useField("theme");
const { value: size } = useField("size");
const { value: enableProtection } = useField("enableProtection");

const captchaVersions = ["v2", "v3"];
const captchaThemes = ["light", "dark"];
const captchaSizes = ["compact", "normal"];

// ✅ Prefill values from DB
watch(
  setting,
  (val) => {
    if (val?.google_recaptcha) {
      setValues({
        siteKey: val.google_recaptcha.site_key || "",
        secretKey: val.google_recaptcha.secret_key || "",
        version: val.google_recaptcha.version || "v2",
        theme: val.google_recaptcha.theme || "light",
        size: val.google_recaptcha.size || "normal",
        enableProtection: val.google_recaptcha.enable_protection || false,
      });
    } else {
      setValues({
        siteKey: "",
        secretKey: "",
        version: "v2",
        theme: "light",
        size: "normal",
        enableProtection: false,
      });
    }
  },
  { immediate: true },
);

// ✅ Save reCAPTCHA settings
const saveCaptchaSettings = handleSubmit(async (values) => {
  isSubmitting.value = true;
  try {
    const payload = {
      recaptcha: {
        site_key: values.siteKey,
        secret_key: values.secretKey,
        version: values.version,
        theme: values.theme,
        size: values.size,
        enable_protection: values.enableProtection,
      },
    };

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

// ✅ Reset form
const resetCaptchaForm = () => {
  resetForm({
    values: {
      siteKey: "",
      secretKey: "",
      version: "v2",
      theme: "light",
      size: "normal",
      enableProtection: false,
    },
  });
};

// ✅ Test configuration
const testCaptcha = () => {
  toast.add({
    severity: "info",
    summary: "Testing...",
    detail: "Testing reCAPTCHA configuration...",
    life: 3000,
  });
};
</script>

<template>
  <VCard title="Google reCAPTCHA">
    <VCardText>
      <VForm @submit.prevent="saveCaptchaSettings">
        <VRow>
          <VCol cols="12" md="6">
            <VTextField
              v-model="siteKey"
              label="reCAPTCHA Site Key"
              placeholder="6Lc..."
              hint="Public key for client-side integration"
              persistent-hint
              prepend-inner-icon="bx-key"
            />
          </VCol>

          <VCol cols="12" md="6">
            <VTextField
              v-model="secretKey"
              label="reCAPTCHA Secret Key"
              placeholder="6Lc..."
              type="password"
              hint="Private key for server-side validation"
              persistent-hint
              prepend-inner-icon="bx-lock"
            />
          </VCol>

          <VCol cols="12" md="4" class="cap-row">
            <VSelect
              v-model="version"
              label="reCAPTCHA Version"
              :items="captchaVersions"
              prepend-inner-icon="bx-shield"
            />
          </VCol>

          <VCol cols="12" md="4" class="cap-row">
            <VSelect
              v-model="theme"
              label="Theme"
              :items="captchaThemes"
              prepend-inner-icon="bx-palette"
            />
          </VCol>

          <VCol cols="12" md="4" class="cap-row">
            <VSelect
              v-model="size"
              label="Size"
              :items="captchaSizes"
              prepend-inner-icon="bx-resize"
            />
          </VCol>

          <VCol cols="12">
            <VSwitch
              v-model="enableProtection"
              label="Enable reCAPTCHA Protection"
              color="primary"
              inset
            />
          </VCol>

          <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 reCAPTCHA Settings
              </VBtn>

              <VBtn
                color="primary"
                variant="outlined"
                @click="testCaptcha"
                :disabled="isSubmitting"
              >
                <VIcon icon="bx-test-tube" class="me-2" /> Test Configuration
              </VBtn>

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

    <!-- Preview -->
    <VDivider />
    <VCardText class="pt-6">
      <h6 class="text-h6 mb-4">Preview</h6>
      <div class="recaptcha-preview pa-4 border rounded">
        <div class="d-flex align-center">
          <VIcon icon="bx-shield-check" color="primary" class="me-2" />
          <span class="text-body-1"
            >reCAPTCHA will appear here when configured</span
          >
        </div>
      </div>
    </VCardText>
  </VCard>
</template>

<style scoped>
.recaptcha-preview {
  background-color: rgb(var(--v-theme-surface));
  min-height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
}
.cap-row {
    padding-top: 20px;
}
</style>
