<template>
  <v-row no-gutters>
    <v-col cols="12" class="mb-2">
      <v-row no-gutters align="center">
        <v-text-field
          v-model="searchText"
          placeholder="Search feedback..."
          variant="outlined"
          density="comfortable"
          clearable
          hide-details
        />
        <v-autocomplete
          v-model="filterByStatus"
          :items="['All', 'To-Do', 'In-Progress', 'For Review', 'Completed']"
          label="Filter by status"
          hide-details
          class="ml-2"
          style="max-width: 250px"
        />
        <v-text-field
          v-model="startDate"
          :value="standardFormatDate(startDate)"
          label="Start Date"
          readonly
          hide-details
          class="ml-2"
          append-inner-icon="mdi-calendar"
          style="max-width: 250px"
          @click="startDateDialog = true"
        />
        <v-dialog v-model="startDateDialog" max-width="355">
          <v-card>
            <v-date-picker v-model="startDate" width="320" :locale="locale" />
          </v-card>
        </v-dialog>
        <v-text-field
          v-model="endDate"
          :value="standardFormatDate(endDate)"
          label="End Date"
          readonly
          hide-details
          class="ml-2"
          append-inner-icon="mdi-calendar"
          style="max-width: 250px"
          @click="endDateDialog = true"
        />
        <v-dialog v-model="endDateDialog" max-width="355">
          <v-card>
            <v-date-picker v-model="endDate" width="320" :locale="locale" />
          </v-card>
        </v-dialog>
        <v-btn
          v-if="canCreateFeedback"
          text="create feedback"
          class="text-none text-capitalize ml-2"
          rounded="pill"
          variant="tonal"
          size="large"
          @click="showCreateDialog = true"
        />
      </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="(page = 1), refreshFeedbacks()"
            >
              <v-icon icon="mdi-refresh" />
            </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 #item.createdBy="{ item, index }">
            <v-avatar
              v-if="item?.createdBy?.name"
              size="small"
              :color="materialColors[index % materialColors.length]"
              class="text-subtitle-2 mr-1 mr-md-4"
            >
              {{ getInitial(item?.createdBy?.name) ?? "" }}
            </v-avatar>
            {{ item?.createdBy?.name ?? "N/A" }}
          </template>
          <template #item.subject="{ item }">
            {{ item.subject || "N/A" }}
            <v-tooltip text="High Priority" location="end">
              <template v-slot:activator="{ props }">
                <v-icon
                  v-if="item.highPriority"
                  icon="mdi-alert-circle-outline"
                  color="red"
                  class="mb-1"
                  size="large"
                  v-bind="props"
                />
              </template>
            </v-tooltip>
          </template>
          <template #item.createdAt="{ value }">
            <v-icon icon="mdi-calendar-month-outline" />
            {{ standardFormatDateTime(value || "") }}
          </template>
          <template #item.status="{ value }">
            <span class="d-inline-block text-truncate">
              <v-chip
                :color="getStatusColor(value ?? '')"
                class="pa-5 text-capitalize text-center whitespace-nowrap text-body-1"
                variant="flat"
              >
                {{ value }}
              </v-chip>
            </span>
          </template>
          <template #item.assigneeInfo="{ item, index }">
            <!-- <span v-if="!item.assigneeInfo">
              <v-btn
                :block="$vuetify.display.xs"
                text="accept"
                variant="flat"
                color="primary"
                :class="`text-${$vuetify.display.xs ? 'h5' : 'body-1'}`"
                :disabled="canAccept(item.raw) ? false : true"
                @click.stop="accept(item.raw)"
              />
            </span> -->
            <span v-if="item.assigneeInfo" class="mt-1 text-wrap">
              <v-avatar
                size="small"
                :color="materialColors[index % materialColors.length]"
                class="mr-2 text-white"
              >
                {{
                  getInitial(
                    `${item.assigneeInfo?.givenName ?? ""} ${
                      item.assigneeInfo?.surname ?? ""
                    }`
                  ) || ""
                }}
              </v-avatar>
              {{
                `${item.assigneeInfo?.givenName ?? ""} ${
                  item.assigneeInfo?.surname ?? ""
                }` || "N/A"
              }}
            </span>
            <span v-else class="mt-1 text-wrap"> Not Assigned </span>
          </template>
        </v-data-table>
      </v-card>
    </v-col>
  </v-row>

  <!-- <FeedbackForm
    v-model="showCreateDialog"
    :feedback="_feedback"
    :is-edit-mode="isEditMode"
    :loading="submitting"
    :categories="serviceProviders"
    :errored-images="erroredImages"
    :max-files="5"
    :message-fn="showMessage"
    @close="handleCloseDialog"
    @submit="submitFeedback"
    @file-added="handleFileAdded"
    @file-deleted="deleteFile"
  /> -->

  <!-- create feeback dialog -->
  <v-dialog
    v-model="showCreateDialog"
    transition="dialog-bottom-transition"
    style="max-width: 650px"
  >
    <v-card class="rounded-lg pa-0">
      <v-toolbar flat class="rounded-tl-lg rounded-tr-lg">
        <span class="ml-6 font-weight-bold text-1-4rem"> Create Feedback </span>
        <v-spacer />
        <v-btn @click="showCreateDialog = false">
          <v-icon icon="mdi-close" size="40" />
        </v-btn>
      </v-toolbar>

      <v-row no-gutters class="pa-8">
        <v-col cols="12" class="text-center">
          <Carousel
            v-if="attachedFiles && attachedFiles.length > 0"
            :data-files="
              attachedFiles.map((file) => ({
                name: file.data.name,
                data: file.data,
                progress: 100,
                type: file.data.type,
                url: file.url,
              }))
            "
            :clickable="true"
            :img-editable="true"
            @on-file-edit="onImageEdited"
            :img-delete="true"
            @on-file-delete="removeFile"
          />
          <span v-else class="font-weight-bold text-subtitle-1">
            No attached image(s) found.
          </span>
        </v-col>

        <v-col cols="12" class="mt-6">
          <div class="text-subtitle-1 text-medium-emphasis">
            Attach image (Optional)
          </div>
          <FileInput
            :init-files="attachedFiles.map((file) => file.data)"
            @update:files="handleFileUpdate"
            @on-clear="attachedFiles = []"
          />
        </v-col>

        <v-col cols="12" class="my-2">
          <div class="text-subtitle-1 text-medium-emphasis">
            Subject
            <span class="text-red">* (Required)</span>
          </div>
          <v-combobox
            v-model="_feedback.subject"
            :items="subjectOptions"
            density="comfortable"
            placeholder="Enter subject"
            clearable
            :filter-keys="['title', 'description']"
            :persistent-hint="false"
            hide-details
          >
            <template v-slot:item="{ props, item }">
              <v-row no-gutters v-bind="props" class="px-3">
                <v-col cols="12" class="pa-2">
                  <span class="font-weight-bold">
                    {{ item.raw.title }}
                  </span>
                  <span
                    class="d-flex align-center flex-wrap mx-auto px-4 text-caption"
                  >
                    {{ item.raw.description }}
                  </span>
                </v-col>
              </v-row>
            </template>
          </v-combobox>
        </v-col>

        <v-col cols="12" class="mb-2">
          <div class="text-subtitle-1 text-medium-emphasis">
            Location
            <span class="text-red">* (Required)</span>
          </div>
          <v-text-field
            v-model="_feedback.location"
            density="comfortable"
            placeholder="Enter location"
            clearable
            :persistent-hint="false"
          />
        </v-col>

        <v-col cols="12">
          <div class="text-subtitle-1 text-medium-emphasis">
            Description
            <span class="text-red">* (Required)</span>
          </div>
          <v-textarea
            v-model="_feedback.description"
            density="comfortable"
            placeholder="Enter description"
            clearable
            :persistent-hint="false"
            no-resize
          ></v-textarea>
        </v-col>

        <!-- <v-col cols="12" class="mb-4">
          <v-btn
            color="primary"
            height="auto"
            class="mb-4"
            variant="flat"
            @click="attachWorkOrderDialog = true"
          >
            <div class="d-flex justify-space-between align-center w-100 py-2">
              <v-icon
                icon="mdi-check-circle-outline"
                size="50"
                :color="attachWorkOrderForm.attachWorkOrder && 'green'"
              />
              <span class="text-wrap ml-4"> Create and Attach Work Order </span>
            </div>
          </v-btn>
        </v-col> -->

        <v-col cols="12">
          <v-btn
            text="submit"
            block
            size="large"
            class="font-weight-bold"
            color="primary"
            :disabled="isFileUploading || isSubmitting"
            @click="submit()"
            :loading="isFileUploading || isSubmitting"
          />
        </v-col>
      </v-row>
    </v-card>
  </v-dialog>

  <!-- attach work order dialog -->
  <!-- <v-dialog
    v-model="attachWorkOrderDialog"
    transition="dialog-bottom-transition"
    style="max-width: 650px"
  >
    <v-card class="rounded-lg">
      <v-toolbar>
        <span class="ml-6 font-weight-bold">
          Create and Attach Work Order
        </span>
        <v-spacer />
        <v-btn @click="attachWorkOrderDialog = false">
          <v-icon icon="mdi-close" size="40" />
        </v-btn>
      </v-toolbar>

      <v-col cols="12" class="px-4">
        <v-textarea
          v-model="attachWorkOrderForm.description"
          label="Email"
          autocomplete="email"
          density="default"
          class="pt-0 mt-0"
          hide-details
          clearable
        >
          <template v-slot:label>
            Description
            <span class="text-error"> (Required)*</span>
          </template>
        </v-textarea>
        <v-checkbox
          v-model="attachWorkOrderForm.isHighPriority"
          label="Set Work Order as High Priority (Optional)"
          class="mb-0 pb-1 mb-n1 ml-n2"
          hide-details
        />
      </v-col>

      <v-col cols="12" class="mb-2 px-4">
        <v-btn
          block
          :text="attachWorkOrderForm.attachWorkOrder ? 'detach' : 'attach'"
          class="rounded-lg"
          color="primary"
          height="40px"
          elevation="0"
          @click="attachWorkOrder()"
        />
      </v-col>
    </v-card>
  </v-dialog> -->

  <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 feedback? </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="canViewFeedback"
  >
    <v-card width="100%">
      <v-card-text style="max-height: 100vh; overflow-y: auto" class="pb-0">
        <v-row no-gutters v-if="selectedFeedback" class="mb-4">
          <v-col cols="12">
            <strong>Subject:</strong> {{ selectedFeedback.subject }}
          </v-col>
          <v-col cols="12">
            <strong>Category:</strong>
            {{ selectedFeedback.category }}
          </v-col>
          <v-col cols="12">
            <strong>Status:</strong>
            {{ selectedFeedback.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
                  v-if="canViewFeedbackDetails"
                  @click="onViewFeedback(selectedFeedback)"
                >
                  <v-list-item-title class="text-subtitle-2">
                    View
                  </v-list-item-title>
                </v-list-item>
                <v-list-item
                  v-if="canUpdateFeedback"
                  @click="editFeedback(selectedFeedback)"
                >
                  <v-list-item-title class="text-subtitle-2">
                    Edit
                  </v-list-item-title>
                </v-list-item>

                <v-list-item
                  v-if="canDeleteFeedback"
                  @click="confirmDeleteFeedback(selectedFeedback)"
                  class="text-red"
                >
                  <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
  >

  <!-- accept dialog -->
  <v-dialog
    v-model="acceptDialog"
    transition="dialog-bottom-transition"
    style="max-width: 650px"
  >
    <v-card class="rounded-lg pa-0">
      <v-toolbar flat class="rounded-tl-lg rounded-tr-lg">
        <span class="ml-6 font-weight-bold"> Accept Feedback </span>
        <v-spacer />
        <v-btn @click="acceptDialog = false">
          <v-icon icon="mdi-close" size="40" />
        </v-btn>
      </v-toolbar>

      <v-card-text class="text-center text-h6">
        Are you sure you want to accept this feedback?
      </v-card-text>

      <v-col cols="12" class="mb-2 px-4">
        <v-btn
          text="confirm"
          class="rounded-lg"
          color="primary"
          block
          size="x-large"
          elevation="0"
          @click="handleAccept()"
        />
      </v-col>
    </v-card>
  </v-dialog>
</template>

<script setup lang="ts">
import moment from "moment-timezone";

const props = defineProps({
  detailRoute: {
    type: String,
    default: "index",
  },
  permissions: {
    type: Object,
    required: true,
    default: () => ({}),
  },
  orgId: {
    type: String,
    default: "",
  },
  customerId: {
    type: String,
    default: "",
  },
  siteId: {
    type: String,
    default: "",
  },
  canCreateFeedback: {
    type: Boolean,
    default: false,
  },
  canViewFeedback: {
    type: Boolean,
    default: false,
  },
  canViewFeedbackDetails: {
    type: Boolean,
    default: false,
  },
  canDeleteFeedback: {
    type: Boolean,
    default: false,
  },
  canUpdateFeedback: {
    type: Boolean,
    default: false,
  },
  category: {
    type: String,
    default: "",
  },
});

const isEditMode = ref(false);
const showCreateDialog = ref(false);
const showDeleteDialog = ref(false);
const submitting = ref(false);
const message = ref("");
const messageColor = ref("");
const messageSnackbar = ref(false);

const { currentUser } = useLocalAuth();

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

// const { data: getAllReq } = useLazyAsyncData("get-all-service-providers", () =>
//   getAllServiceProvider({
//     siteId: useRoute().params.site as 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 _feedback = ref({
  subject: "",
  category: "",
  location: "",
  description: "",
  highPriority: false,
  attachments: [] as Array<{ _id: string; name: string; type: string }>,
  serviceProvider: "",
  assignee: "",
  organization: "",
  site: "",
});

const {
  getStatusColor,
  debounce,
  standardFormatDateTime,
  standardFormatDate,
  materialColors,
  getInitial,
  getImage,
} = useUtils();

const headers: Array<Record<string, any>> = [
  { title: "Name", value: "createdBy", align: "start" },
  { title: "Subject", value: "subject", align: "start" },
  { title: "Date", value: "createdAt", align: "start" },
  { title: "App", value: "app", align: "start" },
  { title: "Status", value: "status", align: "start" },
  { title: "Assignee", value: "assigneeInfo", align: "start" },
  { title: "", value: "action-table", align: "end" },
];

const route = useRoute();

const dialogPreview = ref(false);
const selectedFeedback = ref<TFeedback | null>(null);
const searchText = ref("");

const {
  getFeedbacks: _getFeedbacks,
  deleteFeedback,
  createFeedback,
  getFeedbackById,
  updateFeedback,
} = useFeedback();

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

const filterByStatus = ref("All");
const getPast30DaysDate = (): Date => {
  const today = new Date();
  const past30Days = new Date(today);
  past30Days.setDate(today.getDate() - 30);
  return past30Days;
};
const startDate = ref<any>(getPast30DaysDate());
const startDateDialog = ref(false);
const endDate = ref<any>(new Date());
const endDateDialog = ref(false);
const locale = "en";

const {
  data: feedbacks,
  status: getFeedbacksStatus,
  refresh: refreshFeedbacks,
} = useLazyAsyncData(
  "get-all-feedbacks",
  () =>
    _getFeedbacks({
      page: page.value,
      site: route.params.site as string,
      provider: currentUser.value.serviceProvider,
      ...(currentUser.value.type != "site" && {
        userId: currentUser.value._id,
      }),
      service: "Security",
      dateFrom: moment(startDate.value, "DD/MM/YYYY").startOf("day"),
      dateTo: moment(endDate.value, "DD/MM/YYYY").endOf("day"),
      search: searchText.value,
      status: filterByStatus.value == "All" ? "" : filterByStatus.value,
    }),
  {
    watch: [filterByStatus, searchText, page, startDate, endDate],
  }
);

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

  if (startDate.value) {
    startDateDialog.value = false;
  }

  if (endDate.value) {
    endDateDialog.value = false;
  }
});

const loading = computed(() => getFeedbacksStatus.value === "pending");

async function updatePage(pageVal: any) {
  page.value = pageVal;
}

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

async function editFeedback(item: any) {
  try {
    const _feedbacks = await getFeedbackById(item._id);
    _feedback.value = {
      attachments: (_feedbacks.attachments || []) as string[],
      category: _feedbacks.category || "",
      subject: _feedbacks.subject || "",
      location: _feedbacks.location || "",
      description: _feedbacks.description || "",
      organization: _feedbacks.organization || "",
      site: _feedbacks.site || "",
      highPriority: _feedbacks.highPriority || false,
      serviceProvider: _feedbacks.serviceProvider || "",
      assignee: _feedbacks.assignee || "",
    };
    _feedbackId.value = item._id;
    isEditMode.value = true;
    showCreateDialog.value = true;
    dialogPreview.value = false;
  } catch (error) {
    showMessage("Failed to load full feedback", "error");
  }
}

function onViewFeedback(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 },
  });
  dialogPreview.value = false;
}

function confirmDeleteFeedback(item: any) {
  feedbackToDelete.value = item;
  showDeleteDialog.value = true;
}

const feedbackToDelete = ref<any>(null);

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

const resetFeedbackForm = () => {
  _feedback.value = {
    attachments: [] as Array<{ _id: string; name: string; type: string }>,
    category: "",
    subject: "",
    location: "",
    description: "",
    highPriority: false,
    serviceProvider: "",
    assignee: "",
    organization: "",
    site: "",
  };
};

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

// const _feedbackId = ref<string | null>(null);

// async function _createFeedback(organization: string, site: string) {
//   const userId = getUserFromCookie();

//   const createPayload: TFeedbackCreate = {
//     subject: _feedback.value.subject,
//     category: _feedback.value.category,
//     location: _feedback.value.location,
//     description: _feedback.value.description,
//     highPriority: _feedback.value.highPriority ?? false,
//     attachments: _feedback.value.attachments || [],
//     serviceProvider: _feedback.value.serviceProvider || "",
//     assignee: _feedback.value.assignee || "",
//     organization,
//     site,
//     ...(userId !== null ? { createdBy: userId } : {}),
//   };

//   const response = await createFeedback(createPayload);
//   showMessage(response?.message || "Feedback created successfully", "success");
// }

// async function _updateFeedback() {
//   if (!_feedbackId.value) return;

//   const updatePayload: TFeedbackUpdate = {
//     subject: _feedback.value.subject,
//     category: _feedback.value.category,
//     location: _feedback.value.location,
//     description: _feedback.value.description,
//     attachments: _feedback.value.attachments || [],
//   };

//   const response = await updateFeedback(_feedbackId.value, updatePayload);
//   showMessage(response?.message || "Feedback updated successfully", "success");
// }

// const submitFeedback = async () => {
//   submitting.value = true;

//   try {
//     const organization = route.params.org as string;
//     const site = route.params.site as string;

//     if (isEditMode.value) {
//       await _updateFeedback();
//     } else {
//       await _createFeedback(organization, site);
//     }

//     showCreateDialog.value = false;
//     await refreshFeedbacks();
//     resetFeedbackForm();
//   } catch (error) {
//     console.error(error);
//     showMessage("Something went wrong", "error");
//   } finally {
//     submitting.value = false;
//   }
// };

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

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 = `${uploadedId}`;
//       _feedback.value.attachments = _feedback.value.attachments ?? [];
//       _feedback.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);
//     _feedback.value.attachments = (_feedback.value.attachments ?? []).filter(
//       (file) => file !== value
//     );
//   } catch (error) {
//     console.log(error);
//     showMessage("Failed to delete file", "error");
//   }
// }

const { serviceProviderCategories, getServiceProviderCategories } =
  useServiceProvider();

const categories = computed(() =>
  serviceProviderCategories.value.map((name) => ({
    title: name.charAt(0).toUpperCase() + name.slice(1),
    value: name,
  }))
);

function tableRowClickHandler(_: any, data: any) {
  // console.log(data.item);
  selectedFeedback.value = data.item;
  dialogPreview.value = true;
}

getServiceProviderCategories();

onMounted(() => {
  _feedback.value.description = "";
  _feedback.value.location = "";
  _feedback.value.subject = "";
  _feedback.value.attachments = [];
});

const acceptDialog = ref(false);
const feedbackData = ref();

function canAccept(feedBack: any) {
  return (
    feedBack.provider === currentUser.value?.serviceProvider ||
    (feedBack.subject &&
      feedBack.subject.toLowerCase().includes("security") &&
      !feedBack.provider)
  );
}
async function accept(feedBack: any) {
  acceptDialog.value = true;
  feedbackData.value = feedBack;
}
async function handleAccept() {
  if (
    feedbackData.value.provider === currentUser.value?.serviceProvider ||
    (feedbackData.value.subject &&
      feedbackData.value.subject.toLowerCase().includes("security") &&
      !feedbackData.value.provider)
  ) {
    try {
      const data: any = {
        _id: feedbackData.value._id,
        statusUpdate: {
          status: "In-Progress",
          updatedById: currentUser.value._id,
          updatedByName: `${currentUser.value.givenName} ${currentUser.value.surname}`,
          assignee: currentUser.value._id,
          provider: currentUser.value?.serviceProvider,
        },
      };

      // await updateStatusFeedback(data);

      acceptDialog.value = false;
      //  changePath(feedbackData.value);
    } catch (error) {
      showMessage(error as string, "error");
    }
  } else {
    return showMessage(
      "Only assigned Provider can accept this feedback.",
      "error"
    );
  }
}

const subjectOptions = computed(() => {
  return [
    {
      title: "Facilities",
      description:
        "Shared amenities like gym, pool, BBQ pits, and function rooms.",
    },
    {
      title: "Building Facade",
      description:
        "Exterior walls, paint, cladding, signage, and overall appearance.",
    },
    {
      title: "Security",
      description:
        "Guard services, access control, patrols, and visitor management.",
    },
    {
      title: "Cleaning",
      description:
        "Cleanliness of lobbies, corridors, lifts, bins, and common areas.",
    },
    {
      title: "Landscape",
      description: "Condition of plants, lawns, trees, and garden maintenance.",
    },
    {
      title: "Pest Control",
      description:
        "Effectiveness of measures against insects, rodents, and pests.",
    },
    {
      title: "Water Features",
      description:
        "Operation and cleanliness of fountains, ponds, and pools (non-swimming).",
    },
    {
      title: "Car Park",
      description:
        "Parking availability, markings, lighting, and barrier systems.",
    },
    {
      title: "Lift",
      description:
        "Lift reliability, speed, cleanliness, ventilation, and downtime.",
    },
    {
      title: "Security Systems",
      description: "CCTV, intercoms, access cards, and gate/door sensors.",
    },
    {
      title: "Others",
      description:
        "Any issues or feedback not covered by the categories above.",
    },
  ]
    .filter((item) => item.title !== "Others")
    .sort((a, b) => a.title.localeCompare(b.title))
    .concat({
      title: "Others",
      description:
        "Any issues or feedback not covered by the categories above.",
    });
});

const isFileUploading = ref<boolean>(false);
type TFile = {
  name: string;
  data: File;
  progress: number;
  url?: string;
  type?: string;
  id?: string;
};
const attachedFiles = ref<TFile[]>([]);

const handleFileUpdate = async (
  files: Array<{ data: File; name: string; url: string }>
) => {
  for (const file of files) {
    attachedFiles.value.push(file);
  }
};

const onImageEdited = async (url: string, idx: number) => {
  const response = await getImage(url);
  if (!response) return;
  attachedFiles.value[idx].data = new File(
    [response],
    attachedFiles.value[idx].data?.name,
    { type: attachedFiles.value[idx].data?.type }
  );
  attachedFiles.value[idx].url = url;
};

function removeFile(url: string) {
  const newFiles = attachedFiles.value.filter((item: any) => item.url !== url);

  attachedFiles.value = [];
  nextTick(() => {
    attachedFiles.value = newFiles;
  });
}

const attachWorkOrderDialog = ref(false);
const attachWorkOrderForm = ref<any>({
  description: "",
  isHighPriority: false,
  attachWorkOrder: false,
});

const attachWorkOrder = () => {
  attachWorkOrderForm.value.attachWorkOrder =
    !attachWorkOrderForm.value.attachWorkOrder;
  attachWorkOrderDialog.value = false;
};

const isSubmitting = ref<boolean>(false);

async function submit() {
  if (attachedFiles.value && attachedFiles.value?.length) {
    isFileUploading.value = true;
    for (const file of attachedFiles.value) {
      const res = await addFile(file.data);

      const uploadedId = res?.id;
      if (uploadedId) {
        _feedback.value.attachments = _feedback.value.attachments ?? [];
        _feedback.value.attachments.push(uploadedId);
      }
    }
    isFileUploading.value = false;
  }

  try {
    isSubmitting.value = true;

    const result = await createFeedback({
      createdBy: currentUser.value._id,
      description: _feedback.value.description,
      attachments: _feedback.value.attachments,
      site: route.params.site as string,
      organization: route.params.org as string,
      subject: _feedback.value.subject?.title || _feedback.value.subject,
      location: _feedback.value.location,
      app: "MA",
      ...(attachWorkOrderForm.value.attachWorkOrder && {
        provider: _feedback.value.serviceProvider,
        workOrder: {
          isHighPriority: attachWorkOrderForm.value.isHighPriority,
          description: attachWorkOrderForm.value.description,
        },
      }),
    });
    handleCloseDialog();
    await refreshFeedbacks();
    showMessage(result.message as string, "success");
  } catch (error) {
    showMessage(error as string, "error");
  } finally {
    isSubmitting.value = false;
  }
}
</script>
