<template>
  <v-row no-gutters align="center" justify="center">
    <v-col cols="12" lg="12">
      <TableMain
        :title="'Cleaner Checklist'"
        :headers="headers"
        :items="items"
        :loading="loading"
        :show-header="true"
        v-model:page="page"
        :pages="pages"
        :pageRange="pageRange"
        @update:items="items = $event"
        @row-click="onRowClick"
        @refresh="getScheduleAreasRefresh"
      >
        <template #item.type="{ item }">
          <span class="text-capitalize">{{ item.type }}</span>
        </template>

        <template #extension>
          <v-row no-gutters class="w-100 d-flex flex-column">
            <v-card
              class="w-100 px-3 d-flex align-center ga-5 py-2"
              flat
              :height="60"
            >
              <v-select
                v-model="statusFilter"
                :items="statusOptions"
                density="compact"
                hide-details
                class="mx-2"
                style="max-width: 160px"
                item-title="title"
                item-value="value"
                label="Status"
              />

              <v-select
                v-model="areaTypeFilter"
                :items="typeOptions"
                density="compact"
                hide-details
                class="mx-2"
                style="max-width: 160px"
                item-title="title"
                item-value="value"
                label="Type"
              />
            </v-card>
          </v-row>
        </template>
        <template #actions>
          <v-row class="w-100" align="center" no-gutters>
            <v-col cols="auto">
              <v-btn
                variant="text"
                color="primary"
                class="text-none"
                @click="back"
              >
                <v-icon left>mdi-arrow-left</v-icon>
                Back
              </v-btn>
            </v-col>

            <v-spacer />

            <v-col cols="auto">
              <v-chip
                v-if="isScheduleClosed"
                color="error"
                variant="tonal"
                class="text-capitalize mr-2"
              >
                <v-icon start>mdi-lock</v-icon>
                Closed – View Only
              </v-chip>
              <v-btn
                v-if="canViewHistory"
                class="text-none mr-2"
                size="large"
                color="primary"
                aria-label="History"
                @click="openHistory"
              >
                History
              </v-btn>
              <v-btn
                v-if="canGenerateChecklist"
                class="text-none"
                size="large"
                color="primary"
                aria-label="Generate"
                @click="_generateChecklist"
                :loading="submitting"
                :disabled="isScheduleClosed"
              >
                Generate List
              </v-btn>
            </v-col>
          </v-row>
        </template>
        <template #item.acceptedBy="{ item }">
          <div
            v-if="
              item.acceptedByName ||
              (item.status && String(item.status).toLowerCase() === 'accepted')
            "
          >
            <span class="text-capitalize" color="success" variant="tonal">
              {{ item.acceptedByName || item.acceptedBy || "Accepted" }}
            </span>
          </div>
          <div v-else-if="isScheduleClosed">
            <v-chip
              size="small"
              color="error"
              variant="tonal"
              class="text-capitalize"
              >Closed</v-chip
            >
          </div>
          <div v-else>
            <v-btn
              v-if="canManageScheduleTasks"
              variant="outlined"
              size="medium"
              class="text-capitalize px-4 py-2"
              @click.stop="() => _acceptAreaChecklist(item._id)"
            >
              Accept
            </v-btn>
          </div>
        </template>

        <template #item.createdAt="{ value }">
          {{
            formatDate
              ? formatDate(value)
              : value
              ? new Date(value).toLocaleString()
              : ""
          }}
        </template>

        <template #item.status="{ value }">
          <v-chip
            class="text-capitalize"
            :color="getStatusColor(value)"
            variant="flat"
            pill
          >
            {{ value || "No Status" }}
          </v-chip>
        </template>
      </TableMain></v-col
    >
  </v-row>

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

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

const props = defineProps({
  orgId: { type: String, required: true, default: "" },
  site: { type: String, required: true, default: "" },
  scheduleAreaId: { type: String, required: true, default: "" },
  type: { type: String, required: true, default: "cleaner" },
  serviceType: { type: String, default: "" },
  scheduleRoute: { type: String, default: "cleaning-schedule" },
  canGenerateChecklist: { type: Boolean, default: false },
  canViewHistory: { type: Boolean, default: true },
  canManageScheduleTasks: { type: Boolean, default: false },
});

const submitting = ref(false);
const message = ref("");
const messageSnackbar = ref(false);
const messageColor = ref("");
const areaName = ref<string>("");
const page = ref(1);
const pages = ref(0);
const pageRange = ref("-- - -- of --");

const headers = [
  { title: "Area", value: "name" },
  { title: "Status", value: "status" },
  { title: "Type", value: "type" },
  { title: "No. of Visits", value: "set" },
];

const { formatDate, back } = useUtils();

const canGenerateChecklist = computed(() => props.canGenerateChecklist);
const canViewHistory = computed(() => props.canViewHistory);
const canManageScheduleTasks = computed(() => props.canManageScheduleTasks);

const selectedScheduleStatus = useState<string>(
  "selectedScheduleStatus",
  () => ""
);
const isScheduleClosed = computed(
  () => selectedScheduleStatus.value.toLowerCase() === "closed"
);

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

const statusFilter = ref<TScheduleAreaStatus>("all");
const statusOptions = [
  { title: "All", value: "all" },
  { title: "Open", value: "open" },
  { title: "Ongoing", value: "ongoing" },
  { title: "Completed", value: "completed" },
];
const areaTypeFilter = ref<TAreaType>("all");
const typeOptions = [
  { title: "All", value: "all" },
  { title: "Common", value: "common" },
  { title: "Toilet", value: "toilet" },
];

const { getScheduleAreas, acceptAreaChecklist, generateChecklist } =
  useCleaningSchedules();

const {
  data: getScheduleAreasReq,
  refresh: getScheduleAreasRefresh,
  pending: loading,
} = await useLazyAsyncData(
  "get-all-area-cleaner-checklists",
  () =>
    getScheduleAreas({
      page: page.value,
      scheduleAreaId: props.scheduleAreaId,
      status: statusFilter.value === "all" ? undefined : statusFilter.value,
      type: areaTypeFilter.value === "all" ? undefined : areaTypeFilter.value,
      serviceType: props.serviceType,
    }),
  {
    watch: [
      page,
      () => props.orgId,
      () => props.site,
      () => props.scheduleAreaId,
      statusFilter,
      areaTypeFilter,
    ],
  }
);

watchEffect(() => {
  if (getScheduleAreasReq.value) {
    items.value = getScheduleAreasReq.value.items;
    pages.value = getScheduleAreasReq.value.pages;
    pageRange.value = getScheduleAreasReq.value.pageRange;
    areaName.value = getScheduleAreasReq.value.areaName;
  }
});

const getStatusColor = (status: unknown): string => {
  if (!status) return "grey";

  const normalized = String(status).toLowerCase();

  switch (normalized) {
    case "open":
      return "grey";
    case "ongoing":
      return "primary";
    case "completed":
    case "accepted":
      return "success";
    case "closed":
    case "rejected":
      return "error";
    default:
      return "secondary";
  }
};

function showMessage(msg: string, color: string = "error") {
  message.value = msg;
  messageColor.value = color;
  messageSnackbar.value = true;
}

function onRowClick(data: any) {
  const item = data?.item;
  const id = item?._id || item?.id || item?.areaId;
  if (id) {
    const checklistType =
      props.type === "cleaner"
        ? props.scheduleRoute
        : `${props.type}-checklist`;
    const path = `/${props.orgId}/${props.site}/${checklistType}/${props.scheduleAreaId}/${id}`;
    navigateTo(path);
  } else {
    console.warn("Row clicked but no id found to navigate:", item);
  }
}

function openHistory() {
  const path = `/${props.orgId}/${props.site}/${props.scheduleRoute}/${props.scheduleAreaId}/history`;
  navigateTo(path);
}

async function _acceptAreaChecklist(id?: string) {
  if (!id) {
    showMessage("No checklist id provided to accept.", "error");
    return;
  }

  try {
    submitting.value = true;
    await acceptAreaChecklist(id);
    showMessage("Area checklist accepted successfully.", "success");

    if (typeof getScheduleAreasRefresh === "function") {
      getScheduleAreasRefresh();
    }
  } catch (error: any) {
    showMessage(error?.message || "Failed to accept area checklist.", "error");
  } finally {
    submitting.value = false;
  }
}

async function _generateChecklist() {
  try {
    submitting.value = true;
    await generateChecklist(props.site, props.scheduleAreaId);
    showMessage("Checklist generated successfully.", "success");

    if (typeof getScheduleAreasRefresh === "function") {
      getScheduleAreasRefresh();
    }
  } catch (error: any) {
    showMessage(error?.message || "Failed to generate checklist.", "error");
  } finally {
    submitting.value = false;
  }
}

onMounted(() => {
  try {
    const { $socket } = useNuxtApp() as any;
    if ($socket) {
      $socket.emit("join:cleaning-area", props.scheduleAreaId);

      $socket.on(
        "area-checklist:generated",
        (payload: { scheduleId: string; siteId: string }) => {
          if (payload?.scheduleId !== props.scheduleAreaId) return;
          if (typeof getScheduleAreasRefresh === "function") {
            getScheduleAreasRefresh();
          }
        }
      );
    }
  } catch (_) {}
});

onUnmounted(() => {
  try {
    const { $socket } = useNuxtApp() as any;
    if ($socket) {
      $socket.emit("leave:cleaning-area", props.scheduleAreaId);
      $socket.off("area-checklist:generated");
    }
  } catch (_) {}
});
</script>
