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, Modal } from "antd";
import { useNavigate } from "react-router-dom";

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

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

const PendingPriceModal = ({ open, onClose, t }) => (
  <Modal
    open={open}
    onOk={onClose}
    onCancel={onClose}
    okText={t("common.ok")}
    cancelButtonProps={{ style: { display: "none" } }}
    centered
    title="Bahasy anyklamaly"
    className="pending-price-modal"
    width={400}
  >
    <p>
      Bu sargytdaky bir ýa-da birnäçe harydyň bahasy entek kesgitlenmedik.
      Operatorymyz siziň bilen habarlaşyp, goşmaça maglumat berer.
    </p>
  </Modal>
);

const PendingPriceBadge = ({ t }) => {
  const [tooltipVisible, setTooltipVisible] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [isMobile] = useState(() => /Mobi|Android/i.test(navigator.userAgent));

  const handleClick = (e) => {
    e.preventDefault();
    e.stopPropagation();
    if (isMobile) setModalVisible(true);
  };

  const stopPropagation = (e) => {
    e.stopPropagation();
  };

  return (
    <span onClick={stopPropagation}>
      <span
        className={styles.pendingPriceBadgeWrapper}
        onMouseEnter={() => !isMobile && setTooltipVisible(true)}
        onMouseLeave={() => setTooltipVisible(false)}
        onClick={handleClick}
        onTouchEnd={(e) => {
          e.stopPropagation();
        }}
      >
        <span className={styles.pendingPriceBadge}>!</span>

        {tooltipVisible && (
          <span className={styles.pendingPriceTooltip}>
            <strong>Bahasyny anyklamaly</strong>
            Bu sargytdaky harydyň bahasy kesgitlenmedik. Operator size jaň edip
            goşmaça maglumat berer.
          </span>
        )}
      </span>

      <PendingPriceModal
        open={modalVisible}
        onClose={() => setModalVisible(false)}
        t={t}
      />
    </span>
  );
};

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,
                        }}
                      >
                        Bahasyny anyklamaly <PendingPriceBadge t={t} />
                      </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,
                      }}
                    >
                      Bahasyny anyklamaly <PendingPriceBadge t={t} />
                    </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;
