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

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) => {
      switch (status) {
        case 'waiting':
          return 'در انتظار';
        case 'paid':
          return 'پرداخت شده';
        case 'un_paid':
          return 'پرداخت نشده';
        case 'approved':
          return 'تایید شده';
        case 'processing':
          return 'در حال پردازش';
        case 'shipping':
          return 'در حال ارسال';
        case 'delivered':
          return 'تحویل شده';
        case 'canceled':
          return 'لغو شده';
        case 'in_cart':
          return 'در سبد خرید';
        default:
          return 'وضعیت نامشخص';
      }
    };

    const formatDate = (date) => {
      return moment(date,"YYYY-MM-DD HH:mm:ss")
          .locale("fa")
          .format("HH:mm:ss YYYY/MM/DD");
    };

    const getOrder = () => {
      ApiServiece.get(`admin/orders/${route.params.id}`)
        .then((resp) => {
          const rawOrder = resp.data.data;

          if (Array.isArray(rawOrder.order_items)) {
            rawOrder.order_items = rawOrder.order_items.map((item) => ({
              ...item,
              description: item.description ?? "",
            }));
          }

          order.value = rawOrder;
        })
        .catch((error) => {
          console.error("Failed to fetch order details:", error);
        });
    };

    const updateShippedCount = (item) => {
      const formData = new FormData();
      formData.append("send_count", item.send_count || 0);
      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);
        });
    };

    const formatPrice = (price) => {
      if (!price) return 0

      return numeral(price).format("0,0")
    };

    const amountDiscount = (item) => {
      if (item?.discount_id) {
        if (item?.discount?.type === 'percentage')
          return formatPrice(item?.price * (Number(item?.discount?.amount) / 100)) + 'تومان';

        return 0
      }

      return 0
    }

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

    return {
      order,
      getStatusClass,
      formatDate,
      getStatusLabel,
      updateShippedCount,
      updateNote,
      updateStatus,
      formatPrice,
      amountDiscount,
    };
  },
};
</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">
            <div class="p-3 mb-4 border rounded">
              <BRow class="mb-3">
                <BCol md="6">
                  <strong class="me-2">نام مشتری:</strong>
                  <span>{{ order?.user?.name || "بدون نام" }}</span>
                </BCol>

                <BCol md="6">
                  <strong class="me-2">موبایل:</strong>
                  <span>{{ order?.user?.mobile }}</span>
                </BCol>
              </BRow>

              <BRow class="mb-3">
                <BCol md="6">
                  <strong class="me-2">آدرس:</strong>
                  <span>{{ order?.user_address?.address || "بدون آدرس" }}</span>
                </BCol>
                <BCol md="6">
                  <strong class="me-2">شهر:</strong>
                  <span>{{ order?.user_address?.city || "بدون شهر" }}</span>
                </BCol>
              </BRow>

              <BRow class="mb-3">
                <BCol md="6">
                  <strong class="me-2">هزینه ارسال:</strong>
                  <span>
                    {{
                      order?.shipping_price != null
                        ? formatPrice(order?.shipping_price) + ' تومان'
                        : "بدون قیمت"
                    }}
                  </span>
                </BCol>
                <BCol md="6">
                  <strong class="me-2">تخفیف:</strong>
                  <span>{{ ((order?.order_items?.reduce((sum, item) => sum + Number(item?.price), 0) + Number(order?.shipping_price)) - order?.total_price).toLocaleString() }} تومان</span>
                  <span v-if="order?.discount?.amount">({{ formatPrice(order?.discount?.amount) + (order?.discount?.type === 'percentage' ? ' درصد' : 'تومان') }})</span>
                </BCol>
              </BRow>


              <BRow class="mb-3">
                <BCol md="6">
                  <strong class="me-2">کد تخفیف:</strong>
                  <span>{{ order?.discount?.title ?? '-' }}</span>
                </BCol>

                <BCol md="6">
                  <strong class="me-2">وضعیت سفارش:</strong>
                  <span>{{ getStatusLabel(order?.status) || "-" }}</span>
                </BCol>
              </BRow>

              <BRow class="mb-3">
                <BCol md="6">
                  <strong class="me-2">مبلغ پرداختی:</strong>
                  <span>{{ order?.total_price ? Number(order?.total_price).toLocaleString() + 'تومان' : '0'  }}</span>
                </BCol>

                <BCol md="6">
                  <strong class="me-2">مبلغ کل:</strong>
                  <span>{{ order?.order_items?.reduce((sum, item) => sum + Number(item?.price), 0) + Number(order?.shipping_price) }}</span>
                </BCol>
              </BRow>
            </div>

            <!-- Order Details and Items Here -->

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

                <template #cell(color)="data">
                  <div
                      class="rounded p-1 text-black"
                      :style="{ background: data?.item?.attribute_value_product?.attribute_value?.code }"
                  >
                    {{ data?.item?.attribute_value_product?.attribute_value?.title }}
                  </div>
                </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>
