<template>
  <div class="flex h-dvh flex-col overflow-hidden">
    <TopNavBar :title="t('quick.pageTitle')" />
    <Tabs @change="handleTabChange" />

    <div class="min-h-0 flex-1 overflow-y-auto scrollbar-none [-ms-overflow-style:none] [&::-webkit-scrollbar]:hidden">
      <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
        <div v-if="didSelectedTabItem && didSelectedTabItem.orderType == 0"
          class="bg-white  flex items-center p-[12px]">
          <div class="in flex items-center">
            <span class="text-[11px] font-medium text-ink-400 mr-[4px]">{{ t("quick.date.checkIn") }}</span>
            <span class="text-[14px] font-medium text-[#171717]">
              {{ selectedDate.startDate }}
            </span>
          </div>

          <span
            class="py-[3px] px-[6px] bg-[#E5E8EE]  text-[11px] font-medium text-ink-600 rounded-[5px] ml-[8px] mr-[8px]">
            {{ selectedDate.totalDays }}{{ t("quick.date.nights") }}
          </span>

          <div class="out flex items-center">
            <span class="text-[11px] font-medium text-ink-400 mr-[4px]">{{ t("quick.date.checkOut") }}</span>
            <span class="text-[14px] font-medium text-[#171717]">
              {{ selectedDate.endDate }}
            </span>
          </div>

          <CalendarDays class="ml-auto" color="#0CCD58" @click="handleCalendarClick" />
        </div>

        <van-list v-model:loading="loading" v-model:error="listError" :finished="finished" :immediate-check="false"
          :finished-text="t('common.state.noMore')" :error-text="t('common.errors.loadFailedRetry')" @load="onLoad">
          <Card v-for="(item, index) in dataList" :key="index" :item="item" :selectedDate="selectedDate" />
        </van-list>
      </van-pull-refresh>
    </div>

    <Calender ref="calenderRef" mode="range" :default-value="selectedDate" @close="handleCalendarClose"
      @range-select="handleDateSelect" />
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { useI18n } from "vue-i18n";
import { CalendarDays } from '@lucide/vue';
import TopNavBar from "@/components/TopNavBar/index.vue";
import Calender from "@/components/Calender/index.vue";
import Tabs from "./components/Tabs/index.vue";
import Card from "./components/Card/index.vue";
import { quickBookingList } from "@/api/goods";
import { DateUtils } from "@/utils/dateUtils";
import { useSelectedDateStore } from "@/store";

type SelectedDate = {
  startDate: string;
  endDate: string;
  totalDays: number;
};

type QuickTabItem = {
  typeCode?: string;
  orderType?: number | string;
};

type QuickListItem = Record<string, any>;
type QuickListResponse = {
  records?: QuickListItem[];
  total?: number | string;
};

const PAGE_SIZE = 10;
const { t } = useI18n();
const calenderRef = ref();
const selectedDateStore = useSelectedDateStore();

const getDefaultSelectedDate = (): SelectedDate => ({
  startDate: DateUtils.formatDate(),
  endDate: DateUtils.formatDate(new Date(Date.now() + 24 * 60 * 60 * 1000)),
  totalDays: 1,
});

const normalizeSelectedDate = (data?: Partial<SelectedDate> | null): SelectedDate => {
  if (data?.startDate && data?.endDate && Number(data.totalDays) > 0) {
    return {
      startDate: data.startDate,
      endDate: data.endDate,
      totalDays: Number(data.totalDays),
    };
  }

  return getDefaultSelectedDate();
};

const selectedDate = ref<SelectedDate>(normalizeSelectedDate(selectedDateStore.selectedDate));
selectedDateStore.setData({ ...selectedDate.value });
const dataList = ref<QuickListItem[]>([]);
const currentPage = ref(1);
const loading = ref(false);
const finished = ref(false);
const refreshing = ref(false);
const listError = ref(false);
const didSelectedTabItem = ref<QuickTabItem | null>(null);

const finishLoading = () => {
  loading.value = false;
  refreshing.value = false;
};

const queryList = async (pageNum = currentPage.value, pageSize = PAGE_SIZE) => {
  if (!didSelectedTabItem.value) {
    dataList.value = [];
    finished.value = true;
    listError.value = false;
    finishLoading();
    return;
  }

  try {
    const params: Record<string, any> = {
      commodityTypeCode: didSelectedTabItem.value.typeCode,
      size: pageSize,
      current: pageNum,
    };

    if (didSelectedTabItem.value.orderType == 0) {
      params.checkInDate = selectedDate.value.startDate;
      params.checkOutDate = selectedDate.value.endDate;
    }

    const res = await quickBookingList(params);
    const pageData = res.data as QuickListResponse;
    const records = Array.isArray(pageData.records) ? pageData.records : [];
    const total = Number(pageData.total ?? 0);
    const hasTotal = Number.isFinite(total) && total > 0;

    if (pageNum === 1) {
      dataList.value = records;
    } else {
      dataList.value = [...dataList.value, ...records];
    }

    finished.value =
      records.length < pageSize || (hasTotal && dataList.value.length >= total);
    if (!finished.value) {
      currentPage.value = pageNum + 1;
    }
    listError.value = false;
  } catch (error) {
    console.error("查询列表失败:", error);
    listError.value = true;
  } finally {
    finishLoading();
  }
};

const reloadList = () => {
  currentPage.value = 1;
  finished.value = false;
  listError.value = false;
  loading.value = true;
  queryList(1);
};

const onLoad = () => {
  queryList();
};

const onRefresh = () => {
  currentPage.value = 1;
  finished.value = false;
  listError.value = false;
  loading.value = true;
  queryList(1);
};

const handleTabChange = ({ item }: { item: QuickTabItem }) => {
  didSelectedTabItem.value = item;
  dataList.value = [];
  reloadList();
};

const handleCalendarClose = () => {
  calenderRef.value.close();
};

const handleDateSelect = (data: SelectedDate) => {
  selectedDate.value = normalizeSelectedDate(data);
  selectedDateStore.setData({ ...selectedDate.value });
  calenderRef.value?.close?.();
  dataList.value = [];
  reloadList();
};

const handleCalendarClick = () => {
  calenderRef.value.open();
};
</script>
