<template>
  <v-row no-gutters>
    <v-col cols="12" class="mb-2">
      <v-row no-gutters align="center" justify="space-between">
        <v-btn
          class="text-none text-capitalize"
          rounded="pill"
          variant="tonal"
          size="large"
          @click="(showCreateDialog = true), (isEditMode = false)"
          v-if="canCreateWorkOrder"
        >
          Create Work Order
        </v-btn>

        <v-text-field
          v-model="searchText"
          placeholder="Search work order..."
          variant="outlined"
          density="comfortable"
          clearable
          hide-details
          class="ml-2"
          style="max-width: 250px"
        />
      </v-row>
    </v-col>
    <v-col cols="12">
      <v-card
        width="100%"
        variant="outlined"
        border="thin"
        rounded="lg"
        :loading="loading"
      >
        <v-toolbar density="compact" color="grey-lighten-4">
          <template #prepend>
            <v-btn fab icon density="comfortable" @click="updatePage(1)">
              <v-icon>mdi-refresh</v-icon>
            </v-btn>
          </template>

          <template #append>
            <v-row no-gutters justify="end" align="center">
              <span class="mr-2 text-caption text-fontgray">
                {{ pageRange }}
              </span>
              <local-pagination
                v-model="page"
                :length="pages"
                @update:value="updatePage"
              />
            </v-row>
          </template>
        </v-toolbar>

        <v-data-table
          :headers="headers"
          :items="items"
          item-value="_id"
          items-per-page="20"
          fixed-header
          hide-default-footer
          :hide-default-header="false"
          @click:row="tableRowClickHandler"
          style="max-height: calc(100vh - (200px))"
        >
          <template v-slot:item.createdAt="{ item }">
            {{ formatDateDDMMYYYYLocal(item.createdAt) }}
          </template>
        </v-data-table>
      </v-card>
    </v-col>
  </v-row>

  <WorkOrderCreate
    v-model="showCreateDialog"
    created-from="workOrder"
    :work-order="_workOrder"
    @update:work-order="(val: TWorkOrderCreate) => (_workOrder = val)"
    :is-edit-mode="isEditMode"
    :loading="isSubmitting"
    :categories="serviceProviders"
    :theme="theme"
    :errored-images="erroredImages"
    :max-files="5"
    :message-fn="showMessage"
    @close="handleCloseDialog"
    @file-added="handleFileAdded"
    @file-deleted="deleteFile"
    @submit="submitWorkOrder"
  />

  <ConfirmDialog
    v-model="showDeleteDialog"
    :loading="submitting"
    @submit="submitDelete"
    :image-src="'/images/icons/delete-icon.png'"
  >
    <template #image>
      <v-img
        height="120"
        src="/images/icons/delete-icon.png"
        alt="Delete Icon"
        contain
      />
    </template>

    <template #title>
      Are you sure you want to delete this work order?
    </template>

    <template #footer>
      <v-btn
        color="primary-button"
        variant="flat"
        class="font-weight-bold py-5 d-flex align-center justify-center"
        @click="submitDelete"
        :loading="submitting"
        block
      >
        Confirm
      </v-btn>
    </template>
  </ConfirmDialog>

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

  <!-- Preview Dialog -->
  <v-dialog
    v-model="dialogPreview"
    width="450"
    persistent
    v-if="canViewWorkOrders"
  >
    <v-card width="100%">
      <v-card-text style="max-height: 100vh; overflow-y: auto" class="pb-0">
        <v-row no-gutters v-if="selectedWorkOrder" class="mb-4">
          <v-col cols="12">
            <strong>Subject:</strong> {{ selectedWorkOrder.subject }}
          </v-col>
          <v-col cols="12">
            <strong>Category:</strong>
            {{ selectedWorkOrder.category }}
          </v-col>
          <v-col cols="12">
            <strong>Status:</strong>
            {{ selectedWorkOrder.status }}
          </v-col>
        </v-row>
      </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="dialogPreview = false"
              height="48"
            >
              Close
            </v-btn>
          </v-col>
          <v-col cols="6" class="pa-0">
            <v-menu>
              <template #activator="{ props }">
                <v-btn
                  block
                  variant="flat"
                  color="black"
                  class="text-none"
                  height="48"
                  v-bind="props"
                  tile
                >
                  More actions
                </v-btn>
              </template>

              <v-list class="pa-0">
                <v-list-item
                  @click="onViewWorkOrder(selectedWorkOrder)"
                  v-if="canViewWorkOrderDetails"
                >
                  <v-list-item-title class="text-subtitle-2">
                    View
                  </v-list-item-title>
                </v-list-item>
                <v-list-item
                  @click="editWorkOrder(selectedWorkOrder)"
                  v-if="canUpdateWorkOrder"
                >
                  <v-list-item-title class="text-subtitle-2">
                    Edit
                  </v-list-item-title>
                </v-list-item>

                <v-list-item
                  @click="confirmDeleteWorkOrder(selectedWorkOrder)"
                  class="text-red"
                  v-if="canDeleteWorkOrder"
                >
                  <v-list-item-title class="text-subtitle-2">
                    Delete
                  </v-list-item-title>
                </v-list-item>
              </v-list>
            </v-menu>
          </v-col>
        </v-row>
      </v-toolbar>
    </v-card>
  </v-dialog>
</template>

<script setup lang="ts">
import { useTheme } from "vuetify";
const emit = defineEmits(["click:create", "update:pagination"]);

const props = defineProps({
  detailRoute: {
    type: String,
    default: "index",
  },
  orgId: {
    type: String,
    default: "",
  },
  customerId: {
    type: String,
    default: "",
  },
  siteId: {
    type: String,
    default: "",
  },
  canCreateWorkOrder: {
    type: Boolean,
    default: false,
  },
  canViewWorkOrders: {
    type: Boolean,
    default: false,
  },
  canViewWorkOrderDetails: {
    type: Boolean,
    default: false,
  },
  canDeleteWorkOrder: {
    type: Boolean,
    default: false,
  },
  canUpdateWorkOrder: {
    type: Boolean,
    default: false,
  },
  category: {
    type: String,
    default: "",
  },
});

const theme = useTheme().name;
const showCreateDialog = ref(false);
const isEditMode = ref(false);
const erroredImages = ref<string[]>([]);

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

const { getColorStatus, formatDate, debounce, formatDateDDMMYYYYLocal } =
  useUtils();

const _workOrder = ref<TWorkOrderCreate>({
  attachments: [],
  category: "",
  subject: "",
  location: "",
  description: "",
  highPriority: false,
  block: "",
  level: "",
  unit: "",
  serviceProvider: "",
  assignee: "",
  organization: "",
  site: "",
});

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

const headers: Array<Record<string, any>> = [
  { title: "Created By", value: "createdByName", align: "start" },
  { title: "Subject", value: "subject", align: "start" },
  { title: "Category", value: "category", align: "start" },
  { title: "Date", value: "createdAt", align: "start" },
  { title: "Status", value: "status", align: "start" },
  { title: "", value: "action-table", align: "end" },
];

const submitting = ref(false);
const selected = ref<string[]>([]);
const route = useRoute();
const { customers } = useCustomer();
const showDeleteDialog = ref(false);

const {
  getWorkOrders: _getWorkOrders,
  createWorkOrder,
  getWorkOrderById,
  updateWorkOrder,
  deleteWorkOrder,
} = useWorkOrder();

const page = ref(1);
const pages = ref(0);
const pageRange = ref("-- - -- of --");
const items = ref<Array<Record<string, any>>>([]);

const {
  data: getAllWorkOrderReq,
  refresh: getAllReqRefresh,
  status: getAllReqStatus,
} = useLazyAsyncData("get-all-work-orders-" + props.category, () =>
  _getWorkOrders({
    page: page.value,
    site: route.params.site as string,
    category: props.category,
    search: searchText.value || "",
  })
);

const loading = computed(() => getAllReqStatus.value === "pending");
const onNextPrevPageLoading = ref(false);

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

async function updatePage(pageVal: any) {
  onNextPrevPageLoading.value = true;
  page.value = pageVal;
  const response = await _getWorkOrders({
    page: page.value,
    site: route.params.site as string,
    category: props.category,
  });
  if (response) {
    items.value = response.items;
    pages.value = response.pages;
    pageRange.value = response.pageRange;
    onNextPrevPageLoading.value = false;
  }
}

function onSelectedUpdate(newSelected: string[]) {
  selected.value = newSelected;
}

function handleRowClick(row: any) {
  const org = useRoute().params.org || "defaultOrg";
  const site = useRoute().params.site || "defaultSite";
  const id = row._id;
  useRouter().push({
    name: "work-order-details",
    params: {
      org,
      site,
      id,
    },
  });
}

function resetWorkOrderForm() {
  _workOrder.value = {
    attachments: [],
    category: "",
    subject: "",
    location: "",
    description: "",
    highPriority: false,
    block: "",
    level: "",
    unit: "",
    serviceProvider: "",
    assignee: "",
    organization: "",
    site: "",
  };
}

function handleCloseDialog() {
  resetWorkOrderForm();
  isEditMode.value = false;
  showCreateDialog.value = false;
}

const serviceProviders = ref<
  Array<{ title: string; value: string; subtitle: string }>
>([]);

const { getBySiteAsServiceProvider } = useCustomerSite();

const { data: getAllReq } = useLazyAsyncData(
  "get-by-site-as-service-provider",
  () => getBySiteAsServiceProvider(useRoute().params.site as string)
);

watchEffect(() => {
  if (getAllReq.value) {
    serviceProviders.value = getAllReq.value.map((i: any) => ({
      title: i.nature.replace(/_/g, " "),
      subtitle: i.title,
      value: i.nature,
    }));
  }
});

const { addFile, deleteFile: _deleteFile } = useFile();

const API_DO_STORAGE_ENDPOINT =
  useRuntimeConfig().public.API_DO_STORAGE_ENDPOINT;

async function handleFileAdded(file: File) {
  try {
    const res = await addFile(file);
    const uploadedId = res?.id;
    if (uploadedId) {
      // const url = `${API_DO_STORAGE_ENDPOINT}/${uploadedId}`;
      const url = `${uploadedId}`;
      _workOrder.value.attachments = _workOrder.value.attachments ?? [];
      _workOrder.value.attachments.push(url);
    }
  } catch (error) {
    console.error("Error uploading file:", error);
    showMessage("Failed to upload file", "error");
  }
}

async function deleteFile(value: string) {
  try {
    await _deleteFile(value);
    _workOrder.value.attachments = (_workOrder.value.attachments ?? []).filter(
      (file) => file !== value
    );
  } catch (error) {
    console.log(error);
    showMessage("Failed to delete file", "error");
  }
}

const _workOrderId = ref<string | null>(null);

const isSubmitting = ref(false);

async function submitWorkOrder() {
  try {
    isSubmitting.value = true;

    const payload = {
      ..._workOrder.value,
      organization: route.params.org as string,
      site: route.params.site as string,
    };

    let res: Record<string, any> = {};

    if (isEditMode.value) {
      res = await updateWorkOrder(_workOrderId.value as string, payload);
    } else {
      res = await createWorkOrder(payload);
    }

    showMessage(res.message, "success");
    showCreateDialog.value = false;
    await getAllReqRefresh();
    resetWorkOrderForm();
  } catch (err) {
    showMessage((err as Error).message, "error");
  } finally {
    isSubmitting.value = false;
  }
}

function onViewWorkOrder(item: any) {
  const route = useRoute();
  const org = route.params.org;
  const customer = route.params.customer;
  const site = route.params.site;
  const id = item._id;
  useRouter().push({
    name: props.detailRoute,
    params: { org, site, id },
  });
}

async function editWorkOrder(item: any) {
  try {
    const _workOrders = await getWorkOrderById(item._id);
    _workOrder.value = {
      attachments: (_workOrders.attachments || []) as string[],
      category: _workOrders.category || "",
      subject: _workOrders.subject || "",
      description: _workOrders.description || "",
      highPriority: _workOrders.highPriority || false,
      unit: _workOrders.location || "",
    };
    _workOrderId.value = item._id;
    isEditMode.value = true;
    showCreateDialog.value = true;
    dialogPreview.value = false;
  } catch (error) {
    showMessage("Failed to load full work order", "error");
  }
}

async function _updateWorkOrder() {}

function confirmDeleteWorkOrder(item: any) {
  workOrderToDelete.value = item;
  showDeleteDialog.value = true;
}

const workOrderToDelete = ref<any>(null);

async function submitDelete() {
  if (!workOrderToDelete.value) return;
  submitting.value = true;
  try {
    const response = await deleteWorkOrder(workOrderToDelete.value._id);
    showMessage(response.message, "success");
    await getAllReqRefresh();
  } catch (error) {
    console.error("Failed to delete work order:", error);
    showMessage("Failed to delete work order!", "error");
  } finally {
    submitting.value = false;
    showDeleteDialog.value = false;
    workOrderToDelete.value = null;
    dialogPreview.value = false;
  }
}

function tableRowClickHandler(_: any, data: any) {
  selectedWorkOrder.value = data.item;
  dialogPreview.value = true;
}

const dialogPreview = ref(false);
const selectedWorkOrder = ref<TWorkOrder | null>(null);
const searchText = ref("");

const debounceSearch = debounce(getAllReqRefresh, 500);

watch(
  () => searchText.value,
  () => {
    debounceSearch();
  }
);
</script>
