<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="'workOrder'" />
        </div>
      </v-col>
      <v-col cols="12" xl="5" lg="5" md="5" class="fill-height">
        <div class="panel-container">
          <ChatInformation
            :item="workOrder"
            :service-providers="_serviceProviders"
            :type="'workOrder'"
            @edit="openEditDialog"
            @mark-complete-request="showCompleteDialog = true"
            @delete="showDeleteDialog = true"
          />
        </div>
      </v-col>
    </v-row>
  </div>
  <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"
  />

  <Snackbar v-model="messageSnackbar" :text="message" :color="messageColor" />
</template>
<script lang="ts" setup>
import { useTheme } from "vuetify";
const route = useRoute();
const id = route.params.id;

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

const { getServiceProviderNames } = useServiceProvider();
const erroredImages = ref<string[]>([]);

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

const _getWorkOrderById = async () => {
  try {
    const data = await getWorkOrderById(id as string);
    workOrder.value = data;
  } catch (error) {
    console.error("Error fetching feedback:", error);
  }
};

_getWorkOrderById();

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

const isEditMode = ref(false);
const isSubmitting = ref(false);
const theme = useTheme().name;

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

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

function openEditDialog() {
  isEditMode.value = true;
  _workOrder.value = { ...workOrder.value };
  showCreateDialog.value = true;
}

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

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() {
  if (!isEditMode.value || !workOrder.value?._id) {
    console.warn("Update called without valid edit mode or work order ID.");
    return;
  }
  try {
    isSubmitting.value = true;

    const payload = {
      // ..._workOrder.value,
      attachments: _workOrder.value.attachments,
      category: _workOrder.value.category,
      description: _workOrder.value.description,
      highPriority: _workOrder.value.highPriority,
      organization: route.params.org as string,
      site: route.params.site as string,
      subject: _workOrder.value.subject,
      unit: _workOrder.value.unit,
    };

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

    if (isEditMode.value) {
      console.log("updating...");
      res = await updateWorkOrder(workOrder.value._id as string, payload);
    } else {
      res = await createWorkOrder(payload);
    }

    showMessage(res.message, "success");
    showCreateDialog.value = false;

    await _getWorkOrderById();

    resetWorkOrderForm();
  } catch (err) {
    showMessage((err as Error).message, "error");
  } finally {
    isSubmitting.value = false;
  }
}
</script>
