<script>
import Layout from "@/layout/custom.vue";
import ApiServiece from "@/services/ApiService";
import { useRoute } from "vue-router";
import { onMounted, ref } from "vue";

export default {
  name: "OrderDetails",
  components: {
    Layout,
  },
  setup() {
    const route = useRoute();
    const order = ref(null);

    const getStatusClass = (status) => {
      const statusClasses = {
        waiting: "badge-waiting",
        paid: "badge-paid",
        un_paid: "badge-un_paid",
        approved: "badge-approved",
        processing: "badge-processing",
        shipping: "badge-shipping",
        delivered: "badge-delivered",
        canceled: "badge-canceled",
      };
      return statusClasses[status] || "badge-secondary";
    };

    const getStatusLabel = (status) => {
      const statusLabels = {
        waiting: "در انتظار",
        paid: "پرداخت‌شده",
        un_paid: "پرداخت‌نشده",
        approved: "تأیید‌شده",
        processing: "در حال پردازش",
        shipping: "در حال ارسال",
        delivered: "تحویل‌شده",
        canceled: "لغو‌شده",
      };
      return statusLabels[status] || "نامشخص";
    };

    const formatDate = (date) => {
      return new Date(date).toLocaleDateString("fa-IR");
    };

    const getOrder = () => {
      ApiServiece.get(`admin/orders/${route.params.id}`)
        .then((resp) => {
          order.value = resp.data.data;
          console.log(order.value);
        })
        .catch((error) => {
          console.error("Failed to fetch order details:", error);
        });
    };

    const updateShippedCount = (item) => {
      const formData = new FormData();
      formData.append("send_count", item.send_count);
      ApiServiece.put(`admin/orders/order-items/${item.id}`, formData)
        .then(() => {
          console.log("Shipped quantity updated successfully.");
        })
        .catch((error) => {
          console.error("Failed to update shipped quantity:", error);
        });
    };

    const updateNote = (item) => {
      // Call API to update the note
      console.log(item);
      const formData = new FormData();
      formData.append("description", item.description);
      ApiServiece.put(`admin/orders/order-items/${item.id}`, formData)
        .then(() => {
          console.log("Note updated successfully.");
        })
        .catch((error) => {
          console.error("Failed to update note:", error);
        });
    };

    const updateStatus = (item) => {
      const formData = new FormData();
      formData.append("status", item.status);
      ApiServiece.put(`admin/orders/order-items/${item.id}`, formData)
        .then(() => {
          console.log("Status updated successfully.");
        })
        .catch((error) => {
          console.error("Failed to update status:", error);
        });
    };
    function formatWithCommas(number) {
      return number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    }

    onMounted(() => {
      getOrder();
    });

    return {
      order,
      getStatusClass,
      formatDate,
      getStatusLabel,
      updateShippedCount,
      updateNote,
      updateStatus,
      formatWithCommas
    };
  },
};
</script>

<template>
  <Layout>
    <BRow>
      <BCol sm="12">
        <BCard>
          <BCardHeader
            class="d-flex justify-content-between align-items-center"
          >
            <h5 class="mb-0">جزئیات سفارش</h5>
          </BCardHeader>
          <BCardBody v-if="order">
            <!-- Order Details and Items Here -->

            <h6 class="mt-4 mb-3">آیتم های سفارش</h6>
            <div v-if="order.order_items.length > 0">
              <BTable
                hover
                class="table-header"
                bordered
                :items="order.order_items"
                :fields="[
                  { key: 'title', label: 'عنوان محصول' },
                  { key: 'count', label: 'تعداد در خواستی ' },
                  { key: 'price', label: 'قیمت' },
                  { key: 'created_at', label: 'تاریخ ثبت' },
                  { key: 'edit_count', label: 'تعداد فرستاده شده' },
                  { key: 'description', label: 'یادداشت' },
                  { key: 'status', label: 'ویرایش وضعیت' },
                ]"
              >
                <!-- Price formatting -->
                <template #cell(price)="data">
                  {{ formatWithCommas(data.item.price) }} تومان
                </template>

                <template #cell(title)="data">
                  {{ data.item?.product?.title }}
                </template>

                <!-- Created Date formatting -->
                <template #cell(created_at)="data">
                  {{ formatDate(data.item.created_at) }}
                </template>

                <!-- Requested Quantity (Non-editable) -->
                <template #cell(count)="data">
                  {{ data.item.count }}
                </template>

                <!-- Editable shipped quantity with API call -->
                <template #cell(edit_count)="data">
                  <input
                    v-model="data.item.send_count"
                    type="number"
                    class="form-control"
                    :min="1"
                    :max="data.item.count"
                    placeholder="تعداد فرستاده شده"
                    @input="updateShippedCount(data.item)"
                  />
                </template>

                <!-- Editable note with API call on focus out -->
                <template #cell(description)="data">
                  <textarea
                    v-model="data.item.description"
                    class="form-control"
                    placeholder="یادداشت"
                    @focusout="updateNote(data.item)"
                  ></textarea>
                </template>

                <!-- Editable status cell -->
                <template #cell(status)="data">
                  <select
                    v-model="data.item.status"
                    class="form-control selector"
                    @change="updateStatus(data.item)"
                    placeholder="وضعیت"
                  >
                    <option value="done">کامل شده</option>
                    <option value="processing">در انتظار</option>
                  </select>
                </template>
              </BTable>
            </div>
            <div v-else class="text-center text-muted my-3">
              <p>هیچ آیتمی برای نمایش وجود ندارد.</p>
            </div>
          </BCardBody>
          <BCardBody v-else>
            <p>در حال بارگذاری...</p>
          </BCardBody>
        </BCard>
      </BCol>
    </BRow>
  </Layout>
</template>

<style scoped>
.badge {
  display: inline-block;
  padding: 5px 10px;
  border-radius: 12px;
  font-size: 0.85rem;
  font-weight: 500;
  color: white;
}

/* Order Status Colors */
.badge-waiting {
  background-color: #ffc107;
}
.badge-paid {
  background-color: #28a745;
}
.badge-un_paid {
  background-color: #dc3545;
}
.badge-approved {
  background-color: #17a2b8;
}
.badge-processing {
  background-color: #007bff;
}
.badge-shipping {
  background-color: #6f42c1;
}
.badge-delivered {
  background-color: #20c997;
}
.badge-canceled {
  background-color: #6c757d;
}

h5 {
  font-weight: bold;
}
.dropdown-item {
  cursor: pointer;
}
.table-header {
  text-align: center;
}
.selector {
  padding: 4px;
  height: 35px;
}
</style>
