<template>
  <q-page class="schedule-cart-page bg-page q-pb-xl">
    <div class="row items-center q-px-md q-pt-md q-pb-sm bg-white shadow-cart">
      <q-btn
        color="primary"
        dense
        flat
        icon="mdi-chevron-left"
        round @click="router.back()"
      />

      <div class="col text-center font16 fontbold gradient-diarista text-primary">
        {{ $t('schedule_cart.title') }}
      </div>

      <div style="width: 36px"></div>
    </div>

    <div v-if="cart.items.length === 0" class="q-px-md q-pt-md">
      <q-card :flat="false" class="empty-card bg-surface shadow-card card-border">
        <q-card-section class="column items-center text-center q-pa-lg">
          <q-icon
            color="grey-5"
            name="mdi-cart-off"
            size="42px"
          />

          <span class="font14 fontbold text-text q-mt-sm">
            {{ $t('schedule_cart.empty_title') }}
          </span>

          <span class="font12 text-grey-7 q-mt-xs">
            {{ $t('schedule_cart.empty_message') }}
          </span>

          <q-btn
            class="q-mt-md"
            color="primary"
            no-caps
            padding="8px 18px"
            rounded
            unelevated
            :label="$t('schedule_cart.view_favorites')"
            @click="router.push({ name: 'ProfilePage' })"
          />
        </q-card-section>
      </q-card>

      <q-card v-if="cart.lastCreatedGroup" :flat="false" class="created-card bg-surface shadow-card card-border q-mt-md">
        <q-card-section class="q-pa-md">
          <div class="row items-center no-wrap">
            <q-icon
              color="positive"
              name="mdi-check-circle-outline"
              size="24px"
            />

            <div class="column q-ml-sm">
              <span class="font14 fontbold text-text">
                {{ $t('schedule_cart.last_request_title') }}
              </span>

              <span class="font12 text-grey-7">
                {{ $t('schedule_cart.created_count', { count: cart.lastCreatedGroup.schedule_ids.length }) }}
              </span>
            </div>
          </div>
        </q-card-section>
      </q-card>
    </div>

    <template v-else>
      <div class="q-px-md q-pt-md column q-gutter-y-sm">
        <div class="cart-discount-banner row items-center no-wrap q-pa-sm">
          <q-icon
            color="positive"
            name="mdi-sale-outline"
            size="20px"
          />

          <span class="font12 fontbold text-positive q-ml-sm">
            {{ cartDiscountMessage }}
          </span>
        </div>

        <q-card
          v-for="(item, index) in cart.items"
          :key="item.local_id"
          :flat="false"
          class="cart-item-card bg-surface shadow-card card-border"
        >
          <q-card-section class="row no-wrap q-pa-md">
            <q-avatar color="indigo-1" size="44px" text-color="indigo-4">
              <span>
                {{ getProviderInitial(item) }}
              </span>
            </q-avatar>

            <div class="column col q-ml-sm">
              <span class="font14 fontbold text-text">
                {{ item.provider_name }}
              </span>

              <span class="font12 text-grey-7">
                {{ formatCartDate(item.date) }}
              </span>

              <span class="font12 text-grey-7">
                {{ $t('schedule_cart.time_range', { start: item.start_time, end: item.end_time }) }}
              </span>

              <div class="row items-center q-gutter-x-sm q-mt-xs">
                <q-chip
                  class="font10"
                  color="purple-1"
                  dense
                  square
                  text-color="primary"
                >
                  {{ $t('schedule_cart.hours_short', { hours: item.period_type }) }}
                </q-chip>

                <q-chip class="font10" color="grey-2" dense square text-color="grey-8">
                  {{ item.offers_meal ? $t('schedule_cart.with_meal') : $t('schedule_cart.without_meal') }}
                </q-chip>
              </div>

              <div class="item-prices q-mt-sm">
                <div v-if="!hasCartDiscount" class="row items-center no-wrap">
                  <span class="font11 fontbold text-primary">{{ $t('schedule_cart.pix_total') }}</span>

                  <q-space />

                  <span class="font12 fontbold text-primary">
                    {{ formatCurrencyValue(getStandardPixItemTotal(item)) }}
                  </span>
                </div>

                <div v-if="!hasCartDiscount" class="row items-center no-wrap q-mt-xs">
                  <span class="font11 text-grey-7">
                    {{ $t('schedule_cart.credit_card_total') }}
                  </span>

                  <q-space />

                  <span class="font12 fontbold text-text">
                    {{ formatCurrencyValue(getCreditCardItemTotal(item)) }}
                  </span>
                </div>

                <div v-if="hasCartDiscount" class="row items-center no-wrap q-mt-xs">
                  <span class="font11 fontbold text-positive">
                    {{ $t('schedule_cart.cart_discount_total') }}
                  </span>

                  <q-space />

                  <span class="font12 fontbold text-positive">
                    {{ formatCurrencyValue(getCartDiscountItemTotal(item)) }}
                  </span>
                </div>
              </div>
            </div>

            <q-btn
              color="negative"
              dense
              flat
              icon="mdi-delete-outline"
              round
              @click="cart.removeItem(index)"
            />
          </q-card-section>
        </q-card>
      </div>

      <div class="q-px-md q-pt-md">
        <q-card :flat="false" class="checkout-card bg-surface shadow-card card-border">
          <q-card-section class="q-pa-md">
            <div class="row items-center no-wrap q-mb-sm">
              <span class="font14 fontbold text-primary">
                {{ $t('schedule_cart.summary') }}
              </span>

              <q-space />
            </div>

            <div class="summary-row row items-center no-wrap q-py-xs">
              <span class="font12 text-grey-7">
                {{ $t('schedule_cart.provider') }}
              </span>

              <q-space />

              <span class="font12 fontbold text-text text-right">
                {{ providerName }}
              </span>
            </div>

            <div class="summary-row row items-center no-wrap q-py-xs">
              <span class="font12 text-grey-7">
                {{ $t('schedule_cart.address') }}
              </span>

              <q-space />

              <span class="font12 fontbold text-text text-right">
                {{ primaryAddressLabel }}
              </span>
            </div>

            <div class="summary-row row items-center no-wrap q-py-xs">
              <span class="font12 text-grey-7">
                {{ $t('schedule_cart.quantity') }}
              </span>

              <q-space />

              <span class="font12 fontbold text-text">
                {{ $t('schedule_cart.schedule_count', { count: cart.items.length }) }}
              </span>
            </div>

            <div v-if="!hasCartDiscount" class="summary-row row items-center no-wrap q-py-xs">
              <span class="font12 fontbold text-primary">
                {{ $t('schedule_cart.pix_total') }}
              </span>

              <q-space />

              <span class="font14 fontbold text-primary">
                {{ formatCurrencyValue(pixTotalAmount) }}
              </span>
            </div>

            <div v-if="hasCartDiscount" class="summary-row row items-center no-wrap q-py-xs">
              <span class="font12 fontbold text-positive">
                {{ $t('schedule_cart.cart_discount_total') }}
              </span>

              <q-space />

              <span class="font14 fontbold text-positive">
                {{ formatCurrencyValue(cartDiscountTotalAmount) }}
              </span>
            </div>

            <div v-if="pixDiscountAmount > 0" class="summary-discount row items-center no-wrap q-py-xs q-px-sm q-mt-sm">
              <q-icon color="positive" name="mdi-tag-outline" size="18px" />

              <span class="font12 fontbold text-positive q-ml-xs">
                {{ $t('schedule_cart.cart_fee_discount', { value: formatPrice(pixDiscountAmount) }) }}
              </span>
            </div>
          </q-card-section>

          <q-card-actions class="q-px-md q-pb-md">
            <q-btn
              class="full-width"
              color="primary"
              no-caps
              padding="10px 16px"
              rounded
              unelevated
              :disable="addressLoading || !platformFeesReady"
              :label="$t('schedule_cart.close_cart')"
              :loading="submitting"
              @click="submitCart"
            />
          </q-card-actions>
        </q-card>
      </div>
    </template>
  </q-page>
</template>

<script setup>
import { computed, onMounted, ref } from "vue";
import { useRouter } from "vue-router";
import { useI18n } from "vue-i18n";
import { useQuasar } from "quasar";
import { getAddresses } from "src/api/address";
import { createScheduleCart } from "src/api/cart";
import { usePaymentPlatformFees } from "src/composables/usePaymentPlatformFees";
import { useScheduleCartStore } from "src/stores/scheduleCart";
import { userStore } from "src/stores/user";

const router = useRouter();
const $q     = useQuasar();
const { t }  = useI18n();

const cart  = useScheduleCartStore();
const store = userStore();

const { platformFees, loadPlatformFees } = usePaymentPlatformFees();

const primaryAddress = ref(null);
const addressLoading = ref(false);
const submitting     = ref(false);

const cartDiscountMessage = computed(() => {
  if (hasCartDiscount.value) {
    return t("schedule_cart.cart_discount_applied");
  }

  return t("schedule_cart.cart_discount_hint", { count: missingSchedulesForDiscount.value });
});

const cartDiscountTotalAmount = computed(() => roundNullableMoney(sumCartItems(getCartDiscountItemTotal)));

const hasCartDiscount = computed(() => cart.items.length >= 3);

const missingSchedulesForDiscount = computed(() => Math.max(3 - cart.items.length, 0));

const platformFeesReady = computed(() =>
  isValidFee(platformFees.value.pix)         &&
  isValidFee(platformFees.value.credit_card) &&
  (!hasCartDiscount.value || isValidFee(platformFees.value.cart_min_3_schedules))
);

const pixDiscountAmount = computed(() => {
  if (!hasCartDiscount.value) return 0;

  return roundNullableMoney(sumCartItems((item) => {
    const standardPixItemTotal   = getStandardPixItemTotal(item);
    const discountedPixItemTotal = getCartDiscountItemTotal(item);

    if (standardPixItemTotal === null || discountedPixItemTotal === null) return null;

    return standardPixItemTotal - discountedPixItemTotal;
  })) ?? 0;
});

const pixTotalAmount = computed(() => roundNullableMoney(sumCartItems(getStandardPixItemTotal)));

const primaryAddressLabel = computed(() => {
  if (addressLoading.value)  return t("schedule_cart.loading");
  if (!primaryAddress.value) return t("schedule_cart.no_primary_address");

  return [
    primaryAddress.value.address,
    primaryAddress.value.number,
    primaryAddress.value.district,
  ].filter(Boolean).join(", ");
});

const providerName = computed(() => {
  const providerNames = [...new Set(cart.items.map((item) => item.provider_name).filter(Boolean))];

  if (providerNames.length === 0) return t("schedule_cart.unknown");
  if (providerNames.length === 1) return providerNames[0];

  return t("schedule_cart.multiple_providers", { count: providerNames.length });
});

const formatCartDate = (value) => {
  const parsed = new Date(`${normalizeDate(value)}T12:00:00`);

  return new Intl.DateTimeFormat("pt-BR", { day: "2-digit", month: "2-digit", year: "numeric" }).format(parsed);
};

const formatCurrencyValue = (value) => {
  if (value === null || value === undefined || !Number.isFinite(Number(value))) {
    return t("schedule_cart.loading");
  }

  return t("schedule_cart.currency_value", { value: formatPrice(value) });
};

const formatPrice = (value) => {
  if (value === null || value === undefined || !Number.isFinite(Number(value))) {
    return t("schedule_cart.loading");
  }

  return Number(value ?? 0).toLocaleString("pt-BR", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
};

const getCartDiscountItemTotal = (item) => getTotalWithFee(item, platformFees.value.cart_min_3_schedules);

const getCreditCardItemTotal = (item) => getTotalWithFee(item, platformFees.value.credit_card);

const getProviderInitial = (item) => item.provider_name?.slice(0, 1).toUpperCase() ?? t("schedule_cart.provider_initial");

const getStandardPixItemTotal = (item) => getTotalWithFee(item, platformFees.value.pix);

const getTotalWithFee = (item, fee) => {
  if (!isValidFee(fee)) return null;

  return roundMoney(Number(item.total_amount ?? 0) * (1 + Number(fee)));
};

const isValidFee = (fee) => fee !== null && fee !== undefined && Number.isFinite(Number(fee));

const loadPrimaryAddress = async () => {
  const clientId = store.user?.client_id ?? store.user?.client?.id;

  if (!clientId) return;

  addressLoading.value = true;

  try {
    const addresses = await getAddresses("client", clientId);

    primaryAddress.value = (addresses ?? []).find((address) => address.is_primary) ?? null;
  } catch {
    primaryAddress.value = null;
  } finally {
    addressLoading.value = false;
  }
};

const normalizeDate = (value) => String(value ?? "").replace(/\//g, "-").slice(0, 10);

const roundMoney = (value) => Number(Number(value ?? 0).toFixed(2));

const roundNullableMoney = (value) => {
  if (value === null || value === undefined || !Number.isFinite(Number(value))) return null;

  return roundMoney(value);
};

const submitCart = async () => {
  if (!cart.items.length || submitting.value) return;

  if (!primaryAddress.value) {
    $q.notify({ type: "warning", message: t("schedule_cart.no_primary_address_notify") });

    return;
  }

  const payload = {
    client_id:     store.user.client_id ?? store.user?.client?.id,
    address_id:    primaryAddress.value.id,
    schedule_type: "default",

    schedules: cart.items.map((item) => ({
      provider_id:  item.provider_id,
      date:         item.date,
      period_type:  item.period_type,
      start_time:   item.start_time,
      end_time:     item.end_time,
      total_amount: item.total_amount,
      offers_meal:  item.offers_meal,
    })),
  };

  submitting.value = true;

  try {
    const createdCart = await createScheduleCart(payload);

    const createdSchedules = createdCart?.schedules ?? [];

    const scheduleIds = createdCart?.schedule_ids ?? createdSchedules.map((schedule) => schedule.id);

    cart.setLastCreatedGroup({
      local_group_id: createdCart?.id ?? `cart-${Date.now()}`,
      cart_id:        createdCart?.id ?? null,
      schedule_ids:   scheduleIds,
      schedules:      createdSchedules,
    });

    cart.clear();

    $q.notify({ type: "positive", message: t("schedule_cart.cart_closed_success") });
  } catch (error) {
    const message = error?.response?.data?.message ?? error?.message ?? t("schedule_cart.submit_error");

    $q.notify({ type: "negative", message });
  } finally {
    submitting.value = false;
  }
};

const sumCartItems = (callback) => {
  let total = 0;

  for (const item of cart.items) {
    const itemTotal = callback(item);

    if (itemTotal === null) return null;

    total += itemTotal;
  }

  return total;
};

onMounted(() => {
  loadPrimaryAddress();
  loadPlatformFees().catch(() => {});
});
</script>

<style scoped lang="scss">
.schedule-cart-page {
  min-height: 100%;
}

.shadow-cart {
  box-shadow: 0 1px 8px rgba(0, 0, 0, 0.1);
}

.cart-item-card,
.checkout-card,
.empty-card,
.created-card {
  border-radius: 8px;
}

.summary-row {
  border-top: 1px solid rgba(0, 0, 0, 0.05);
}

.item-prices {
  max-width: 220px;
}

.cart-discount-banner {
  background: rgba(34, 197, 94, 0.1);
  border: 1px solid rgba(34, 197, 94, 0.22);
  border-radius: 8px;
}

.summary-discount {
  background: rgba(34, 197, 94, 0.12);
  border-radius: 8px;
}
</style>
