import type { MembershipClubChargeCenter } from "@/lib/features/charge-centers/models";
import type { MemberAccountStatus } from "@/lib/features/member-account-status/models";
import type { MembershipClub } from "@/lib/features/membership-clubs/models";
import type { Membership } from "@/lib/features/memberships/models";
import { useCoreFetcher } from "@/lib/features/useCoreFetcher";
import {
  Button,
  Flex,
  Grid,
  Menu,
  MultiSelect,
  NativeSelect,
  Stack,
  Tabs,
  Text,
  Textarea,
  TextInput,
  Title,
} from "@mantine/core";
import { useForm, type UseFormReturnType } from "@mantine/form";
import { IconPlus, IconSettings, IconX } from "@tabler/icons-react";
import { zod4Resolver } from "mantine-form-zod-resolver";
import type { GetInputPropsReturnType } from "node_modules/@mantine/form/lib/types";
import { useEffect, useMemo, useState } from "react";
import { toast } from "sonner";
import { z } from "zod";
import { AccessRestrictionSettings } from "../_widgets/accessSettingsDrawer";

const BasePolicyOptions = [
  {
    label: "FULL ACCESS",
    value: "FULL_ACCESS",
    access_settings: false,
  },
  {
    label: "BLOCKED",
    value: "BLOCKED",
    access_settings: true,
  },
];

const GenralPolicyOptions = [
  ...BasePolicyOptions,
  {
    label: "READ ACCESS",
    value: "READ_ONLY",
    access_settings: true,
  },
];

const BookingAddOnPolicyOptions = [
  ...GenralPolicyOptions,
  {
    label: "BlOCK BOOKING COMPLETION",
    value: "BLOCK_BOOKING_COMPLETION",
    access_settings: true,
  },
];
const statusSchema = z.object({
  id: z.string({
    message: "Account status ID is required",
  }),
  name: z.string({
    message: "Account status name is required",
  }),
  ext_account_status_id: z.string({
    message: "Account status name is required",
  }),
  city_stopovers: z
    .string({
      message: "City Stopovers access policy is required",
    })
    .default("FULL_ACCESS"),
  curated_events: z
    .string({
      message: "Curated events access policy is required",
    })
    .default("FULL_ACCESS"),
  internal_properties: z
    .string({
      message: "Internal properties access policy is required",
    })
    .default("FULL_ACCESS"),
  hot_deals: z
    .string({
      message: "Hot deals access policy is required",
    })
    .default("FULL_ACCESS"),
  karma_alliance: z
    .string({
      message: "Karma alliance access policy is required",
    })
    .default("FULL_ACCESS"),
  karma_alliance_offers: z
    .string({
      message: "Karma alliance offers access policy is required",
    })
    .default("FULL_ACCESS"),
  karma_getaway: z
    .string({
      message: "Karma getaway access policy is required",
    })
    .default("FULL_ACCESS"),
  karma_getaway_offers: z
    .string({
      message: "Karma getaway offers access policy is required",
    })
    .default("FULL_ACCESS"),
  karma_nomad: z
    .string({
      message: "Karma nomad access policy is required",
    })
    .default("FULL_ACCESS"),
  karma_registry_collection: z
    .string({
      message: "Karma registry collection access policy is required",
    })
    .default("FULL_ACCESS"),
  login: z
    .boolean({
      message: "Login access policy is required",
    })
    .default(true),
  member_privileges_travel: z
    .string({
      message: "Member privileges travel access policy is required",
    })
    .default("FULL_ACCESS"),
  profile: z
    .string({
      message: "Profile access policy is required",
    })
    .default("FULL_ACCESS"),
  rci_exchange: z
    .string({
      message: "RCI Exchange access policy is required",
    })
    .default("FULL_ACCESS"),
  rci_rental: z
    .string({
      message: "RCI Rental access policy is required",
    })
    .default("FULL_ACCESS"),
  reciprocal_partners: z
    .string({
      message: "Reciprocal partners access policy is required",
    })
    .default("FULL_ACCESS"),
  twoforone: z
    .string({
      message: "241 Rewards access policy is required",
    })
    .default("FULL_ACCESS"),
  restrictions: z.record(z.string(), z.any()).optional().nullable(),
});

const schema = z.object({
  clubName: z
    .string({ message: "Club name is required" })
    .min(1, "Club name is required"),
  clubID: z
    .string({ message: "Club ID is required" })
    .min(1, "Club Id is required"),
  account_types: z
    .array(z.string(), {
      message: "Membership type is required",
    })
    .min(1, { message: "At least one membership type is required" }),
  status_policies: z
    .array(statusSchema, { message: "All status policies are required" })
    .default([]),
  note: z.string().optional(),
  charge_centers: z
    .array(z.string())
    // .min(1, { message: "At least one club charge center is required" }),
    .optional(),
});

type SchemaType = z.infer<typeof schema>;

const MembershipClubForm: React.FC<{
  account_statuses: MemberAccountStatus[];
  memberships: Membership[];
  membershipClub?: MembershipClub;
  chargeCenters: MembershipClubChargeCenter[];
}> = ({ account_statuses, memberships, membershipClub, chargeCenters }) => {
  const { trigger: createTrigger, isLoading: createLoading } = useCoreFetcher(
    "create-membership-club",
    "post",
    {
      onSuccess: () => {
        toast.success("Membership Club created successfully");
        form.reset();
      },
      onError: (error) =>
        toast.error(
          (error as Error)?.message ?? "Failed to create Membership Club",
        ),
    },
  );
  const { trigger: updateTrigger, isLoading: updateLoading } = useCoreFetcher(
    "update-membership-club",
    "patch",
    {
      onSuccess: () => toast.success("Membership Club Updated successfully"),
      onError: (error) =>
        toast.error(
          (error as Error)?.message ?? "Failed to update Membership Club",
        ),
    },
  );

  const form = useForm<SchemaType>({
    initialValues: {
      clubName: membershipClub?.clubName ?? "",
      clubID: membershipClub?.clubID ?? "",
      account_types:
        (membershipClub?.account_types ?? [])?.map((item) =>
          item?.id?.toString(),
        ) ?? [],
      status_policies: (membershipClub?.statuses ?? [])?.map((item) => ({
        ...item,
        id: item.id.toString(),
      })),
      note: membershipClub?.note ?? "",
      charge_centers: membershipClub?.charge_centers?.map((cc) => cc.id) ?? [],
    },
    validate: zod4Resolver(schema),
  });

  const [activeStatusTab, setActiveStatusTab] = useState<string | null>(
    form
      .getValues()
      ?.status_policies?.map(
        ({ ext_account_status_id }) => ext_account_status_id,
      )[0] ?? null,
  );

  const handleAddAccountStatusPolicy = (
    id: string,
    name: string,
    ext_account_status_id: string,
  ) => {
    form.setFieldValue("status_policies", (prev) => [
      ...prev,
      {
        id: id,
        name: name,
        ext_account_status_id: ext_account_status_id,
        city_stopovers: "FULL_ACCESS",
        curated_events: "FULL_ACCESS",
        internal_properties: "FULL_ACCESS",
        hot_deals: "FULL_ACCESS",
        karma_alliance: "FULL_ACCESS",
        karma_alliance_offers: "FULL_ACCESS",
        karma_getaway: "FULL_ACCESS",
        karma_getaway_offers: "FULL_ACCESS",
        karma_nomad: "FULL_ACCESS",
        karma_registry_collection: "FULL_ACCESS",
        login: true,
        member_privileges_travel: "FULL_ACCESS",
        profile: "FULL_ACCESS",
        rci_exchange: "FULL_ACCESS",
        rci_rental: "FULL_ACCESS",
        reciprocal_partners: "FULL_ACCESS",
        twoforone: "FULL_ACCESS",
        restrictions: null,
      },
    ]);
    setActiveStatusTab(ext_account_status_id);
  };

  const handleRemoveAccountStatusPolicy = (id: string) => {
    const formStatusPolicies = form.values.status_policies;
    const currentActiveTab = formStatusPolicies.findIndex(
      (item) => item.ext_account_status_id === id,
    );
    if (currentActiveTab !== -1) {
      if (currentActiveTab === 0 && formStatusPolicies?.length > 1) {
        setActiveStatusTab(formStatusPolicies[1].ext_account_status_id);
      } else if (currentActiveTab > 0) {
        const nextTab =
          formStatusPolicies[currentActiveTab - 1].ext_account_status_id;
        setActiveStatusTab(nextTab);
      }
    }
    form.setFieldValue("status_policies", (prev) => {
      const newList = prev.filter((p) => p.ext_account_status_id !== id);
      return newList;
    });
  };

  const usedStatuses = form.getValues().status_policies;
  const unUsedStatuses = useMemo(() => {
    return account_statuses.filter(
      (as) => !usedStatuses.find((us) => us.id === as.id),
    );
  }, [usedStatuses]);

  const handleSubmit = async () => {
    const result = form.validate();
    if (!result.hasErrors) {
      const parsed = schema.safeParse(form.values);
      if (parsed.success) {
        const { status_policies, ...restData } = parsed.data;
        const payload = {
          ...restData,
          account_types: parsed?.data?.account_types?.map((at) => ({
            id: at,
          })),
          charge_centers: parsed?.data?.charge_centers?.map((cc) => ({
            id: cc,
          })),
          statuses: status_policies?.map((sp) => {
            const { id, restrictions, ...access_policies } = sp;
            // Transform restrictions if they exist
            const transformedRestrictions = restrictions
              ? Object.entries(restrictions)?.reduce(
                  (acc: Record<string, unknown>, [key, value]) => {
                    // Check if subito_error already exists
                    if (value.subito_error) {
                      // If subito_error exists, use it directly but transform alert_variants
                      acc[key] = {
                        subito_error: {
                          ...value.subito_error,
                          alert_variants: Array.isArray(
                            value.subito_error.alert_variants,
                          )
                            ? value.subito_error.alert_variants?.[0]
                            : value.subito_error.alert_variants,
                        },
                      };
                    } else {
                      // If subito_error doesn't exist, create it
                      acc[key] = {
                        subito_error: {
                          ...value,
                          alert_variants: value.alert_variants?.[0] || null,
                        },
                      };
                    }
                    return acc;
                  },
                  {},
                )
              : null;
            return {
              id,
              access_policies: {
                ...access_policies,
                restrictions: transformedRestrictions,
              },
            };
          }),
        };
        if (membershipClub?.id) {
          await updateTrigger(payload);
        } else {
          await createTrigger(payload);
        }
      }
    }
  };
  return (
    <Stack bg={"grey.0"} mih={"100vh"} p={"sm"}>
      <form>
        <Stack gap={20}>
          <Stack bg={"white.0"} p={"sm"} bdrs={"sm"}>
            <Title order={6}>Membership Club Details</Title>
            <Grid columns={6} gutter={"lg"}>
              <Grid.Col span={3}>
                <TextInput
                  label="Club Name"
                  placeholder="Enter club name"
                  key={form.key("clubName")}
                  {...form.getInputProps("clubName")}
                />
              </Grid.Col>
              <Grid.Col span={3}>
                <TextInput
                  label="Club ID"
                  placeholder="Enter club ID"
                  key={form.key("clubID")}
                  {...form.getInputProps("clubID")}
                />
              </Grid.Col>
              <Grid.Col span={3}>
                <MultiSelect
                  label="Membership"
                  data={memberships.map(
                    ({ name, ext_account_type_id, id }) => ({
                      label: `${name} (${ext_account_type_id})`,
                      value: id,
                    }),
                  )}
                  searchable
                  key={form.key("account_types")}
                  {...form.getInputProps("account_types")}
                />
              </Grid.Col>
              <Grid.Col span={3}>
                <MultiSelect
                  label="Club Charge Center"
                  placeholder="Pick value"
                  data={chargeCenters.map(({ id, currency }) => ({
                    label: currency,
                    value: id,
                  }))}
                  searchable
                  key={form.key("charge_centers")}
                  {...form.getInputProps("charge_centers")}
                />
              </Grid.Col>
              <Grid.Col span={6}>
                <Textarea
                  rows={5}
                  label="Note"
                  key={form.key("note")}
                  {...form.getInputProps("note")}
                />
              </Grid.Col>
            </Grid>
          </Stack>
          <Stack
            bg={"white.0"}
            p={"sm"}
            bdrs={"sm"}
            style={{ overflowX: "hidden" }}
          >
            <Title order={6}>Status Policies</Title>

            <Tabs value={activeStatusTab}>
              <Tabs.List
                style={{
                  flexWrap: "nowrap",
                  overflowX: "scroll",
                  overflowY: "hidden",
                }}
                className="hide-scrollbar"
                mb={24}
              >
                {form
                  .getValues()
                  .status_policies.map(({ name, ext_account_status_id }) => (
                    <Tabs.Tab
                      key={ext_account_status_id}
                      value={ext_account_status_id}
                      pos={"relative"}
                      // onClick={() => setActiveStatusTab(ext_account_status_id)}
                    >
                      <Stack
                        onClick={() =>
                          setActiveStatusTab(ext_account_status_id)
                        }
                      >
                        {`${name}(${ext_account_status_id})`}
                      </Stack>
                      <Button
                        variant="subtle"
                        size="compact-xs"
                        onClick={() =>
                          handleRemoveAccountStatusPolicy(ext_account_status_id)
                        }
                        pos={"absolute"}
                        top={-4}
                        right={-8}
                        bdrs={1000}
                        p={0}
                      >
                        <IconX size={12} />
                      </Button>
                    </Tabs.Tab>
                  ))}
                {unUsedStatuses.length > 0 && (
                  <StatusesMenu
                    statuses={unUsedStatuses}
                    onStatusSelect={handleAddAccountStatusPolicy}
                  />
                )}
              </Tabs.List>

              {form
                .getValues()
                .status_policies.map(({ ext_account_status_id }, index) => {
                  return (
                    <Tabs.Panel
                      key={ext_account_status_id}
                      value={ext_account_status_id}
                    >
                      <StatusPolicy index={index} form={form} />
                    </Tabs.Panel>
                  );
                })}
            </Tabs>
          </Stack>
        </Stack>
        <Flex justify={"end"} mt={20}>
          <Button
            variant="filled"
            bg="blue.1"
            c="blue.9"
            onClick={handleSubmit}
            loading={createLoading || updateLoading}
          >
            Save
          </Button>
        </Flex>
      </form>
    </Stack>
  );
};

const StatusesMenu: React.FC<{
  statuses: { id: string; name: string; ext_account_status_id: string }[];
  onStatusSelect: (
    id: string,
    name: string,
    ext_account_status_id: string,
  ) => void;
}> = ({ statuses, onStatusSelect }) => {
  return (
    <Menu shadow="md" width={250}>
      <Menu.Target>
        <Button ml={14} size="compact-sm" bg={"grey.2"} c={"grey.8"} px={6}>
          <IconPlus size={14} />
        </Button>
      </Menu.Target>

      <Menu.Dropdown mah={300} style={{ overflowY: "scroll" }}>
        <Menu.Label>Availabel Statuses</Menu.Label>
        {statuses.map(({ id, name, ext_account_status_id }) => (
          <Menu.Item
            key={id}
            onClick={() => onStatusSelect(id, name, ext_account_status_id)}
          >
            {`${name}(${ext_account_status_id})`}
          </Menu.Item>
        ))}
      </Menu.Dropdown>
    </Menu>
  );
};

const StatusPolicy: React.FC<{
  index: number;
  form: UseFormReturnType<SchemaType>;
}> = ({ index, form }) => {
  const handleAddRestrictions = (
    key: string,
    value: Record<string, unknown>,
  ) => {
    form.setFieldValue(`status_policies.${index}.restrictions`, (prev) => ({
      ...prev,
      [key]: value,
    }));
  };
  const handleRemoveRestrictions = (key: string) => {
    form.setFieldValue(`status_policies.${index}.restrictions`, (prev) => {
      const obj = { ...prev };
      if (obj?.[key]) {
        delete obj[key];
      }

      return obj;
    });
  };
  const restrictions = form.getValues().status_policies[index]
    .restrictions as Record<string, Record<string, unknown>>;
  return (
    <Stack gap={40}>
      <Grid gutter={20}>
        <Grid.Col span={6}>
          <Stack gap={8}>
            <Text fw={"bold"} fz={14}>
              Users Access Policy
            </Text>
            <Grid columns={2}>
              <Grid.Col span={1}>
                <PolicySelectField
                  label="Login Access"
                  options={BasePolicyOptions}
                  formKey={form.key(`status_policies.${index}.login`)}
                  formInputProps={form.getInputProps(
                    `status_policies.${index}.login`,
                  )}
                  onAddRestrictions={(value) =>
                    handleAddRestrictions("login", value)
                  }
                  onRemoveRestrictions={() => handleRemoveRestrictions("login")}
                  restrictions={restrictions?.login}
                />
              </Grid.Col>
              <Grid.Col span={1}>
                <PolicySelectField
                  label="Profile Access"
                  options={GenralPolicyOptions}
                  formKey={form.key(`status_policies.${index}.profile`)}
                  formInputProps={form.getInputProps(
                    `status_policies.${index}.profile`,
                  )}
                  onAddRestrictions={(value) =>
                    handleAddRestrictions("profile", value)
                  }
                  onRemoveRestrictions={() =>
                    handleRemoveRestrictions("profile")
                  }
                  restrictions={restrictions?.profile}
                />
              </Grid.Col>
            </Grid>
          </Stack>
        </Grid.Col>
        <Grid.Col span={6}>
          <Stack gap={8}>
            <Text fw={"bold"} fz={14}>
              Internal Access Policy
            </Text>
            <Grid columns={2}>
              <Grid.Col span={1}>
                <PolicySelectField
                  label="Internal Properties Access"
                  options={BookingAddOnPolicyOptions}
                  formKey={form.key(
                    `status_policies.${index}.internal_properties`,
                  )}
                  formInputProps={form.getInputProps(
                    `status_policies.${index}.internal_properties`,
                  )}
                  onAddRestrictions={(value) =>
                    handleAddRestrictions("internal_properties", value)
                  }
                  onRemoveRestrictions={() =>
                    handleRemoveRestrictions("internal_properties")
                  }
                  restrictions={restrictions?.internal_properties}
                />
              </Grid.Col>
              <Grid.Col span={1}>
                <PolicySelectField
                  label="Curated Events Access"
                  options={BookingAddOnPolicyOptions}
                  formKey={form.key(`status_policies.${index}.curated_events`)}
                  formInputProps={form.getInputProps(
                    `status_policies.${index}.curated_events`,
                  )}
                  onAddRestrictions={(value) =>
                    handleAddRestrictions("curated_events", value)
                  }
                  onRemoveRestrictions={() =>
                    handleRemoveRestrictions("curated_events")
                  }
                  restrictions={restrictions?.curated_events}
                />
              </Grid.Col>
            </Grid>
          </Stack>
        </Grid.Col>
      </Grid>
      <Stack gap={8}>
        <Text fw={"bold"} fz={14}>
          External Access Policy
        </Text>
        <Grid columns={4}>
          <Grid.Col span={1}>
            <PolicySelectField
              label="Reciprocal Partners Access"
              options={BasePolicyOptions}
              formKey={form.key(`status_policies.${index}.reciprocal_partners`)}
              formInputProps={form.getInputProps(
                `status_policies.${index}.reciprocal_partners`,
              )}
              onAddRestrictions={(value) =>
                handleAddRestrictions("reciprocal_partners", value)
              }
              onRemoveRestrictions={() =>
                handleRemoveRestrictions("reciprocal_partners")
              }
              restrictions={restrictions?.reciprocal_partners}
            />
          </Grid.Col>
          <Grid.Col span={1}>
            <PolicySelectField
              label="Karma Alliance Access"
              options={GenralPolicyOptions}
              formKey={form.key(`status_policies.${index}.karma_alliance`)}
              formInputProps={form.getInputProps(
                `status_policies.${index}.karma_alliance`,
              )}
              onAddRestrictions={(value) =>
                handleAddRestrictions("karma_alliance", value)
              }
              onRemoveRestrictions={() =>
                handleRemoveRestrictions("karma_alliance")
              }
              restrictions={restrictions?.karma_alliance}
            />
          </Grid.Col>
          <Grid.Col span={1}>
            <PolicySelectField
              label="Karma Getaways Access"
              options={GenralPolicyOptions}
              formKey={form.key(`status_policies.${index}.karma_getaway`)}
              formInputProps={form.getInputProps(
                `status_policies.${index}.karma_getaway`,
              )}
              onAddRestrictions={(value) =>
                handleAddRestrictions("karma_getaway", value)
              }
              onRemoveRestrictions={() =>
                handleRemoveRestrictions("karma_getaway")
              }
              restrictions={restrictions?.karma_getaway}
            />
          </Grid.Col>
          <Grid.Col span={1}>
            <PolicySelectField
              label="Karma Nomad Access"
              options={BasePolicyOptions}
              formKey={form.key(`status_policies.${index}.karma_nomad`)}
              formInputProps={form.getInputProps(
                `status_policies.${index}.karma_nomad`,
              )}
              onAddRestrictions={(value) =>
                handleAddRestrictions("karma_nomad", value)
              }
              onRemoveRestrictions={() =>
                handleRemoveRestrictions("karma_nomad")
              }
              restrictions={restrictions?.karma_nomad}
            />
          </Grid.Col>
          <Grid.Col span={1}>
            <PolicySelectField
              label="Karma Registry Collection Access"
              options={BasePolicyOptions}
              formKey={form.key(
                `status_policies.${index}.karma_registry_collection`,
              )}
              formInputProps={form.getInputProps(
                `status_policies.${index}.karma_registry_collection`,
              )}
              onAddRestrictions={(value) =>
                handleAddRestrictions("karma_registry_collection", value)
              }
              onRemoveRestrictions={() =>
                handleRemoveRestrictions("karma_registry_collection")
              }
              restrictions={restrictions?.karma_registry_collection}
            />
          </Grid.Col>
          <Grid.Col span={1}>
            <PolicySelectField
              label="KWE/RCI Exchange Access"
              options={BookingAddOnPolicyOptions}
              formKey={form.key(`status_policies.${index}.rci_exchange`)}
              formInputProps={form.getInputProps(
                `status_policies.${index}.rci_exchange`,
              )}
              onAddRestrictions={(value) =>
                handleAddRestrictions("rci_exchange", value)
              }
              onRemoveRestrictions={() =>
                handleRemoveRestrictions("rci_exchange")
              }
              restrictions={restrictions?.rci_exchange}
            />
          </Grid.Col>
          <Grid.Col span={1}>
            <PolicySelectField
              label="KNE/RCI Rental Access"
              options={BookingAddOnPolicyOptions}
              formKey={form.key(`status_policies.${index}.rci_rental`)}
              formInputProps={form.getInputProps(
                `status_policies.${index}.rci_rental`,
              )}
              onAddRestrictions={(value) =>
                handleAddRestrictions("rci_rental", value)
              }
              onRemoveRestrictions={() =>
                handleRemoveRestrictions("rci_rental")
              }
              restrictions={restrictions?.rci_rental}
            />
          </Grid.Col>
          <Grid.Col span={1}>
            <PolicySelectField
              label="241 Rewards Access"
              options={BasePolicyOptions}
              formKey={form.key(`status_policies.${index}.twoforone`)}
              formInputProps={form.getInputProps(
                `status_policies.${index}.twoforone`,
              )}
              onAddRestrictions={(value) =>
                handleAddRestrictions("twoforone", value)
              }
              onRemoveRestrictions={() => handleRemoveRestrictions("twoforone")}
              restrictions={restrictions?.twoforone}
            />
          </Grid.Col>
          <Grid.Col span={1}>
            <PolicySelectField
              label="Member Privileges Travels Access"
              options={BasePolicyOptions}
              formKey={form.key(
                `status_policies.${index}.member_privileges_travel`,
              )}
              formInputProps={form.getInputProps(
                `status_policies.${index}.member_privileges_travel`,
              )}
              onAddRestrictions={(value) =>
                handleAddRestrictions("member_privileges_travel", value)
              }
              onRemoveRestrictions={() =>
                handleRemoveRestrictions("member_privileges_travel")
              }
              restrictions={restrictions?.member_privileges_travel}
            />
          </Grid.Col>
        </Grid>
      </Stack>
      <Stack gap={8}>
        <Text fw={"bold"} fz={14}>
          Offers Access Policy
        </Text>
        <Grid columns={3}>
          <Grid.Col span={1}>
            <PolicySelectField
              label="Hot Deals Access"
              options={BookingAddOnPolicyOptions}
              formKey={form.key(`status_policies.${index}.hot_deals`)}
              formInputProps={form.getInputProps(
                `status_policies.${index}.hot_deals`,
              )}
              onAddRestrictions={(value) =>
                handleAddRestrictions("hot_deals", value)
              }
              onRemoveRestrictions={() => handleRemoveRestrictions("hot_deals")}
              restrictions={restrictions?.hot_deals}
            />
          </Grid.Col>
          <Grid.Col span={1}>
            <PolicySelectField
              label={"Karma Alliance(Offers) Access"}
              options={BookingAddOnPolicyOptions}
              formKey={form.key(
                `status_policies.${index}.karma_alliance_offers`,
              )}
              formInputProps={form.getInputProps(
                `status_policies.${index}.karma_alliance_offers`,
              )}
              onAddRestrictions={(value) =>
                handleAddRestrictions("karma_alliance_offers", value)
              }
              onRemoveRestrictions={() =>
                handleRemoveRestrictions("karma_alliance_offers")
              }
              restrictions={restrictions?.karma_alliance_offers}
            />
          </Grid.Col>
          <Grid.Col span={1}>
            <PolicySelectField
              label="Karma Getaways(Offers) Access"
              options={BookingAddOnPolicyOptions}
              formKey={form.key(
                `status_policies.${index}.karma_getaway_offers`,
              )}
              formInputProps={form.getInputProps(
                `status_policies.${index}.karma_getaway_offers`,
              )}
              onAddRestrictions={(value) =>
                handleAddRestrictions("karma_getaway_offers", value)
              }
              onRemoveRestrictions={() =>
                handleRemoveRestrictions("karma_getaway_offers")
              }
              restrictions={restrictions?.karma_getaway_offers}
            />
          </Grid.Col>
        </Grid>
      </Stack>
    </Stack>
  );
};

const PolicySelectField: React.FC<{
  label: string;
  options: { label: string; value: string; access_settings: boolean }[];
  formKey: string;
  formInputProps: GetInputPropsReturnType;
  onAddRestrictions?: (value: Record<string, unknown>) => void;
  onRemoveRestrictions?: () => void;
  restrictions?: Record<string, unknown> | null;
}> = ({
  label,
  options,
  formInputProps,
  formKey,
  onAddRestrictions,
  onRemoveRestrictions,
  restrictions,
}) => {
  const [openDrawer, setOpenDrawer] = useState(false);

  const showAccessSettings = useMemo(() => {
    return (
      options.find((op) => op.value === formInputProps.value)
        ?.access_settings ?? false
    );
  }, [formInputProps.value]);
  useEffect(() => {
    if (!showAccessSettings && restrictions && onRemoveRestrictions) {
      onRemoveRestrictions();
    }
  }, [showAccessSettings, restrictions]);
  return (
    <Grid align="center" gutter={6}>
      <Grid.Col span={10}>
        <NativeSelect
          label={label}
          data={options.map(({ label, value }) => ({ label, value }))}
          key={formKey}
          {...formInputProps}
        />
      </Grid.Col>
      {showAccessSettings && (
        <Grid.Col span={2}>
          <Button
            variant={"transparent"}
            size={"compact-sm"}
            mt={18}
            p={0}
            onClick={() => setOpenDrawer(true)}
          >
            <IconSettings size={18} />
          </Button>
        </Grid.Col>
      )}
      <AccessRestrictionSettings
        policy={{
          policy_type: label,
          access_type: formInputProps.value as string,
        }}
        openDrawer={openDrawer}
        onDrawerClose={() => setOpenDrawer(false)}
        onSave={(record) => {
          if (onAddRestrictions) {
            onAddRestrictions(record);
          }
        }}
        value={restrictions?.subito_error as Record<string, unknown>}
      />
    </Grid>
  );
};

export default MembershipClubForm;
