<template>
  <v-row no-gutters align="center" justify="center">
    <v-col cols="12" lg="12">
      <TableMain
        title="Attendance Records"
        :items="items"
        :headers="headers"
        :loading="loading"
        :show-header="true"
        v-model:page="page"
        :pages="pages"
        :pageRange="pageRange"
        no-data-text="No attendance records found."
        @row-click="handleRowClick"
      >
        <template #actions>
          <v-row no-gutters align="center" class="w-100">
            <v-col cols="auto" v-if="canCheckInOut">
              <v-btn
                class="text-none"
                rounded="pill"
                variant="tonal"
                size="large"
                @click="onCreateItem"
              >
                {{ hasCheckedInToday ? "Check Out" : "Check In" }}
              </v-btn>
            </v-col>
            <v-spacer />

            <v-col cols="auto">
              <v-text-field
                v-model="searchInput"
                density="compact"
                placeholder="Search"
                clearable
                width="300"
                append-inner-icon="mdi-magnify"
                hide-details
              />
            </v-col>
          </v-row>
        </template>

        <template #item.checkInTimestamp="{ item }">
          <span>{{ formatDate(item.checkInTimestamp) }}</span>
        </template>

        <template #item.checkOutTimestamp="{ item }">
          <span>{{
            item.checkOutTimestamp ? formatDate(item.checkOutTimestamp) : "N/A"
          }}</span>
        </template>

        <template #item.totalHours="{ item }">
          <span>{{ calculateTotalHours(item) }}</span>
        </template>
      </TableMain>
    </v-col>
  </v-row>

  <AttendanceCheckInOutDialog
    v-model="dialogShowForm"
    :action="currentAction"
    :serviceType="props.serviceType"
    @saved="onAttendanceSaved"
    @close="dialogShowForm = false"
  />

  <AttendanceDetailsDialog
    v-model="dialogShowMoreActions"
    :attendance-id="selectedAttendanceId"
    :serviceType="props.serviceType"
    @close="dialogShowMoreActions = false"
  />

  <Snackbar v-model="messageSnackbar" :text="message" :color="messageColor" />
</template>

<script setup lang="ts">
import useAttendance from "../composables/useAttendance";

const props = defineProps({
  orgId: { type: String, default: "" },
  site: { type: String, default: "" },
  serviceType: { type: String, default: "" },
  canViewOwnAttendance: { type: Boolean, default: true },
  canCheckInOut: { type: Boolean, default: false },
  canViewAttendanceDetails: { type: Boolean, default: true },
});

const canViewOwnAttendance = computed(() => props.canViewOwnAttendance);
const canCheckInOut = computed(() => props.canCheckInOut);
const canViewAttendanceDetails = computed(() => props.canViewAttendanceDetails);

const searchInput = ref("");
const dialogShowForm = ref(false);
const currentAction = ref<"checkIn" | "checkOut">("checkIn");
const messageSnackbar = ref(false);
const message = ref("");
const messageColor = ref("success");

const items = ref<Array<Record<string, any>>>([]);
const submitting = ref(false);

const headers = [
  { title: "Team Member", value: "userName" },
  { title: "Check In", value: "checkInTimestamp" },
  { title: "Check Out", value: "checkOutTimestamp" },
  { title: "Total Hours", value: "totalHours" },
];

const { getMyAttendances, checkIn, checkOut } = useAttendance();
const { formatDate } = useUtils();

const dialogShowMoreActions = ref(false);
const selectedAttendanceId = ref("");
const todayAttendance = ref<Record<string, any> | null>(null);

const hasCheckedInToday = computed(() => {
  return (
    todayAttendance.value &&
    todayAttendance.value.checkInTimestamp &&
    !todayAttendance.value.checkOutTimestamp
  );
});

function calculateTotalHours(attendance: any): string {
  const checkInTime =
    attendance.checkInTimestamp || attendance.checkIn?.timestamp;
  const checkOutTime =
    attendance.checkOutTimestamp || attendance.checkOut?.timestamp;

  if (!checkInTime) return "N/A";
  if (!checkOutTime) return "In Progress";

  const checkIn = new Date(checkInTime);
  const checkOut = new Date(checkOutTime);
  const diffMs = checkOut.getTime() - checkIn.getTime();
  const diffHours = diffMs / (1000 * 60 * 60);

  return `${diffHours.toFixed(2)} hrs`;
}

const page = ref(1);
const pages = ref(0);
const pageRange = ref("-- - -- of --");

const {
  data: getMyAttendancesReq,
  refresh: getMyAttendancesRefresh,
  pending: loading,
} = await useLazyAsyncData(
  "get-my-attendances",
  () =>
    getMyAttendances({
      page: page.value,
      search: searchInput.value,
      site: props.site,
      serviceType: props.serviceType,
    }),
  {
    watch: [page, searchInput, () => props.site],
  }
);

watchEffect(() => {
  if (getMyAttendancesReq.value) {
    items.value = getMyAttendancesReq.value.items;
    pages.value = getMyAttendancesReq.value.pages;
    pageRange.value = getMyAttendancesReq.value.pageRange;

    const today = new Date().toISOString().split("T")[0];
    todayAttendance.value =
      getMyAttendancesReq.value.items.find((item: any) => {
        if (!item.checkInTimestamp) return false;
        const itemDate = new Date(item.checkInTimestamp)
          .toISOString()
          .split("T")[0];
        return itemDate === today && !item.checkOutTimestamp;
      }) || null;
  }
});

const onCreateItem = () => {
  currentAction.value = hasCheckedInToday.value ? "checkOut" : "checkIn";
  dialogShowForm.value = true;
};

async function handleRowClick(data: any) {
  const id = (data?.item as any)?._id;
  if (!id) return;

  selectedAttendanceId.value = id;
  dialogShowMoreActions.value = true;
}

const onAttendanceSaved = async (
  payload: TAttendanceCheckIn | TAttendanceCheckOut
) => {
  submitting.value = true;

  try {
    let response;
    if (currentAction.value === "checkIn") {
      response = await checkIn(props.site, payload as TAttendanceCheckIn);
    } else {
      if (!todayAttendance.value?._id) {
        throw new Error("Attendance ID not found");
      }
      response = await checkOut(
        todayAttendance.value._id,
        payload as TAttendanceCheckOut
      );
    }

    message.value = response.message;
    messageColor.value = "success";
    messageSnackbar.value = true;
    dialogShowForm.value = false;

    await getMyAttendancesRefresh();
  } catch (err: any) {
    message.value = err.data?.message;
    messageColor.value = "error";
    messageSnackbar.value = true;
  } finally {
    submitting.value = false;
  }
};
</script>
