<template>
  <v-row no-gutters align="center" justify="center">
    <v-col cols="12">
      <TableMain
        :title="'Schedule Tasks'"
        :items="items"
        :headers="headers"
        :loading="loading"
        :show-header="true"
        v-model:page="page"
        :pages="pages"
        :pageRange="pageRange"
        :no-data-text="'No schedule tasks found'"
        @refresh="getTaskRefresh"
        :canCreate="canCreateScheduleTask"
        createLabel="Create Schedule Task"
        @create="openFormDialog"
        @row-click="onRowClick"
      >
        <template #actions>
          <v-row no-gutters align="center" class="w-100">
            <v-col cols="auto" v-if="canCreateScheduleTask">
              <v-btn
                class="text-none"
                rounded="pill"
                variant="tonal"
                size="large"
                @click="openFormDialog"
              >
                Create Schedule Task
              </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.areas="{ value }">
          <div v-if="value && value.length > 0">
            <v-chip
              v-for="(area, idx) in value.slice(0, 2)"
              :key="idx"
              size="small"
              class="mr-1 mb-1"
            >
              {{ area.name }}
            </v-chip>
            <v-chip v-if="value.length > 2" size="small" class="mb-1">
              +{{ value.length - 2 }} more
            </v-chip>
          </div>
          <span v-else>N/A</span>
        </template>

        <template #item.status="{ value }">
          <v-chip
            :color="value === 'active' ? 'success' : 'default'"
            class="text-capitalize"
          >
            {{ value || "N/A" }}
          </v-chip>
        </template>
      </TableMain>

      <ScheduleTaskForm
        v-model:show="showForm"
        :mode="formMode"
        :taskData="selectedTask"
        :site="props.site"
        :serviceType="props.serviceType"
        @refresh="getTaskRefresh"
      />

      <v-dialog v-model="dialogShowMoreActions" width="400" persistent>
        <HygieneUpdateMoreAction
          :title="selectedTask?.title || 'Schedule Task Actions'"
          :canUpdate="canUpdateScheduleTask"
          @close="dialogShowMoreActions = false"
          :canDelete="canDeleteScheduleTask"
          :deleteButtonLabel="'Delete Schedule Task'"
          @edit="onEditFromMoreAction"
          @delete="onDeleteFromMoreAction"
          :editButtonLabel="'Edit Schedule Task'"
        >
          <template #content>
            <v-row no-gutters>
              <v-col v-if="selectedTask" cols="12" class="mb-2">
                <v-row no-gutters class="mb-2">
                  <v-col cols="5" class="text-subtitle-2 font-weight-bold">
                    Title:
                  </v-col>
                  <v-col cols="7" class="text-subtitle-2">
                    {{ selectedTask.title || "N/A" }}
                  </v-col>
                </v-row>

                <v-row no-gutters class="mb-2">
                  <v-col cols="5" class="text-subtitle-2 font-weight-bold">
                    Dates:
                  </v-col>
                  <v-col cols="7" class="text-subtitle-2">
                    <div
                      v-if="selectedTask.dates && selectedTask.dates.length > 0"
                      class="d-flex flex-wrap gap-1"
                    >
                      <v-chip
                        v-for="date in selectedTask.dates"
                        :key="date"
                        size="x-small"
                        class="mr-1 mb-1"
                      >
                        {{ formatDateChip(date) }}
                      </v-chip>
                    </div>
                    <div v-else>N/A</div>
                  </v-col>
                </v-row>

                <v-row v-if="selectedTask.time" no-gutters class="mb-2">
                  <v-col cols="5" class="text-subtitle-2 font-weight-bold">
                    Time:
                  </v-col>
                  <v-col cols="7" class="text-subtitle-2">
                    {{ selectedTask.time || "N/A" }}
                  </v-col>
                </v-row>

                <v-row
                  v-if="selectedTask.areas && selectedTask.areas.length > 0"
                  no-gutters
                  class="mb-2"
                >
                  <v-col cols="5" class="text-subtitle-2 font-weight-bold">
                    Areas:
                  </v-col>
                  <v-col cols="7" class="text-subtitle-2">
                    <div
                      v-for="(area, idx) in selectedTask.areas"
                      :key="idx"
                      class="mb-1"
                    >
                      {{ area.name || area }}
                    </div>
                  </v-col>
                </v-row>

                <v-row
                  v-if="selectedTask.areas && selectedTask.areas.length > 0"
                  no-gutters
                  class="mb-2"
                >
                  <v-col cols="12">
                    <div class="text-subtitle-2 font-weight-bold mb-2">Units Under Selected Areas:</div>
                    <v-card variant="outlined" rounded>
                      <v-list density="compact" nav>
                        <template
                          v-for="(area, idx) in selectedTask.areas"
                          :key="area.value || area._id"
                        >
                          <v-divider v-if="Number(idx) > 0" />
                          <v-list-item
                            :title="area.name"
                            class="font-weight-medium"
                            @click="toggleViewArea(area.value || area._id)"
                          >
                            <template #prepend>
                              <v-icon size="16">
                                {{
                                  openViewAreas.includes(area.value || area._id)
                                    ? 'mdi-chevron-down'
                                    : 'mdi-chevron-right'
                                }}
                              </v-icon>
                            </template>
                            <template #append>
                              <v-progress-circular
                                v-if="loadingViewUnits && !(area.value || area._id in fetchedViewAreaUnits)"
                                size="14"
                                width="2"
                                indeterminate
                                color="primary"
                              />
                              <v-chip v-else size="x-small" variant="tonal" color="primary">
                                {{ (fetchedViewAreaUnits[area.value || area._id] || []).length }}
                              </v-chip>
                            </template>
                          </v-list-item>
                          <v-expand-transition>
                            <div v-show="openViewAreas.includes(area.value || area._id)">
                              <v-card-text class="px-3 py-2">
                                <div
                                  v-if="(fetchedViewAreaUnits[area.value || area._id] || []).length > 0"
                                  class="d-flex flex-wrap ga-3"
                                >
                                  <v-chip
                                    v-for="unit in fetchedViewAreaUnits[area.value || area._id]"
                                    :key="unit.unit"
                                    size="small"
                                    variant="tonal"
                                  >
                                    {{ unit.name }}
                                  </v-chip>
                                </div>
                                <span v-else class="text-caption text-disabled">No units configured</span>
                              </v-card-text>
                            </div>
                          </v-expand-transition>
                        </template>
                      </v-list>
                    </v-card>
                  </v-col>
                </v-row>

                <v-row v-if="selectedTask.description" no-gutters class="mb-2">
                  <v-col cols="5" class="text-subtitle-2 font-weight-bold">
                    Description:
                  </v-col>
                  <v-col cols="7" class="text-subtitle-2">
                    {{ selectedTask.description || "N/A" }}
                  </v-col>
                </v-row>

                <v-row v-if="selectedTask.status" no-gutters class="mb-2">
                  <v-col cols="5" class="text-subtitle-2 font-weight-bold">
                    Status:
                  </v-col>
                  <v-col cols="7" class="text-subtitle-2">
                    <v-chip
                      :color="
                        selectedTask.status === 'active' ? 'success' : 'default'
                      "
                      size="small"
                      class="text-capitalize"
                    >
                      {{ selectedTask.status || "N/A" }}
                    </v-chip>
                  </v-col>
                </v-row>

                <v-row v-if="selectedTask.createdAt" no-gutters class="mb-2">
                  <v-col cols="5" class="text-subtitle-2 font-weight-bold">
                    Created At:
                  </v-col>
                  <v-col cols="7" class="text-subtitle-2">
                    {{ formatDate(selectedTask.createdAt) || "N/A" }}
                  </v-col>
                </v-row>
              </v-col>

              <v-col v-if="message" cols="12" class="my-2">
                <span class="text-subtitle-2 text-error">{{ message }}</span>
              </v-col>
            </v-row>
          </template>
        </HygieneUpdateMoreAction>
      </v-dialog>

      <v-dialog v-model="dialogDeleteTask" max-width="450">
        <v-card>
          <v-toolbar>
            <v-row no-gutters class="fill-height px-6" align="center">
              <span class="font-weight-bold text-h6 text-capitalize">
                Delete {{ selectedTask?.title || "Schedule Task" }}
              </span>
            </v-row>
          </v-toolbar>
          <v-card-text>
            <span class="text-subtitle-2"
              >Are you sure you want to delete this schedule task?</span
            >
          </v-card-text>

          <v-toolbar class="pa-0" density="compact">
            <v-row no-gutters>
              <v-col cols="6" class="pa-0">
                <v-btn
                  block
                  variant="text"
                  class="text-none"
                  size="large"
                  @click="dialogDeleteTask = false"
                  height="48"
                >
                  Cancel
                </v-btn>
              </v-col>

              <v-col cols="6" class="pa-0">
                <v-btn
                  block
                  variant="flat"
                  color="black"
                  class="text-none font-weight-bold"
                  height="48"
                  :loading="submitting"
                  @click="_deleteScheduleTask"
                >
                  Delete
                </v-btn>
              </v-col>
            </v-row>
          </v-toolbar>
        </v-card>
      </v-dialog>

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

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

const props = defineProps({
  orgId: { type: String, required: true },
  site: { type: String, required: true },
  type: { type: String, default: "toilet" },
  serviceType: { type: String, default: "" },
  canViewScheduleTasks: { type: Boolean, default: true },
  canCreateScheduleTask: { type: Boolean, default: false },
  canUpdateScheduleTask: { type: Boolean, default: false },
  canDeleteScheduleTask: { type: Boolean, default: false },
  canViewScheduleTaskDetails: { type: Boolean, default: true },
});

const { formatDate, debounce } = useUtils();
const { getScheduleTasks, getScheduleTaskById, deleteScheduleTask } =
  useScheduleTask();
const { getAreaById } = useAreas();

const canViewScheduleTasks = computed(() => props.canViewScheduleTasks);
const canCreateScheduleTask = computed(() => props.canCreateScheduleTask);
const canUpdateScheduleTask = computed(() => props.canUpdateScheduleTask);
const canDeleteScheduleTask = computed(() => props.canDeleteScheduleTask);
const canViewScheduleTaskDetails = computed(
  () => props.canViewScheduleTaskDetails
);

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

const searchInput = ref("");
const showForm = ref(false);
const selectedTask = ref<Record<string, any>>({});
const formMode = ref<"add" | "edit">("add");
const submitting = ref(false);
const dialogShowMoreActions = ref(false);
const dialogDeleteTask = ref(false);

const message = ref("");
const messageSnackbar = ref(false);
const messageColor = ref("success");

const loadingViewUnits = ref(false);
const fetchedViewAreaUnits = ref<Record<string, { name: string; unit: string }[]>>({});
const openViewAreas = ref<string[]>([]);

const toggleViewArea = (id: string) => {
  const idx = openViewAreas.value.indexOf(id);
  if (idx === -1) openViewAreas.value.push(id);
  else openViewAreas.value.splice(idx, 1);
};

watch(dialogShowMoreActions, async (isOpen) => {
  if (!isOpen) return;
  const areas = (selectedTask.value?.areas || []) as any[];
  if (areas.length === 0) return;
  openViewAreas.value = areas.map((a) => a.value || a._id);
  const toFetch = areas
    .map((a) => a.value || a._id)
    .filter((id) => id && !(id in fetchedViewAreaUnits.value));
  if (toFetch.length === 0) return;
  loadingViewUnits.value = true;
  try {
    await Promise.all(
      toFetch.map(async (id: string) => {
        try {
          const result = await getAreaById(id);
          fetchedViewAreaUnits.value[id] = result?.units || [];
        } catch {
          fetchedViewAreaUnits.value[id] = [];
        }
      })
    );
  } finally {
    loadingViewUnits.value = false;
  }
});

const items = ref<any[]>([]);

const headers = [
  { title: "Title", value: "title" },
  { title: "Areas", value: "areas" },
  { title: "Status", value: "status" },
];

const showMessage = (text: string, color: string = "success") => {
  message.value = text;
  messageColor.value = color;
  messageSnackbar.value = true;
};

const formatDateChip = (dateStr: string) => {
  const parts = dateStr?.split("-");
  if (parts?.length === 3) return `${parts[2]}-${parts[1]}-${parts[0]}`;
  return dateStr;
};

const mapShortToDay = (short: string) => {
  const mapping: Record<string, string> = {
    Mon: "Monday",
    Tue: "Tuesday",
    Wed: "Wednesday",
    Thu: "Thursday",
    Fri: "Friday",
    Sat: "Saturday",
    Sun: "Sunday",
  };
  return mapping[short] || short;
};

const formatTaskDays = (dayField: any) => {
  if (!dayField) return "N/A";
  if (Array.isArray(dayField))
    return dayField.map((d) => mapShortToDay(d)).join(", ");
  return String(dayField);
};

const {
  data: getTaskReq,
  refresh: getTaskRefresh,
  pending: loading,
} = await useLazyAsyncData(
  `get-schedule-tasks-${props.site}`,
  () =>
    getScheduleTasks({
      page: page.value,
      site: props.site,
      search: searchInput.value,
      serviceType: props.serviceType,
    }),
  {
    watch: [page, () => props.site],
  }
);

watchEffect(() => {
  if (getTaskReq.value) {
    items.value = getTaskReq.value.items || getTaskReq.value || [];
    pages.value = getTaskReq.value.pages || 0;
    pageRange.value = getTaskReq.value.pageRange || "-- - -- of --";
  }
});

const debounceSearch = debounce(getTaskRefresh, 500);

watch(
  [searchInput],
  () => {
    debounceSearch();
  },
  { immediate: false, deep: true }
);

function openFormDialog() {
  formMode.value = "add";
  selectedTask.value = {};
  showForm.value = true;
}

async function onRowClick(data: any) {
  const taskId = data?.item?._id || data?._id || data?.item?.id || data?.id;

  if (taskId) {
    try {
      const fullTaskData = await getScheduleTaskById(taskId);
      selectedTask.value = fullTaskData || data?.item || data;
    } catch (error) {
      selectedTask.value = data?.item || data;
    }
  } else {
    selectedTask.value = data?.item || data;
  }

  dialogShowMoreActions.value = true;
  message.value = "";
}

const onEditFromMoreAction = async () => {
  dialogShowMoreActions.value = false;
  formMode.value = "edit";
  showForm.value = true;
};

const onDeleteFromMoreAction = () => {
  dialogShowMoreActions.value = false;
  dialogDeleteTask.value = true;
};

async function _deleteScheduleTask() {
  if (!selectedTask.value) return;

  try {
    submitting.value = true;
    const id =
      (selectedTask.value as any)._id || (selectedTask.value as any).id;
    if (!id) throw new Error("Invalid schedule task id");

    const response = await deleteScheduleTask(id);
    dialogDeleteTask.value = false;
    showMessage(response?.message, "success");

    await getTaskRefresh();
  } catch (error: any) {
    showMessage(error?.data?.message, "error");
  } finally {
    submitting.value = false;
  }
}
</script>
