<template>
  <v-sheet
    elevation="1"
    rounded="0"
    class="fill-height d-flex flex-column"
    style="border-right: 1px solid #e0e0e0; border-top: 1px solid #e0e0e0"
  >
    <v-row class="pa-4">
      <v-sheet
        class="overflow-y-auto flex-grow-1"
        :style="{ height: 'calc(100vh - 250px)', overflowX: 'hidden' }"
      >
        <v-col
          cols="12"
          class="mb-2"
          style="position: sticky; top: 0; background-color: white; z-index: 1"
        >
          <h3 class="text-h6">
            {{ type === "workOrder" ? "Work Order" : "Feedback" }} Information
          </h3>
        </v-col>

        <v-col cols="12" class="text-center mb-0" v-if="item">
          <v-img
            v-if="item.attachments.length === 1"
            :src="`/api/public/${item.attachments[0]}`"
            height="200"
            cover
            class="rounded mb-2"
          />
          <v-carousel
            v-else-if="item.attachments.length > 1"
            hide-delimiter-background
            height="200"
            class="rounded mb-2"
            show-arrows
            cycle
          >
            <v-carousel-item
              v-for="(attachment, index) in item.attachments"
              :key="index"
            >
              <v-img
                :src="`/api/public/${attachment}`"
                cover
                class="w-100 h-100"
              />
            </v-carousel-item>
          </v-carousel>
        </v-col>

        <v-col cols="12" v-if="item">
          <v-row dense class="my-1" v-if="type === 'feedback'">
            <v-col cols="12" class="py-1"><strong>Subject:</strong></v-col>
            <v-col cols="12" class="py-1">
              {{ item.subject }}
            </v-col>
          </v-row>

          <v-divider />

          <v-row dense class="my-1 pr-4">
            <v-col cols="6" class="py-1"><strong>Category:</strong></v-col>
            <v-col cols="6" class="py-1 text-right text-capitalize">{{
              item.category
            }}</v-col>
          </v-row>

          <v-divider />

          <v-row dense class="my-1">
            <v-col cols="6" class="py-1"><strong>Location:</strong></v-col>
            <v-col cols="6" class="py-1 text-right">{{ item.location }}</v-col>
          </v-row>
          <v-divider />

          <v-row dense class="my-1" v-if="type === 'feedback'">
            <v-col cols="12" class="py-1"
              ><strong>Description Feedback:</strong></v-col
            >
            <v-col cols="12" class="py-1">
              {{ item.description }}
            </v-col>
          </v-row>
          <v-divider />

          <v-row dense class="my-1" v-if="type === 'workOrder'">
            <v-col cols="12" class="py-1"
              ><strong>Description Work Order:</strong></v-col
            >
            <v-col cols="12" class="py-1">
              {{ item.description || "No work order description available" }}
            </v-col>
          </v-row>
          <v-divider />

          <v-row dense class="my-1" v-if="type === 'feedback'">
            <v-col cols="6" class="py-1"
              ><strong>Work Order No.:</strong></v-col
            >
            <v-col v-if="item.workOrderNo" cols="6" class="py-1 text-right">
              <NuxtLink :to="showWorkOrderInfo(item.workOrderId)">{{
                item.workOrderNo
              }}</NuxtLink>
            </v-col>
            <v-col v-else cols="6" class="py-1 text-right">
              <v-btn
                class="text-none text-capitalize text-blue"
                rounded="pill"
                variant="flat"
                size="small"
                @click="openWorOrderCreateDialog()"
              >
                Create WorkOrder
              </v-btn>
            </v-col>
          </v-row>

          <v-row dense class="my-1" v-if="type === 'workOrder'">
            <v-col cols="6" class="py-1"
              ><strong>Work Order Number:</strong></v-col
            >
            <v-col v-if="item.workOrderNo" cols="6" class="py-1 text-right"
              >{{ item.workOrderNo }}
            </v-col>
          </v-row>

          <v-divider />

          <v-row dense class="my-1">
            <v-col cols="6" class="py-1"><strong>Status:</strong></v-col>
            <v-col cols="6" class="py-1 text-right">
              <v-chip
                :color="getColorStatus(item.status)"
                size="x-small"
                text-color="white"
              >
                {{ item.status }}
              </v-chip>
            </v-col>
          </v-row>

          <v-divider />

          <v-row dense class="my-1">
            <v-col cols="6" class="py-1"><strong>Created At:</strong></v-col>
            <v-col cols="6" class="py-1 text-right">{{
              formatDate(item.createdAt)
            }}</v-col>
          </v-row>
        </v-col>
      </v-sheet>
    </v-row>

    <v-sheet class="px-4 py-2">
      <v-btn
        block
        color="primary"
        variant="flat"
        class="mb-2 text-capitalize"
        @click="$emit('edit')"
      >
        Edit
      </v-btn>
      <v-btn
        v-if="item?.status !== 'Completed'"
        block
        color="primary-button"
        density="default"
        class="mb-2 text-capitalize"
        @click="$emit('mark-complete-request')"
      >
        Mark as Complete
      </v-btn>
      <v-btn
        block
        variant="flat"
        color="red"
        density="default"
        class="text-white text-capitalize"
        @click="$emit('delete')"
      >
        Delete
      </v-btn>
    </v-sheet>

    <WorkOrderCreate
      v-model="showCreateDialog"
      created-from="feedback"
      :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"
    />

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

<script setup lang="ts">
import { useTheme } from "vuetify";
const { getColorStatus, formatDate } = useUtils();

const props = defineProps({
  item: {
    type: Object,
    default: () => ({}),
  },
  senderName: {
    type: String,
    default: "",
  },
  type: {
    type: String,
    default: "feedback",
  },
});

const emit = defineEmits<{
  (e: "update:provider", serviceProvider: string): void;
  (e: "mark-complete-request"): void;
  (e: "delete"): void;
  (e: "edit"): void;
  (e: "updateWorkOrderId", workOrderId: string): void;
}>();

const { currentUser } = useLocalAuth();
const { getNameInitials } = useUtils();

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

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

const route = useRoute();

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

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

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,
//   })
// );

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

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
    }));
  }
});

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

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

function openWorOrderCreateDialog() {
  let newWorkOrder = {
    ..._workOrder.value,
    attachments:
      props.item.attachments.length > 0 ? props.item.attachments : [],
    subject: props.item.subject ? props.item.subject : "",
    category: props.item.category ? props.item.category : "",
    location: props.item.location ? props.item.location : "",
  };
  _workOrder.value = newWorkOrder;
  showCreateDialog.value = true;
}

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

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}`;
      _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");
  }
}

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

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

    const res = await createWorkOrder(payload);

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

function showWorkOrderInfo(workOrderId: string) {
  const route = useRoute();
  const org = route.params.org;
  const site = route.params.site;
  const id = workOrderId;
  return {
    name: "org-site-work-orders-id",
    params: { org, site, id },
  };
}
</script>
