<script setup>
import { ref, defineProps, defineEmits, defineExpose } from "vue";
import ApiService from "@/services/ApiService";
import { toast } from "vue3-toastify";

const props = defineProps({
  categoryId: {
    type: String,
    required: true,
  },
  productId: {
    type: Number,
    required: true,
  },
});

const emit = defineEmits(["nextStep","previousStep"])

const loading = ref(false);

const loadingNewAttr = ref(false);

const loadingNewAttrValue = ref(false);

const loadingSaveSpecification = ref(false);

const attributes = ref([]);

const specifications = ref([{ selectedAttributeId: null, selectedValueId: null }]);

const showAddAttribute = ref(false);

const showAddAttributeValue = ref(null);

const newAttributeTitle = ref("");

const newAttributeValueTitle = ref("");

// Fetch attributes
const getAttributes = async () => {
  try {
    loading.value = true;

    const { data: { data, success } } = await ApiService.get(`admin/attributes`, {
      params: {
        category_id: props.categoryId,
        with_global: 1,
      },
    });

    if (success) {
      attributes.value = data?.filter(attribute => attribute?.translation);
    }
  } catch (e) {
    toast.error(e?.response?.data?.message);
  } finally {
    loading.value = false;
  }
};

const addSpecification = () => {
  specifications.value.push({ selectedAttributeId: null, selectedValueId: null });
};

const getAttributeValues = (attributeId) => {
  const attribute = attributes.value.find(attr => attr.id === attributeId);
  return attribute ? attribute.attribute_values.filter(val => val.translation) : [];
};

const removeRow = async (index) => {
  if (!specifications.value[index].id) {
    specifications.value = specifications.value.filter((r,i) => i !== index)
  } else {
    try {
      const { data: { message, success } } = await ApiService.delete(`admin/products/${props.productId}/specifications/${specifications.value[index]?.id}`)

      if (success) {
        toast.success(message);

        specifications.value = specifications.value.filter((r,i) => i !== index)
      }
    } catch (e) {
      toast.error(e?.response?.data?.message);
    }
  }
}

// Create a new attribute
const createAttribute = async () => {
  if (!newAttributeTitle.value.trim()) {
    toast.error("Attribute title is required");
    return;
  }

  try {
    loadingNewAttr.value = true;
    const payload = {
      category_id: props.categoryId,
      title: newAttributeTitle.value
    };
    const { data: { data, success, message } } = await ApiService.post(`admin/attributes`, payload);

    if (success) {
      attributes.value.push(data);
      newAttributeTitle.value = "";
      showAddAttribute.value = false;
      toast.success(message);
    }
  } catch (e) {
    toast.error(e?.response?.data?.message);
    console.log(e)
  } finally {
    loadingNewAttr.value = false;
  }
};

// Create a new attribute value
const createAttributeValue = async (specIndex) => {
  if (!newAttributeValueTitle.value.trim()) {
    toast.error("Attribute value title is required");
    return;
  }

  const spec = specifications.value[specIndex];
  if (!spec.selectedAttributeId) {
    toast.error("Please select an attribute first");
    return;
  }

  try {
    loadingNewAttrValue.value = true;
    const payload = {
      attribute_id: spec.selectedAttributeId,
      title: newAttributeValueTitle.value
    };
    const { data: { data, success, message } } = await ApiService.post(`admin/attribute-values`, payload);

    if (success) {
      const attribute = attributes.value.find(attr => attr.id === spec.selectedAttributeId);
      if (attribute) {
        attribute.attribute_values.push(data);
      }
      newAttributeValueTitle.value = "";
      showAddAttributeValue.value = null;
      toast.success(message);
    }
  } catch (e) {
    toast.error(e?.response?.data?.message);
  } finally {
    loadingNewAttrValue.value = false;
  }
};

// Handle attribute selection
const handleAttributeSelect = (spec) => {
  if (spec.selectedAttributeId === "add") {
    showAddAttribute.value = true;
    spec.selectedAttributeId = null; // Reset to prevent "add" being a valid selection
  } else {
    spec.selectedValueId = null; // Reset value when attribute changes
    showAddAttributeValue.value = null; // Hide any open value input
  }
};

// Handle attribute value selection
const handleAttributeValueSelect = (spec, index) => {
  if (spec.selectedValueId === "add") {
    showAddAttributeValue.value = index;
    spec.selectedValueId = null; // Reset to prevent "add" being a valid selection
  }
};

const submitSpecification = async () => {
  try {
    loadingSaveSpecification.value = true;

    const { data: { message, success } } = await ApiService.post(
        `admin/products/${props.productId}/specifications`, {
      productSpecifications: specifications.value?.map(item => item.selectedValueId).filter(item => item !== null),
    })

    if (success) {
      emit('nextStep')

      toast.success(message)
    }
  } catch (e) {
    toast.error(e?.response?.data?.message);
  } finally {
    loadingSaveSpecification.value = false;
  }
}

// Initialize attributes
getAttributes();

defineExpose({ specifications })
</script>

<template>
  <div>
    <span v-if="loading" class="d-flex justify-content-center w-100">
      <i class="fa fa-spinner fa-spin text-2xl"></i>
    </span>

    <div v-else class="pt-8">
      <!-- Specifications -->
      <div v-for="(spec, i) in specifications" :key="i" class="mb-2 d-flex gap-2 align-items-center">
        <!-- First dropdown: Attributes -->
        <select
            v-model="spec.selectedAttributeId"
            :id="'attr-' + i"
            class="border rounded px-2 py-1 form-select"
            :style="{ minWidth: '200px' }"
            @change="handleAttributeSelect(spec, i)"
        >
          <option value="add">افزودن ویژگی</option>
          <option
              v-for="attr in attributes"
              :key="attr.id"
              :value="attr.id"
          >
            {{ attr.translation?.title }}
          </option>
        </select>

        <!-- Second dropdown: Attribute Values -->
        <select
            v-model="spec.selectedValueId"
            :id="'value-' + i"
            class="border rounded px-2 py-1 form-select"
            :style="{ minWidth: '200px' }"
            :disabled="!spec.selectedAttributeId"
            @change="handleAttributeValueSelect(spec, i)"
        >
          <option value="add">افزودن مقدار ویژگی</option>
          <option
              v-for="value in getAttributeValues(spec.selectedAttributeId)"
              :key="value.id"
              :value="value.id"
          >
            {{ value?.translation?.title }}
          </option>
        </select>

        <button
            @click="removeRow(i)"
            class="btn btn-danger btn-outline rounded btn-sm"
        >
          <i class="ti ti-trash me-1 text-xl"></i>
        </button>
      </div>

      <div class="d-flex justify-content-between">
        <div v-if="showAddAttribute" class="mt-4 d-flex gap-2 align-items-center">
          <input
              v-model="newAttributeTitle"
              type="text"
              class="form-control"
              placeholder="عنوان ویژگی جدید را وارد کنید"
              :style="{ maxWidth: '400px' }"
          />
          <button
              @click="createAttribute"
              class="px-4 py-2 btn btn-success text-white rounded text-nowrap"
              :disabled="loadingNewAttr"
          >
             <span v-if="loadingNewAttr">
               <i class="fa fa-spinner fa-spin text-2xl"></i>
             </span>
             <template v-else>
               ذخیره ویژگی
             </template>
          </button>
          <button
              @click="showAddAttribute = false; newAttributeTitle = ''"
              class="px-4 py-2 btn btn-link rounded"
          >
            انصراف
          </button>
        </div>

        <div v-if="showAddAttributeValue !== null" class="mt-4 d-flex gap-2 align-items-center align-self-start">
          <input
              v-model="newAttributeValueTitle"
              type="text"
              class="form-control"
              placeholder="مقدار ویژگی جدید را وارد کنید"
              :style="{ maxWidth: '400px' }"
          />
          <button
              @click="createAttributeValue(showAddAttributeValue)"
              class="px-4 py-2 btn btn-success rounded text-nowrap"
              :disabled="loadingNewAttrValue"
          >
             <span v-if="loadingNewAttrValue">
               <i class="fa fa-spinner fa-spin text-2xl"></i>
             </span>
             <template v-else>
               ذخیره مقدار ویژگی
             </template>
          </button>
          <button
              @click="showAddAttributeValue = null; newAttributeValueTitle = ''"
              class="px-4 py-2 btn btn-link rounded"
          >
            انصراف
          </button>
        </div>
      </div>

      <button
          @click="addSpecification"
          class="mt-4 px-4 py-2 btn btn-primary text-white rounded"
      >
        <i class="ti ti-plus"></i>
        افزودن مشخصات
      </button>

      <hr class="py-2"/>

      <button
          :disabled="loadingSaveSpecification"
          @click="submitSpecification"
          class="px-4 py-2 btn btn-primary text-white rounded"
      >
         <span v-if="loadingSaveSpecification" class="d-flex justify-content-center w-100">
            <i class="fa fa-spinner fa-spin text-2xl"></i>
         </span>
        <template v-else>
          ذخیره مشخصات
        </template>
      </button>

    </div>
  </div>
</template>