import ProText from "components/ProText.tsx";
import styles from "pages/product/product.module.css";
import ProCheckboxGroups from "components/ProCheckboxGroups/ProCheckboxGroups.tsx";
import { message } from "antd";
import { TheExtrasGroup } from "utils/types/appTypes.ts";
import { useAppSelector } from "redux/hooks.ts";

type Props = {
  group: TheExtrasGroup;
  selectedExtras: Array<string>;
  onChange: (values: Array<string>) => void;
};
export default function ExtrasGroup({
  group,
  selectedExtras,
  onChange,
}: Props) {
  const { isRTL } = useAppSelector((state) => state.locale);

  return (
    <div>
      <div
        style={{
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
        }}
      >
        <ProText strong style={{ fontSize: "1rem" }}>
          {isRTL ? group.nameAR : group.name}
        </ProText>
        <div
          style={{
            display: "flex",
            alignItems: "center",
            gap: "8px",
          }}
        >
          <ProText style={{ fontSize: "0.75rem", color: "#666" }}>
            {group.force_limit_selection === 1 ? "Required" : "Optional"}
          </ProText>
          <ProText style={{ fontSize: "0.75rem", color: "#666" }}>
            ({selectedExtras?.length || 0}/{group.limit})
          </ProText>
        </div>
      </div>

      {group.force_limit_selection === 1 && (
        <ProText
          style={{
            fontSize: "0.75rem",
            color: "red",
            marginBottom: "8px",
          }}
        >
          * You must select exactly {group.limit} option
          {group.limit > 1 ? "s" : ""}
        </ProText>
      )}

      <div className={styles.productContainer}>
        <ProCheckboxGroups
          options={group.extras.map((extra: any) => ({
            value: extra.id.toString(),
            label: isRTL ? extra.name : extra.nameAR,
            price: `+${extra.price}`,
          }))}
          value={selectedExtras}
          onChange={(values: string[]) => {
            // Check if the new selection would exceed the limit
            if (values.length > group.limit) {
              message.error(
                `You can only select up to ${group.limit} option${group.limit > 1 ? "s" : ""} from this group.`,
              );
              return;
            }
            onChange(
              group.extras
                .filter((o) => values?.includes(o.id.toString()))
                .map((e) => e.id.toString()) || [],
            );
          }}
        />
      </div>
    </div>
  );
}
