import { PlusOutlined } from "@ant-design/icons";
import { Card, Divider, Form, Space, Layout } from "antd";
import ArabicPrice from "components/ArabicPrice";
import CartActionsButtons from "components/CartActionsButtons/CartActionsButtons.tsx";
import ImageWithFallback from "components/ImageWithFallback";
import ProHeader from "components/ProHeader/ProHeader.tsx";
import ProInputCard from "components/ProInputCard/ProInputCard.tsx";
import ProRatioGroups from "components/ProRatioGroups/ProRatioGroups.tsx";
import ProText from "components/ProText.tsx";
import ProTitle from "components/ProTitle.tsx";
import {
  selectCart,
  updateCollectionMethod,
} from "features/order/orderSlice.ts";
import styles from "pages/cart/cart.module.css";
import YouMightAlsoLike from "pages/cart/components/youMayLike/YouMightAlsoLike.tsx";
import { Link, useParams } from "react-router-dom";
import { colors } from "ThemeConstants.ts";

import OrderSummary from "components/OrderSummary/OrderSummary.tsx";
import { useAppSelector } from "redux/hooks.ts";

import { FormInstance } from "antd";
import useBreakPoint from "hooks/useBreakPoint.ts";
import CarPlateCard from "pages/cart/components/CarPlateCard.tsx";
import CartFooter from "pages/cart/components/cartFooter/CartFooter.tsx";
import CouponCard from "pages/cart/components/CouponCard.tsx";
import RewardWaiterCard from "pages/cart/components/RewardWaiterCard.tsx";
import SpecialRequestCard from "pages/cart/components/specialRequest/SpecialRequestCard.tsx";
import TableNumberCard from "pages/cart/components/TableNumberCard.tsx";
import TimeEstimateCard from "pages/cart/components/timeEstimate/TimeEstimateCard.tsx";
import { OrderType } from "pages/checkout/hooks/types";
import { useTranslation } from "react-i18next";
import { Variant } from "utils/types/appTypes";

interface CartMobileTabletLayoutProps {
  form: FormInstance;
}

export default function CartMobileTabletLayout({
  form,
}: CartMobileTabletLayoutProps) {
  const { t } = useTranslation();
  const { items, collectionMethod, orderType } = useAppSelector(selectCart);
  const { isRTL } = useAppSelector((state) => state.locale);
  const { subdomain } = useParams();
  const { pickup_type } = useAppSelector((state) => state.order.restaurant);
  const { isMobile, isTablet } = useBreakPoint();

  const getResponsiveClass = () => (isTablet ? "tablet" : "mobile");

  const getMenuItemImageStyle = () => {
    if (isMobile) {
      return {
        width: 90,
        height: 80,
      };
    }
    return {
      width: 120,
      height: 120,
    };
  };

  return (
    <Layout>
      <ProHeader>{t("cart.title")}</ProHeader>
      <Layout.Content
        className={`${styles.cartContainer} '${styles.cartLayout}' ${getResponsiveClass()}`}
      >
        <Space
          direction="vertical"
          size={isMobile ? "middle" : isTablet ? "large" : "large"}
          style={{ width: "100%", gap: 16 }}
        >
          <div className={`${styles.cartContent} ${getResponsiveClass()}`}>
            <div className={styles.cartItems}>
              <Card hoverable className={styles.cartItem}>
                <div
                  style={{
                    display: "flex",
                    flexDirection: "row",
                    justifyContent: "space-between",
                  }}
                >
                  <div
                    style={{
                      marginTop: 10,
                      boxSizing: "border-box", // Explicit box model definition
                    }}
                  >
                    <ProTitle level={5} style={{ whiteSpace: "nowrap" }}>
                      {t("cart.yourOrder")}
                    </ProTitle>
                  </div>

                  <Link
                    to={`/${subdomain}/menu?${
                      orderType ? `orderType=${orderType}` : ""
                    }`}
                    style={{
                      width: "100%",
                      textAlign: "end",
                    }}
                  >
                    <div
                      style={{
                        color: colors.primary,
                      }}
                    >
                      <PlusOutlined
                        style={{
                          color: colors.primary,
                          marginLeft: 5,
                          marginTop: 15,
                        }}
                      />
                      {t("cart.addMore")}
                    </div>
                  </Link>
                </div>

                {items.length >= 1 && (
                  <Divider style={{ margin: "0px 0px 10px 0px" }} />
                )}
                {items.map((item, index) => (
                  <div key={index} style={{ position: "relative" }}>
                    <Space
                      size="middle"
                      style={{
                        display: "flex",
                        alignItems: "center",
                        justifyContent: "space-between",
                        height: "100%",
                      }}
                    >
                      <Space direction="vertical" size="small">
                        <div
                          style={{
                            position: "absolute",
                            top: 0,
                            [isRTL ? "right" : "left"]: 0,
                          }}
                        >
                          <ProText
                            style={{
                              margin: 0,
                              lineClamp: 1,
                              fontSize: isMobile ? 14 : isTablet ? 16 : 18,
                              fontWeight: 600,
                            }}
                          >
                            {item.name}{" "}
                            <span
                              style={{
                                fontWeight: 400,
                              }}
                            >
                              {isRTL
                                ? (item.variant as Variant)?.optionsAR?.[0]
                                    ?.value
                                : (item.variant as Variant)?.options?.[0]
                                    ?.value}
                            </span>
                          </ProText>
                          <br />
                          <ProText
                            type="secondary"
                            className={`${styles.itemDescription} responsive-text`}
                            style={{
                              margin: 0,
                              lineClamp: 1,
                              padding: isMobile ? 3 : isTablet ? 8 : 10,
                              fontSize: isMobile ? 14 : isTablet ? 18 : 20,
                              display: "-webkit-box",
                              WebkitBoxOrient: "vertical",
                              WebkitLineClamp: 1,
                              overflow: "hidden",
                              textOverflow: "ellipsis",
                              wordWrap: "break-word",
                              overflowWrap: "break-word",
                              lineHeight: "1.4",
                              maxHeight: isMobile
                                ? "2.8em"
                                : isTablet
                                  ? "4.8em"
                                  : "6.8em",
                              fontWeight: 500,
                              letterSpacing: "0.01em",
                              width: "65%",
                            }}
                          >
                            {item.description}
                          </ProText>
                        </div>
                        <div
                          style={{
                            position: "absolute",
                            bottom: index !== items.length - 1 ? 16 : 6,
                            [isRTL ? "right" : "left"]: 0,
                          }}
                        >
                          <ArabicPrice
                            price={item.price}
                            style={{ fontStyle: "bold" }}
                          />
                        </div>
                      </Space>
                      <div style={{ position: "relative" }}>
                        <ImageWithFallback
                          src={item.image}
                          alt={item.name}
                          className={`${styles.menuItemImage} responsive-image`}
                          {...getMenuItemImageStyle()}
                          fallbackSrc={
                            "https://fascano-space.s3.me-central-1.amazonaws.com/uploads/restorants/685a8fc884a8c_large.jpg"
                          }
                        />
                        <div
                          style={{
                            marginTop: 10,
                          }}
                        >
                          <CartActionsButtons item={item} />
                        </div>
                      </div>
                    </Space>

                    {index !== items.length - 1 && (
                      <Divider style={{ margin: "10px 0" }} />
                    )}
                  </div>
                ))}
              </Card>
            </div>
          </div>

          <YouMightAlsoLike />

          <SpecialRequestCard />

          <CouponCard />

          {/* Car Plate*/}
          {((orderType === OrderType.Pickup && pickup_type === "car") ||
            orderType === OrderType.ScheduledOrder) && <CarPlateCard />}

          {/* Estimate Time */}
          {(orderType === OrderType.Pickup ||
            orderType === OrderType.ScheduledOrder) && <TimeEstimateCard />}

          {/* Collection Method */}
          {orderType === OrderType.Pickup && (
            <ProInputCard title={t("cart.collectionMethod")}>
              <Form.Item
                name="collectionMethod"
                required
                rules={[
                  {
                    required: true,
                    message: t("cart.pleaseSelectCollectionMethod"),
                  },
                ]}
              >
                <ProRatioGroups
                  options={[
                    { label: t("cart.Cash"), value: "cod", price: "" },
                    {
                      label: t("cart.e-payment"),
                      value: "paymentgateway",
                      price: "",
                    },
                  ]}
                  value={collectionMethod}
                  onRatioClick={(value) => {
                    if (value === "cod") {
                      updateCollectionMethod(value);
                    } else {
                      updateCollectionMethod(value);
                    }
                  }}
                />
              </Form.Item>
            </ProInputCard>
          )}

          {/* Reward Your Waiter */}
          <RewardWaiterCard />

          {/* Table Number */}
          {(orderType === OrderType.DineIn ||
            orderType === OrderType.ToOffice) && <TableNumberCard />}

          {/* Invoice Summary */}
          <OrderSummary />
        </Space>
      </Layout.Content>
      <CartFooter form={form} />
    </Layout>
  );
}
