<template>
  <div class="feedback-detail-wrapper">
    <v-row no-gutters class="fill-height">

      <v-col cols="12" xl="7" lg="7" md="7" class="fill-height">
        <div class="panel-container border-e">
          <ChatMessage :type="'feedback'" />
        </div>
      </v-col>

      <v-col cols="12" xl="5" lg="5" md="5" class="fill-height">
        <div class="panel-container">
          <ChatInformation
            :item="feedback"
            :service-providers="_serviceProviders"
            :type="'feedback'"
            @edit="openEditDialog"
            @mark-complete-request="showCompleteDialog = true"
            @delete="showDeleteDialog = true"
            @update-work-order-id="updateWorkOrderId"
          />
        </div>
      </v-col>
    </v-row>
  </div>

  <FeedbackForm
    v-model="showCreateDialog"
    :feedback="_feedback"
    @update:feedback="(val: TFeedbackUpdate) => (_feedback = val)"
    :is-edit-mode="isEditMode"
    :loading="submitting"
    :categories="categories"
    :theme="'light'"
    :errored-images="[]"
    :max-files="5"
    :message-fn="(msg:any) => console.log(msg)"
    @close="handleCloseDialog"
    @submit="submitFeedback"
    @file-added="handleFileAdded"
    @file-deleted="deleteFile"
  />

  <v-dialog v-model="showCompleteDialog" max-width="450px">
    <v-card class="rounded-xl pa-0 d-flex flex-column" style="max-height: 90vh">
      <!-- Title Bar -->
      <v-card-title class="d-flex justify-space-between align-center pa-4">
        <span class="text-h6">Completion Confirmation</span>
        <v-icon @click="showCompleteDialog = false">mdi-close</v-icon>
      </v-card-title>

      <!-- Scrollable form content -->
      <v-card-text class="px-4 pt-0 overflow-y-auto" style="flex: 1 1 auto">
        <InputFile
          ref="completionFileInput"
          :attachments="completionAttachments"
          :max-files="3"
          :errored-images="[]"
          @add="handleCompletionFileAdded"
          @delete="handleCompletionFileDeleted"
        />

        <div class="mb-4">
          <label class="text-subtitle-2 mb-1 d-block">
            Full Name <span class="text-error">*</span>
          </label>
          <v-text-field
            placeholder="Enter your full name"
            variant="outlined"
            density="comfortable"
            v-model="feedback.name"
            hide-details
            class="mt-1"
          ></v-text-field>
        </div>

        <div class="mb-4">
          <label class="text-subtitle-2 mb-1 d-block">
            Signature <span class="text-error">*</span>
          </label>
          <SignaturePad v-model="feedback.signature" />
        </div>
      </v-card-text>

      <v-card-actions class="px-4 pb-4">
        <v-btn
          block
          color="primary-button"
          size="large"
          variant="flat"
          :loading="completeLoading"
          @click="markFeedbackAsComplete"
          class="text-capitalize"
        >
          Mark as complete
        </v-btn>
      </v-card-actions>
    </v-card>
  </v-dialog>

  <ConfirmDialog
    v-model="showDeleteDialog"
    :loading="deleteLoading"
    @submit="deleteFeedback"
    :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 text-capitalize align-center justify-center"
        @click="deleteFeedback"
        :loading="deleteLoading"
        block
      >
        Confirm
      </v-btn>
    </template>
  </ConfirmDialog>

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

<script lang="ts" setup>
const route = useRoute();
const id = route.params.id;

const {
  feedback,
  getFeedbackById,
  feedbacks,
  getFeedbacks: _getFeedbacks,
  updateFeedback,
  updateFeedbackServiceProvider,
  updateStatusComplete,
  deleteFeedback: _deleteFeedback,
} = useFeedback();

const { getServiceProviderNames } = useServiceProvider();

const _getFeedbackById = async () => {
  try {
    const data = await getFeedbackById(id as string);
    feedback.value = data;
  } catch (error) {
    console.error("Error fetching feedback:", error);
  }
};
const page = ref(1);
const pages = ref(0);
const pageRange = ref("-- - -- of --");
const items = ref<Array<Record<string, any>>>([]);

const {
  data: getAllFeedbackReq,
  status: getAllReqStatus,
  refresh: getAllReqRefresh,
} = useLazyAsyncData("get-all-feedbacks", () =>
  _getFeedbacks({
    page: page.value,
    site: route.params.site as string,
  })
);

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

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

const handleSelectFeedback = async (id: string) => {
  try {
    await useRouter().push({ params: { id } });

    const data = await getFeedbackById(id);
    feedback.value = data;
  } catch (error) {
    console.error("Error selecting feedback:", error);
  }
};

_getFeedbackById();

const _serviceProviders = ref<TServiceProviderName[]>([]);

const _getServiceProviderNames = async () => {
  try {
    const response = await getServiceProviderNames();
    if (!response) return;

    _serviceProviders.value = response.items.map((provider) => ({
      _id: provider._id as string,
      name: provider.name,
    }));
  } catch (error) {
    console.error("Error fetching service providers:", error);
  }
};

_getServiceProviderNames();

const showCreateDialog = ref(false);
const showCompleteDialog = ref(false);
const showDeleteDialog = ref(false);
const completeNotes = ref("");

const completionAttachments = ref<string[]>([]);

const completeLoading = ref(false);
const deleteLoading = ref(false);

const isEditMode = ref(false);

const _feedback = ref<TFeedbackCreate>({
  attachments: [],
  category: "",
  subject: "",
  location: "",
  description: "",
});

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

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

function openEditDialog() {
  isEditMode.value = true;
  _feedback.value = { ...feedback.value };
  showCreateDialog.value = true;
}

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

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

async function handleFileAdded(file: File) {
  try {
    const res = await addFile(file);

    if (res?.id && res?.name) {
      const url = `https://seven365-storage.sgp1.cdn.digitaloceanspaces.com/dev/${res.id}`;

      _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) {
    showMessage("Failed to delete file", "error");
  }
}

const resetFeedbackForm = () => {
  _feedback.value = {
    attachments: [],
    category: "",
    subject: "",
    location: "",
    description: "",
  };
};

const completionFileInput = ref<any>(null);
const completionFileNames = ref<Record<string, string>>({});

async function handleCompletionFileAdded(file: File) {
  try {
    file.name;

    const res = await addFile(file);

    const uploadedId = res?.id;

    if (uploadedId) {
      const url = `${uploadedId}`;

      completionAttachments.value = completionAttachments.value ?? [];
      completionAttachments.value.push(url);
    }

    // if (res?.id && res?.name) {
    //   const url = `https://seven365-storage.sgp1.cdn.digitaloceanspaces.com/dev/${res.id}`;

    //   if (!completionAttachments.value) {
    //     completionAttachments.value = [];
    //   }

    //   completionAttachments.value.push(url);

    //   completionFileNames.value[url] = res.name;

    //   if (completionFileInput.value) {
    //     completionFileInput.value.updateFileName(url, res.name);
    //   }
    // }

    console.log("completionAttachments.value", completionAttachments.value);
  } catch (error) {
    console.error("Error uploading completion file:", error);
    showMessage("Failed to upload file", "error");
  }
}

async function handleCompletionFileDeleted(value: string) {
  try {
    await _deleteFile(value);

    completionAttachments.value = completionAttachments.value || [];

    completionAttachments.value = completionAttachments.value.filter(
      (file) => file !== value
    );
  } catch (error) {
    console.log(error);
    showMessage("Failed to delete file", "error");
  }
}

const resetCompletionForm = () => {
  completionAttachments.value = [];

  if (completionFileInput.value) {
    completionFileInput.value.clearFiles?.();
  }

  feedback.value.name = "";
  feedback.value.signature = "";
};

const { serviceProviderCategories, getServiceProviderCategories } =
  useServiceProvider();

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

getServiceProviderCategories();
async function markFeedbackAsComplete() {
  if (!feedback.value?._id) {
    console.warn("Update called without valid feedback ID.");
    return;
  }

  if (!feedback.value.name || !feedback.value.signature) {
    console.warn("Signature or name is missing:", feedback.value.signature);
    showMessage("Please provide both name and signature.", "error");
    return;
  }

  try {
    completeLoading.value = true;

    const payload: TFeedbackStatusComplete = {
      name: feedback.value.name,
      signature: feedback.value.signature,
      attachments: completionAttachments.value || [],
    };

    const response = await updateStatusComplete(feedback.value._id, payload);
    const message = response?.message || "Feedback marked as complete";
    showMessage(message, "success");

    showCompleteDialog.value = false;
    resetCompletionForm();
    await _getFeedbackById();
  } catch (error) {
    showMessage("Failed to mark feedback as complete", "error");
    console.error("Error updating feedback status:", error);
  } finally {
    completeLoading.value = false;
  }
}

async function deleteFeedback() {
  if (!feedback.value?._id) {
    console.warn("Delete called without valid feedback ID.");
    return;
  }

  try {
    deleteLoading.value = true;

    const response = await _deleteFeedback(feedback.value._id);
    const message = response?.message || "Feedback deleted successfully";
    showMessage(message, "success");

    showDeleteDialog.value = false;
    await _getFeedbacks();

    const org = useRoute().params.org || "customer1";
    const site = useRoute().params.site || "site1";

    await useRouter().push({
      name: "org-site-feedbacks",
      params: { org, site },
    });
  } catch (error) {
    showMessage("Failed to delete feedback", "error");
    console.error("Error deleting feedback:", error);
  } finally {
    deleteLoading.value = false;
  }
}

async function submitFeedback(payload: TFeedbackUpdate) {
  if (!isEditMode.value || !feedback.value?._id) {
    console.warn("Update called without valid edit mode or feedback ID.");
    return;
  }

  try {
    submitting.value = true;

    const payload = {
      category: _feedback.value.category,
      subject: _feedback.value.subject,
      location: _feedback.value.location,
      description: _feedback.value.description,
    };

    const response = await updateFeedback(feedback.value._id, payload);
    const message = response?.message || "Feedback updated successfully";
    showMessage(message, "success");

    showCreateDialog.value = false;
    await _getFeedbackById();

    resetFeedbackForm();
  } catch (error) {
    showMessage("Something went wrong", "error");
    console.error("Error updating feedback:", error);
  } finally {
    submitting.value = false;
  }
}

async function updateWorkOrderId(workOrderId: string) {
  const payload = {
    category: feedback.value.category,
    subject: feedback.value.subject,
    location: feedback.value.location,
    description: feedback.value.description,
    workOrderId: workOrderId,
  };
  const response = await updateFeedback(feedback.value._id, payload);
  const message =
    response?.message || "Feedback updated with Work Order Number successfully";
  showMessage(message, "success");

  showCreateDialog.value = false;
  await _getFeedbackById();

  resetFeedbackForm();
}
</script>

<style scoped>
.feedback-detail-wrapper {
  height: calc(100vh - 80px); /* Account for header and padding */
  max-height: calc(100vh - 80px);
  overflow: hidden;
  position: relative;
  background-color: rgb(var(--v-theme-surface));
}

.panel-container {
  height: 100%;
  max-height: 100%;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  background-color: rgb(var(--v-theme-surface));
}

.border-e {
  border-right: 1px solid rgba(var(--v-border-color), var(--v-border-opacity));
}

.fill-height {
  height: 100%;
  max-height: 100%;
  overflow: hidden;
}

/* Ensure the root row doesn't create scrolling */
.v-row.fill-height {
  margin: 0;
  height: 100%;
  max-height: 100%;
  overflow: hidden;
  align-items: stretch;
}

/* Better column spacing */
.v-col {
  padding: 0;
  display: flex;
  flex-direction: column;
}

/* Ensure responsive behavior */
@media (max-width: 1280px) {
  .feedback-detail-wrapper {
    height: calc(100vh - 72px);
    max-height: calc(100vh - 72px);
  }
}

@media (max-width: 960px) {
  .feedback-detail-wrapper {
    height: calc(100vh - 64px); /* Mobile header height */
    max-height: calc(100vh - 64px);
  }

  .border-e {
    border-right: none;
    border-bottom: 1px solid
      rgba(var(--v-border-color), var(--v-border-opacity));
  }

  .v-col {
    height: auto;
    min-height: 300px;
  }
}

/* Individual component styling */
:deep(.chat-navigation) {
  height: 100%;
  overflow-y: auto;
  background-color: rgb(var(--v-theme-surface));
}

:deep(.chat-message) {
  height: 100%;
  overflow-y: auto;
  background-color: rgb(var(--v-theme-surface));
}

:deep(.chat-information) {
  height: 100%;
  overflow-y: auto;
  background-color: rgb(var(--v-theme-surface));
  padding: 16px;
}

/* Smooth scrollbars */
:deep(*::-webkit-scrollbar) {
  width: 6px;
}

:deep(*::-webkit-scrollbar-track) {
  background: transparent;
}

:deep(*::-webkit-scrollbar-thumb) {
  background: rgba(var(--v-border-color), 0.3);
  border-radius: 3px;
}

:deep(*::-webkit-scrollbar-thumb:hover) {
  background: rgba(var(--v-border-color), 0.5);
}

/* Remove default margins/padding that might cause issues */
:deep(.v-container) {
  padding: 0;
  margin: 0;
  max-width: none;
}
</style>
