import { Form, Select } from "antd";
import ProInputCard from "components/ProInputCard/ProInputCard.tsx";
import {
  removeTable,
  selectCart,
  updateTables,
} from "features/order/orderSlice.ts";
import styles from "pages/cart/cart.module.css";
import { OrderType } from "pages/checkout/hooks/types";
import { useTranslation } from "react-i18next";
import { useGetTablesQuery } from "redux/api/others";
import { useAppDispatch, useAppSelector } from "redux/hooks.ts";

export default function TableNumberCard() {
  const { t } = useTranslation();
  const { tables, orderType } = useAppSelector(selectCart);
  const dispatch = useAppDispatch();
  const { data: tableList } = useGetTablesQuery(
    {
      restaurantID: localStorage.getItem("restaurantID") || "",
      tableType: orderType === OrderType.DineIn ? "1" : "2",
    },
    {
      skip: !localStorage.getItem("restaurantID") || !orderType,
    },
  );

  return (
    <>
      <ProInputCard
        title={
          orderType === OrderType.DineIn
            ? t("cart.tableNumber")
            : t("cart.selectCompany")
        }
        className={styles.tableNumberCard}
        dividerStyle={{ margin: "5px 0 0 0" }}
      >
        <Form.Item
          label={
            orderType === OrderType.DineIn
              ? t("cart.tableNumber")
              : t("cart.selectCompany")
          }
          name="tables"
          required
          rules={[
            {
              required: true,
              message:
                orderType === OrderType.DineIn
                  ? t("cart.pleaseSelectTable")
                  : t("cart.pleaseSelectCompany"),
            },
          ]}
          initialValue={tables}
          style={{ position: "relative", top: -5 }}
        >
          <Select
            value={tables}
            mode="multiple"
            placeholder={
              orderType === OrderType.DineIn
                ? t("cart.tableNumber")
                : t("cart.selectCompany")
            }
            size="large"
            options={tableList?.map((table: any) => ({
              label: table.name,
              value: table.id,
            }))}
            style={{
              width: "100%",
              height: 50,
              fontSize: 12,
            }}
            onChange={(value) => {
              console.log(value);
              dispatch(updateTables(value));
            }}
            onClear={() => {
              dispatch(removeTable());
            }}
            allowClear
          />
        </Form.Item>
      </ProInputCard>
    </>
  );
}
