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

const props = defineProps({
  visible: Boolean,
  activity: Object,
  mode: { type: String, default: "create" },
  loading: Boolean,
});
const emit = defineEmits(["update:visible", "save", "cancel"]);

const showMediaPicker = ref(false);
const selectedImageData = ref(null);
const formData = ref({
  title: "",
  desctiprtion: "",
  image: "",
  status: "draft",
  cta_button_text: "",
  cta_button_url: "",
});

const formFields = [
  { name: "title", label: "Activity Title", type: "text", required: true },
  {
    name: "desctiprtion",
    label: "Description",
    type: "textarea",
    required: true,
  },
  {
    name: "cta_button_text",
    label: "CTA Button Text",
    type: "text",
    required: true,
  },
  {
    name: "cta_button_url",
    label: "CTA Button URL",
    type: "text",
    required: true,
  },
  {
    name: "status",
    label: "Status",
    type: "select",
    required: true,
    options: [
      { title: "Publish", value: "publish" },
      { title: "Draft", value: "draft" },
    ],
  },
];

const validationSchema = yup.object({
  title: yup.string().required("Activity title required").min(2).max(255),
  desctiprtion: yup.string().required("Description required").min(10).max(1000),
  status: yup
    .string()
    .required("Status required")
    .oneOf(["draft", "publish"]),
  cta_button_text: yup
    .string()
    .required("CTA button text required")
    .min(1)
    .max(100),
  cta_button_url: yup
    .string()
    .required("CTA button URL required")
    .url("Must be a valid URL"),
  image: yup
    .string()
    .required("Activity image is required")
    .test("is-url", "Must be a valid image URL", (value) => {
      if (!value) return false;
      try {
        new URL(value);
        return true;
      } catch {
        return false;
      }
    }),
});

const dialogTitle = computed(() =>
  props.mode === "create" ? "Add Activity" : "Edit Activity",
);
const submitButtonLabel = computed(() =>
  props.mode === "create" ? "Add Activity" : "Update Activity",
);

watch(
  () => props.activity,
  (activity) => {
    if (activity && props.mode === "edit") {
      formData.value = {
        title: activity.title || "",
        desctiprtion: activity.desctiprtion || "",
        image: activity.image || "",
        status: activity.status || "draft",
        cta_button_text: activity.cta_button?.text || "",
        cta_button_url: activity.cta_button?.url || "",
      };
      selectedImageData.value = activity.image ? { url: activity.image } : null;
    }
  },
  { immediate: true },
);

watch(
  () => props.visible,
  (newVisible) => {
    if (newVisible && props.mode === "create") {
      resetForm();
    }
  },
);

function resetForm() {
  formData.value = {
    title: "",
    desctiprtion: "",
    image: "",
    status: "draft",
    cta_button_text: "",
    cta_button_url: "",
  };
  selectedImageData.value = null;
}

const openMediaPicker = () => {
  if (!props.loading) showMediaPicker.value = true;
};
const handleMediaSelect = (media) => {
  if (media?.url) {
    formData.value.image = media.url;
    selectedImageData.value = media;
  }
  showMediaPicker.value = false;
};
const handleSubmit = (data) => {
  // Validate image is selected
  const imageUrl = selectedImageData.value?.url || props.activity?.image;
  if (!imageUrl) {
    alert("Please select an image for the activity");
    return;
  }

  emit("save", {
    title: data.title,
    desctiprtion: data.desctiprtion,
    status: data.status,
    image: imageUrl,
    cta_button: {
      text: data.cta_button_text,
      url: data.cta_button_url,
    },
  });
};
const handleCancel = () => emit("cancel");
</script>

<template>
  <ReusableModal
    :visible="props.visible"
    :title="dialogTitle"
    :fields="formFields"
    :model-value="formData"
    :validation-schema="validationSchema"
    :loading="props.loading"
    :submit-label="submitButtonLabel"
    @update:visible="(value) => emit('update:visible', value)"
    @update:model-value="(value) => (formData = value)"
    @submit="handleSubmit"
    @cancel="handleCancel"
  >
    <template #custom-content>
      <div style="text-align: center; margin-bottom: 1.5rem">
        <label
          class="field-label"
          style="display: block; margin-bottom: 0.75rem"
        >
          Activity Image
          <span style="color: #ef4444">*</span>
        </label>
        <div
          class="img-selector"
          :class="{ 'has-image': selectedImageData?.url || formData.image }"
          @click="openMediaPicker"
        >
          <img
            :src="
              selectedImageData?.url ||
              formData.image ||
              'https://yefranchisees.b-cdn.net/media/super_admin/activity-placeholder.jpg'
            "
            alt="Activity"
            style="width: 100%; height: 100%; object-fit: cover"
          />
          <div class="img-edit-overlay">
            <i class="pi pi-pencil" style="margin-right: 0.25rem"></i>
            <span>{{
              selectedImageData?.url || formData.image ? "Change" : "Select"
            }}</span>
          </div>
          <div
            v-if="!selectedImageData?.url && !formData.image"
            class="img-placeholder-text"
          >
            <i
              class="pi pi-image"
              style="font-size: 2rem; margin-bottom: 0.5rem"
            ></i>
            <p>Click to select an image</p>
          </div>
        </div>
        <small style="color: #9ca3b8; display: block; margin-top: 0.5rem">
          JPG, PNG, or GIF (Max 5MB)
        </small>
      </div>
    </template>
  </ReusableModal>
  <MediaPickerModal
    v-model="showMediaPicker"
    :multiple="false"
    filter-type="image"
    media-category="activity"
    @select="handleMediaSelect"
  />
</template>

<style scoped>
.field-label {
  font-weight: 500 !important;
  color: rgba(0, 0, 0, 0.87) !important;
}

.img-selector {
  position: relative;
  width: 160px;
  height: 160px;
  border-radius: 12px;
  border: 3px dashed #003b6f;
  margin: 0 auto;
  overflow: hidden;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f8fafc;
  transition: all 0.3s ease;
}

.img-selector:hover {
  border-color: #002147;
  background: #f1f5f9;
  box-shadow: 0 4px 12px rgba(0, 59, 111, 0.1);
}

.img-selector.has-image {
  border: 2px solid #e2e8f0;
  background: #fff;
}

.img-placeholder-text {
  position: absolute;
  text-align: center;
  color: #64748b;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  background: rgba(248, 250, 252, 0.8);
}

.img-placeholder-text p {
  margin: 0.5rem 0 0 0;
  font-size: 0.9rem;
  font-weight: 500;
}

.img-edit-overlay {
  position: absolute;
  bottom: 8px;
  right: 8px;
  background: linear-gradient(135deg, #003b6f 0%, #004d8f 100%);
  color: #fff;
  padding: 6px 12px;
  border-radius: 8px;
  font-size: 0.85rem;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 0.5rem;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.img-selector:hover .img-edit-overlay {
  opacity: 1;
}

.img-selector.has-image .img-edit-overlay {
  opacity: 1;
}

.img-selector.has-image:hover .img-edit-overlay {
  background: linear-gradient(135deg, #002147 0%, #003366 100%);
}
</style>
