import { useParams, useNavigate } from "react-router-dom";
import { useState } from "react";
import styles from "./OrderDetail.module.scss";
import { useTranslation } from "react-i18next";
import { useGetOrderByIdQuery } from "../../app/api/orderApi";
import track from "../../assets/track.jpg";
import Loader from "../../components/Loader/index";
import { Result, Button, Modal } from "antd";

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

const PendingPriceModal = ({ open, onClose, t }) => (
  <Modal
    open={open}
    onOk={onClose}
    onCancel={onClose}
    okText={t ? t("common.ok") : "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 OrderDetail = () => {
  const { t } = useTranslation();
  const { id } = useParams();
  const navigate = useNavigate();
  const { data: orderData, isLoading, error } = useGetOrderByIdQuery(id);

  const formatDate = (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;
    }
  };

  const formatDeliveryTime = (time, date) => {
    try {
      const formatted = new Date(date).toLocaleDateString("tk-TM", {
        day: "2-digit",
        month: "2-digit",
        year: "numeric",
      });
      return `${time} (${formatted})`;
    } catch {
      return time;
    }
  };

  const calculateTotal = (orderItems) => {
    if (!orderItems?.length) return null;
    const hasZero = orderItems.some((item) =>
      isPriceZero(item.unit_price_amount),
    );
    if (hasZero) return null;
    return orderItems
      .reduce(
        (sum, item) => sum + parseFloat(item.unit_price_amount) * item.quantity,
        0,
      )
      .toFixed(2);
  };

  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 (!orderData) return <div className={styles.notFound}>Order not found</div>;

  const totalAmount = calculateTotal(orderData.orderItems);

  return (
    <div className={styles.container}>
      <div className={styles.header}>
        <h1>
          {t("order.orderNumber")}: {orderData.id}
        </h1>
        <div className={styles.Buttons} />
      </div>

      <div className={styles.content}>
        <div className={styles.details}>
          <div className={styles.rowContainer}>
            <div className={styles.row}>
              <span>{t("order.orderDate")}:</span>
              <span>{formatDate(orderData.delivery_at)}</span>
            </div>
            <div className={styles.row}>
              <span>{t("order.orderStatus")}:</span>
              <span>{orderData.status}</span>
            </div>
            <div className={styles.row}>
              <span>{t("order.deliveryTime")}:</span>
              <span>
                {formatDeliveryTime(
                  orderData.delivery_time,
                  orderData.delivery_at,
                )}
              </span>
            </div>
          </div>
          <div className={styles.rowContainer}>
            <div className={styles.row}>
              <span>{t("checkout.paymentMethod")}:</span>
              <span>{orderData.payment_type}</span>
            </div>
            <div className={styles.row}>
              <span>{t("order.sum")}:</span>
              <span className={styles.total}>
                {totalAmount === null ? (
                  <span
                    style={{
                      display: "inline-flex",
                      alignItems: "center",
                      gap: 6,
                    }}
                  >
                    <PendingPriceBadge t={t} />
                  </span>
                ) : (
                  `${totalAmount} m.`
                )}
              </span>
            </div>
          </div>
        </div>

        {/* Desktop table */}
        <div className={styles.tableContainer}>
          <table className={styles.table}>
            <thead>
              <tr>
                <th>{t("order.photo")}</th>
                <th>{t("order.productName")}</th>
                <th>{t("order.brand")}</th>
                <th>{t("order.code")}</th>
                <th>{t("order.price")}</th>
                <th>{t("order.quantity")}</th>
                <th>{t("order.sum")}</th>
              </tr>
            </thead>
            <tbody>
              {orderData.orderItems.map((item, index) => {
                const product = item.product;
                const zeroPriceItem = isPriceZero(item.unit_price_amount);
                const itemTotal = zeroPriceItem
                  ? null
                  : (
                      parseFloat(item.unit_price_amount) * item.quantity
                    ).toFixed(2);

                return (
                  <tr key={index}>
                    <td>
                      <img
                        src={product.thumbnail}
                        alt={product.name}
                        className={styles.image}
                      />
                    </td>
                    <td>{product.name}</td>
                    <td>{product.brand || "-"}</td>
                    <td>{product.id || "-"}</td>
                    <td>
                      {zeroPriceItem ? (
                        <span
                          style={{
                            display: "inline-flex",
                            alignItems: "center",
                            gap: 6,
                          }}
                        >
                          <PendingPriceBadge t={t} />
                        </span>
                      ) : (
                        `${item.unit_price_amount} m.`
                      )}
                    </td>
                    <td>{item.quantity}</td>
                    <td>
                      {itemTotal === null ? (
                        <span
                          style={{
                            display: "inline-flex",
                            alignItems: "center",
                            gap: 6,
                          }}
                        >
                          <PendingPriceBadge t={t} />
                        </span>
                      ) : (
                        `${itemTotal} m.`
                      )}
                    </td>
                  </tr>
                );
              })}

              {orderData.shipping_method && (
                <tr>
                  <td>
                    <img src={track} alt="Delivery" className={styles.image} />
                  </td>
                  <td>Eltip bermek hyzmaty</td>
                  <td>Beýleki</td>
                  <td>DELIVERY</td>
                  <td>10.00 m.</td>
                  <td>1</td>
                  <td>10.00 m.</td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>

      {/* Mobile cards */}
      <div className={styles.productList}>
        {orderData.orderItems.map((item, index) => {
          const product = item.product;
          const zeroPriceItem = isPriceZero(item.unit_price_amount);
          const itemTotal = zeroPriceItem
            ? null
            : (parseFloat(item.unit_price_amount) * item.quantity).toFixed(2);

          return (
            <div className={styles.card} key={index}>
              <div className={styles.imageContainer}>
                <img src={product.thumbnail} alt={product.name} />
              </div>
              <div className={styles.detailsMobile}>
                <h3 className={styles.title}>
                  {product.brand || product.name}
                </h3>
                <p className={styles.description}>{product.name}</p>
                <div className={styles.footer}>
                  <span className={styles.quantity}>
                    {t("order.quantity")}: {item.quantity}
                  </span>
                  <span className={styles.price}>
                    {zeroPriceItem ? (
                      <span
                        style={{
                          display: "inline-flex",
                          alignItems: "center",
                          gap: 6,
                        }}
                      >
                        <PendingPriceBadge t={t} />
                      </span>
                    ) : (
                      `${item.unit_price_amount} m.`
                    )}
                  </span>
                </div>
              </div>
            </div>
          );
        })}

        {/* {orderData.shipping_method && (
          <div className={styles.card}>
            <div className={styles.imageContainer}>
              <img src={track} alt="Delivery" />
            </div>
            <div className={styles.detailsMobile}>
              <h3 className={styles.title}>Beýleki</h3>
              <p className={styles.description}>Eltip bermek hyzmaty</p>
              <div className={styles.footer}>
                <span className={styles.quantity}>
                  {t("order.quantity")}: 1
                </span>
                <span className={styles.price}>10.00 m.</span>
              </div>
            </div>
          </div>
        )} */}
      </div>
    </div>
  );
};

export default OrderDetail;
