import React, { useState } from "react";
import styles from "./Orders.module.scss";
import { Link } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { useGetOrdersQuery } from "../../app/api/orderApi";
import EmptyOrderState from "./emptyOrder";
import Loader from "../../components/Loader/index";
import { Result, Button } from "antd";
import { useNavigate } from "react-router-dom";
import PendingPriceBadge from "../../components/PendingPriceBadge";

const isPriceZero = (price) => !price || parseFloat(price) === 0;

const orderHasZeroPrice = (orderItems) =>
  orderItems?.some((item) => isPriceZero(item.unit_price_amount));

const Orders = () => {
  const { t } = useTranslation();
  const { data: orders, isLoading, error } = useGetOrdersQuery();
  const navigate = useNavigate();

  const formatOrderDate = (dateString) => {
    try {
      return new Date(dateString).toLocaleString("tk-TM", {
        day: "2-digit",
        month: "2-digit",
        year: "numeric",
        hour: "2-digit",
        minute: "2-digit",
      });
    } catch {
      return dateString;
    }
  };

  if (isLoading) return <Loader />;

  if (error)
    return (
      <Result
        status="500"
        title="500"
        subTitle="Näbelli ýalňyşlyk ýüze çykdy."
        extra={
          <Button type="primary" onClick={() => navigate("/")}>
            Baş sahypa gidiň
          </Button>
        }
      />
    );

  if (!orders || orders.length === 0) return <EmptyOrderState />;

  return (
    <div className={styles.container}>
      <h2 className={styles.title}>Sargytlarym</h2>

      {/* Desktop table */}
      <div className={styles.tableContainer}>
        <table className={styles.table}>
          <thead>
            <tr>
              <th>{t("order.orderNumber")}</th>
              <th>{t("order.orderDate")}</th>
              <th>{t("order.sum")}</th>
              <th>{t("checkout.paymentMethod")}</th>
              <th>{t("order.orderStatus")}</th>
              <th>{t("order.action")}</th>
            </tr>
          </thead>
          <tbody>
            {orders.map((order) => {
              const hasZeroPrice = orderHasZeroPrice(order.orderItems);
              const totalAmount = order.orderItems.reduce(
                (sum, item) =>
                  sum + parseFloat(item.unit_price_amount) * item.quantity,
                0,
              );

              return (
                <tr key={order.id}>
                  <td>{order.id}</td>
                  <td>{formatOrderDate(order.delivery_at)}</td>
                  <td style={{ color: "#888888", fontWeight: "700" }}>
                    {hasZeroPrice ? (
                      <span
                        style={{
                          display: "inline-flex",
                          alignItems: "center",
                          gap: 6,
                        }}
                      >
                         {t("cart.pendingPriceTitle")} <PendingPriceBadge />
                      </span>
                    ) : (
                      `${totalAmount.toFixed(2)} m.`
                    )}
                  </td>
                  <td>{order.payment_type}</td>
                  <td>{order.status}</td>
                  <td>
                    <Link to={`/orderdetail/${order.id}`}>
                      <button className={styles.actionButton}>
                        {t("order.information")}
                      </button>
                    </Link>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      {/* Mobile cards */}
      <div className={styles.Mobilecontainer}>
        {orders.map((order) => {
          const hasZeroPrice = orderHasZeroPrice(order.orderItems);
          const totalAmount = order.orderItems.reduce(
            (sum, item) =>
              sum + parseFloat(item.unit_price_amount) * item.quantity,
            0,
          );

          return (
            <div
              key={order.id}
              className={styles.orderCard}
              onClick={(e) => {
                // Modal veya badge içerisine tıklandığında yönlendirmeyi engelle
                if (
                  e.target.closest(`.${styles.pendingPriceBadgeWrapper}`) ||
                  e.target.closest(".ant-modal-root") ||
                  e.target.closest(".ant-modal-wrap")
                ) {
                  return;
                }
                navigate(`/orderdetail/${order.id}`);
              }}
              style={{ cursor: "pointer" }}
            >
              <div className={styles.orderRow}>
                <span className={styles.label}>{t("order.orderNumber")}:</span>
                <span className={styles.value}>{order.id}</span>
              </div>
              <div className={styles.orderRow}>
                <span className={styles.label}>{t("order.orderDate")}:</span>
                <span className={styles.value}>
                  {formatOrderDate(order.delivery_at)}
                </span>
              </div>
              <div className={styles.orderRow}>
                <span className={styles.label}>{t("order.sum")}:</span>
                <span className={styles.total}>
                  {hasZeroPrice ? (
                    <span
                      style={{
                        display: "inline-flex",
                        alignItems: "center",
                        gap: 6,
                      }}
                    >
                       {t("cart.pendingPriceTitle")} <PendingPriceBadge />
                    </span>
                  ) : (
                    `${totalAmount.toFixed(2)} m.`
                  )}
                </span>
              </div>
              <div className={styles.orderRow}>
                <span className={styles.label}>
                  {t("checkout.paymentMethod")}:
                </span>
                <span className={styles.value}>{order.payment_type}</span>
              </div>
              <div className={styles.orderRow}>
                <span className={styles.label}>{t("order.orderStatus")}:</span>
                <span className={styles.value}>{order.status}</span>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
};

export default Orders;
