import { Button, FormInstance, Layout } from "antd";
import { selectCart } from "features/order/orderSlice";
import { OrderType } from "pages/checkout/hooks/types.ts";
import { useCallback, useMemo } from "react";
import { useTranslation } from "react-i18next";
import { useNavigate, useParams } from "react-router-dom";
import { useAppSelector } from "redux/hooks";
import styles from "../../address/address.module.css";
import useOrder from "../hooks/useOrder";

export default function CheckoutButton({ form }: { form: FormInstance }) {
  const { t } = useTranslation();
  const { orderType } = useAppSelector(selectCart);
  const navigate = useNavigate();
  const { handleCreateOrder } = useOrder();
  const { subdomain } = useParams();

  const handleSplitBillClick = useCallback(() => {
    navigate(`/${subdomain}/split-bill`);
  }, [navigate, subdomain]);

  const handlePlaceOrderClick = useCallback(async () => {
    try {
      await form.validateFields();
      handleCreateOrder();
    } catch (error) {
      console.log(error);
    }
  }, [handleCreateOrder, form]);

  const shouldShowSplitBill = useMemo(
    () => orderType === OrderType.DineIn,
    [orderType],
  );

  return (
    <Layout.Footer className={styles.checkoutButtonContainer}>
      {shouldShowSplitBill && (
        <Button
          className={styles.splitBillButton}
          onClick={handleSplitBillClick}
        >
          {t("checkout.splitBill")}
        </Button>
      )}

      <Button
        type="primary"
        shape="round"
        className={styles.placeOrderButton}
        onClick={handlePlaceOrderClick}
      >
        {t("checkout.placeOrder")}
      </Button>
    </Layout.Footer>
  );
}
