<script setup lang="ts">
import type { DateValue } from "@internationalized/date";
import {
  CalendarDate,
  fromDate,
  getLocalTimeZone,
} from "@internationalized/date";
import { Calendar } from "@/components/ui/calendar";
import { Separator } from "@/components/ui/separator";
import { toast } from "vue-sonner";
import { useUtmPayload } from "~/composables/useUtmPayload";
import { useApi } from "~/composables/useApi";
import { computed } from "vue";

const props = defineProps<{
  next: () => void;
  prev: () => void;
  isNextDisabled: boolean;
  isPrevDisabled: boolean;
}>();

const date = ref(undefined) as Ref<DateValue | undefined>;
const selectedTime = ref("");
const loading = ref(false);
const availableDates = ref<string[]>([]);
const availableTimes = ref<{ id: string; label: string }[]>([]);
const loadingTimeSlots = ref(false);
const { get, post } = useApi();
const { locale } = useI18n();

const calendarLocale = computed(() => locale.value);
const calendarDir = computed(() => (locale.value === "ar" ? "rtl" : "ltr"));

const isStartButtonDisabled = computed(() => {
  return loading.value || !date.value || !selectedTime.value;
});

onMounted(async () => {
  try {
    const res = (await get("get_available_date")) as any;
    if (res.data?.success) {
      availableDates.value = res.data.data.available_dates;
      if (availableDates.value.length > 0) {
        const firstDate = availableDates.value[0];
        const [year, month, day] = firstDate.split("-").map(Number);
        date.value = new CalendarDate(year, month, day);
      }
    }
  } catch (error) {
    console.error("Failed to fetch available dates", error);
    toast.error("Failed to load available dates");
  }
});

watch(date, async (newDate) => {
  if (newDate) {
    selectedTime.value = "";
    availableTimes.value = [];
    loadingTimeSlots.value = true;
    try {
      const formattedDate = newDate.toString();
      const res = (await post("get-time-slots", {
        day_date: formattedDate,
      })) as any;
      if (res.data?.success) {
        const slots = res.data.data.time_slots || {};
        availableTimes.value = Object.entries(slots).map(([key, value]) => ({
          id: key,
          label: value as string,
        }));
      }
    } catch (error) {
      console.error("Failed to fetch time slots", error);
      toast.error("Failed to load time slots");
    } finally {
      loadingTimeSlots.value = false;
    }
  }
});

function isDateUnavailable(dateToCheck: DateValue) {
  const d = dateToCheck.toString();
  return !availableDates.value.includes(d);
}

async function handleSubmit() {
  if (!date.value || !selectedTime.value) {
    toast.error("Please select both date and time.");
    return;
  }

  const { getUTMPayload } = useUtmPayload();
  const utm = getUTMPayload();
  const formState = useState("campaign-form");

  try {
    loading.value = true;
    const formattedDate = date.value.toString();
    const payload = {
      order_id: (formState.value as any)?.order_id,
      meeting_date: formattedDate,
      meeting_time: selectedTime.value,
      utm: utm,
    };

     await post("contact_us_stepper?step=7", payload);
    navigateTo("/thank-you-v2");
  } catch (err) {
    console.error(err);
    toast.error("Error submitting form");
  } finally {
    loading.value = false;
  }
}
</script>

<template>
  <div>
    <h2 class="mb-2"> {{ $t("stepper.step7.desc") }}</h2>
    <div
      class="flex w-full flex-col items-start gap-2 lg:flex-row lg:items-center"
    >
      <!-- Calendar -->
      <div class="w-full lg:w-2/3">
        <Calendar
          v-model="date"
          class="rounded-md border shadow-sm **:data-[slot=calendar-cell-trigger]:size-10! **:data-[slot=calendar-grid-row]:justify-around!"
          :min-value="
            new CalendarDate(
              new Date().getFullYear(),
              new Date().getMonth(),
              new Date().getDate(),
            )
          "
          :max-value="new CalendarDate(2035, 1, 1)"
          :locale="calendarLocale"
          :dir="calendarDir"
          :is-date-unavailable="isDateUnavailable"
        />
      </div>

    <!-- Separator -->
  <div class="hidden lg:flex">
    <Separator 
      orientation="vertical" 
      class="bg-gray-800 h-[300px] w-[1px]"
    />
  </div>

  <!-- Horizontal separator for mobile only -->
  <div class="lg:hidden w-full">
    <Separator 
      orientation="horizontal"
      class="bg-gray-800 h-[1px] w-full mb-8"
    />
  </div>

      <!-- Time list -->
      <div
        class="scrollable-list w-full lg:w-1/3 h-[250px] flex flex-col items-center gap-4"
      >
        <template v-if="loadingTimeSlots">
          <div
            v-for="i in 5"
            :key="i"
            class="border-surface-border h-[40px] w-full max-w-[135px] animate-pulse rounded-[8px] border bg-gray-100 dark:bg-gray-800 p-6"
          ></div>
        </template>
        <div
          v-else-if="availableTimes.length === 0 && date"
          class="py-4 text-sm text-gray-500"
        >
         {{ $t("step7.noTime") }}
        </div>
        <div v-else-if="!date" class="py-4 text-sm text-gray-500">
          {{ $t("step7.selectDate") }}
        </div>
        <div
          v-for="time in availableTimes"
          :key="time.id"
          @click="selectedTime = time.id"
          :class="[
            'border-surface-border flex h-[40px] w-full max-w-[135px] cursor-pointer items-center justify-center rounded-[8px] border py-4 text-[16px] font-medium transition-colors',
            selectedTime === time.id
              ? 'bg-gradient-default text-primary'
              : 'hover:bg-muted',
          ]"
        >
          {{ time.label }}
        </div>
      </div>
    </div>
    <p class="m-2 mt-6"> {{ $t("step7.scheduledAt") }} {{ date }} ,{{ selectedTime }}</p>
    <div class="mt-6  flex w-[98%] gap-4">
      <Button
        size="stepBtn"
        variant="wsPrev"
        :disabled="props.isPrevDisabled || loading"
        @click="props.prev"
        class="w-1/2"
      >
        {{ $t("buttons.prev") }}
      </Button>

      <Button
        size="stepBtn"
        :disabled="isStartButtonDisabled"
        @click="handleSubmit"
        class="w-1/2"
      >
        <span v-if="loading"> {{ $t("buttons.loading_send_button") }}</span>
        <span v-else>{{ $t("buttons.start") }}</span>
      </Button>
    </div>
  </div>
</template>
<style scoped>
.scrollable-list::-webkit-scrollbar {
  width: 8px;
}

.scrollable-list::-webkit-scrollbar-track {
  background: transparent;
  border-radius: 4px;
}

.scrollable-list::-webkit-scrollbar-thumb {
  background: var(--surface-border);
  border-radius: 4px;
}

.scrollable-list::-webkit-scrollbar-thumb:hover {
  background: var(--surface-border);
}

.scrollable-list {
  scrollbar-width: thin;
  scrollbar-color: var(--surface-border) transparent;
  overflow-y: auto;
  overflow-x: hidden;
}
</style>
