<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."
        @refresh="getAttendancesRefresh"
        @row-click="handleRowClick"
      >
        <template #actions>
          <v-btn
            v-if="canManageAttendanceSettings"
            variant="flat"
            color="black"
            class="text-none"
            @click="dialogShowSettings = true"
          >
            <v-icon class="mr-2">mdi-cog</v-icon>
            Settings
          </v-btn>
        </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>

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

  <AttendanceSettingsDialog
    v-model="dialogShowSettings"
    :site="props.site"
    :serviceType="props.serviceType"
    @saved="onSettingsSaved"
    @close="dialogShowSettings = false"
  />
</template>

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

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

const canViewAllAttendance = computed(() => props.canViewAllAttendance);
const canViewAttendanceDetails = computed(() => props.canViewAttendanceDetails);
const canManageAttendanceSettings = computed(() => props.canManageAttendanceSettings);

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

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

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

const { getAttendances } = useAttendance();
const { formatDate } = useUtils();

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 {
  data: getAttendancesReq,
  refresh: getAttendancesRefresh,
  pending: loading,
} = await useLazyAsyncData(
  "get-my-attendances",
  () =>
    getAttendances({
      page: page.value,
      search: searchInput.value,
        site: props.site,
        serviceType: props.serviceType,
    }),
  {
    watch: [page, searchInput, () => props.site],
  }
);

watchEffect(() => {
  if (getAttendancesReq.value) {
    items.value = getAttendancesReq.value.items.map((item: any) => ({
      ...item,
      totalHours: calculateTotalHours(item),
    }));
    pages.value = getAttendancesReq.value.pages;
    pageRange.value = getAttendancesReq.value.pageRange;
  }
});

const dialogShowMoreActions = ref(false);
const dialogShowSettings = ref(false);
const selectedAttendanceId = ref("");

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

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

const onSettingsSaved = async (payload: any) => {
  console.log("Settings saved:", payload);
  // TODO: Implement API call to save settings
  await getAttendancesRefresh();
};
</script>
