import { Button, Card, Divider, Image } from "antd";
import EmptyOrdersIcon from "components/Icons/EmptyOrdersIcon";
import RateIcon from "components/Icons/RateIcon";
import ReOrderIcon from "components/Icons/ReOrderIcon";
import LoadingSpinner from "components/LoadingSpinner";
import ProText from "components/ProText";
import ProTitle from "components/ProTitle";
import { useTranslation } from "react-i18next";
import { useGetOrdersQuery } from "redux/api/others";
import { colors } from "ThemeConstants";
import styles from "./orders.module.css";
import { Link, useParams } from "react-router-dom";
import { RateBottomSheet } from "components/CustomBottomSheet/RateBottomSheet";
import { useState } from "react";

// Utility function to format date
const formatDate = (dateString: string): string => {
  const date = new Date(dateString);

  // Format: "14 December 2022 18:45"
  const options: Intl.DateTimeFormatOptions = {
    day: "numeric",
    month: "long",
    year: "numeric",
    hour: "2-digit",
    minute: "2-digit",
    hour12: false,
  };

  return date.toLocaleDateString("en-GB", options);
};

export default function OrdersList() {
  const { data: orders = [], isLoading, error, refetch } = useGetOrdersQuery();
  const { subdomain } = useParams();
  const { t } = useTranslation();
  const [orderId, setOrderId] = useState("");
  const [isRateBottomSheetOpen, setIsRateBottomSheetOpen] = useState(false);
  if (isLoading) {
    return <LoadingSpinner />;
  }

  if (error) {
    return (
      <div
        style={{
          display: "flex",
          flexDirection: "column",
          justifyContent: "center",
          alignItems: "center",
          height: "100vh",
        }}
      >
        <ProTitle level={4}>{t("orders.errorLoadingOrders")}</ProTitle>
        <Button onClick={refetch}>{t("orders.retry")}</Button>
      </div>
    );
  }

  // Determine button styles based on order status
  const getStatusButtonStyles = (order: any) => {
    const status = order?.status?.toLowerCase() || "";

    if (status.includes("close") || status === "closed") {
      return {
        backgroundColor: "var(--color-error-12, #EA1F221F)",
        color: "#EA1F22",
      };
    } else if (status.includes("completed") || status === "complete") {
      return {
        backgroundColor: "var(--color-success-12, #28A7451F)",
        color: "#28A745",
      };
    } else if (status.includes("preparing") || status.includes("prepare")) {
      return {
        backgroundColor: "var(--Color-Primary-100, #FFB7001F)",
        color: "#FFB700",
      };
    }

    // Default fallback
    return {
      backgroundColor: "var(--color-success-12, #28A7451F)",
      color: "#28A745",
    };
  };

  console.log(orders);

  return (
    <>
      {orders.length === 0 ? (
        // Empty state
        <div
          style={{
            display: "flex",
            flexDirection: "column",
            justifyContent: "center",
            alignItems: "center",
            height: "90vh",
            padding: "1rem",
          }}
        >
          <EmptyOrdersIcon />
          <ProTitle level={4}>{t("orders.noOrdersFound")}</ProTitle>
          <ProText>{t("orders.youHavenTPlacedAnyOrdersYet")}</ProText>
        </div>
      ) : (
        // Orders list
        <div style={{ padding: "16px" }}>
          {orders.map((order: any) => (
            <Link to={`/${subdomain}/orders/${order.id}`} key={order.id}>
              <Card
                key={order.id}
                style={{
                  borderRadius: "16px",
                  boxShadow: "0 2px 8px rgba(0, 0, 0, 0.1)",
                  marginBottom: 12,
                }}
              >
                <div
                  style={{
                    display: "flex",
                    flexDirection: "row",
                    justifyContent: "flex-start",
                    gap: "1rem",
                  }}
                >
                  <Image
                    src={order.restaurant_icon}
                    className={styles.profileImage}
                    width={50}
                    height={50}
                    preview={false}
                  />
                  <div
                    style={{ display: "flex", flexDirection: "column", gap: 8 }}
                  >
                    <ProText style={{ fontSize: "1rem" }}>
                      {order.restaurant_name}
                    </ProText>
                    <ProText type="secondary">
                      {formatDate(order?.created_at)}
                    </ProText>
                    <ProText type="secondary">
                      {t("orders.orderID")} {order.id}
                    </ProText>
                    <Button
                      style={{
                        height: 28,
                        gap: 10,
                        opacity: 1,
                        borderRadius: "Spacing/4XL",
                        padding: "4px 8px",
                        border: "none",
                        width: "fit-content",
                        ...getStatusButtonStyles(order),
                      }}
                    >
                      {order.status}
                    </Button>
                  </div>
                </div>
                <Divider style={{ margin: "15px 0 10px 0" }} />
                <div
                  style={{
                    display: "flex",
                    flexDirection: "row",
                    justifyContent: "space-around",
                  }}
                >
                  <div>
                    <ProText
                      onClick={(e) => {
                        e.preventDefault();
                        setOrderId(order.id);
                        setIsRateBottomSheetOpen(true);
                      }}
                      style={{ fontSize: "1rem", color: colors.primary }}
                    >
                      <RateIcon className={styles.rateIcon} />
                      {t("orders.rateOrder")}
                    </ProText>{" "}
                  </div>

                  <div>
                    <ProText
                      style={{ fontSize: "1rem", color: colors.primary }}
                    >
                      <ReOrderIcon className={styles.reorderIcon} />
                      {t("orders.reOrder")}
                    </ProText>
                  </div>
                </div>
              </Card>
            </Link>
          ))}
          <RateBottomSheet
            isOpen={isRateBottomSheetOpen}
            onClose={() => setIsRateBottomSheetOpen(false)}
            orderIdProp={orderId}
          />
        </div>
      )}
    </>
  );
}
