import React, { useEffect, useState } from "react";
import Skeleton from "react-loading-skeleton";

import {
  Input,
  InlineMessage,
  RadioButtons,
  KomiButton,
  useConfirmationModal,
  MultiSelect,
  IconToggle,
  HorzPosition,
  SubpageLayout
} from "@komi-app/components";

import {
  deleteModalContext,
  exportModalContext,
  noConsentModalContext,
  unsavedModalContext,
} from "./modals";

import { SegmentPropRule } from "./Segment/SegmentPropRule";
import { SegmentRuleSkeleton } from "./Segment/SegmentRuleSkeleton";


import { segmentMenuActionOptions } from "./constants/segments/labelMaps";


import {
  contactTypeOptionMap,
  emailMarketingOptionMap,
  deprecatedOptionMarketingMap,
  DeprecatedMarketingPermission,
  SegmentAttributeType,
  SegmentExpression,
  Segment,
  MarketingPermission,
  SegmentMode,
  SegmentMenuAction,
  SegmentPropertyAttribute,
  SegmentActionAttributeType,
  SegmentActionProperty,
  SegmentActionAttributeTag,
  SegmentAction,
  SegmentProperty,
  SegmentValue,
  SegmentActionAttribute,
} from "@komi-app/fans-sdk";
import { SelectOption, CommonSelectOptions } from "../BuilderPage/types/select";

import classnames from "classnames";
import "./SegmentPage.scss";
import { useUpdateEffect } from "hooks/useUpdateEffect";
import { SegmentActionRule } from "./Segment/SegmentActionRule";


export interface SegmentPageProps extends React.HTMLProps<HTMLDivElement> {
  contactCount: number;
  isMarketingPermissionFixEnabled?: boolean;
  isNavigatingWhenUnsaved?: boolean;
  loading?: boolean;
  mode?: SegmentMode;
  segment: Segment;
  segmentPropertyAttributes?: SegmentPropertyAttribute[];
  onBackClick: () => void;
  onMenuOptionClick: (action: SegmentMenuAction) => void;
  onSaveClick: (segment: Segment) => Promise<boolean>;
  onSegmentChange: (segment: Segment) => void;
}

export const SegmentPage: React.FC<SegmentPageProps> = ({
  contactCount = 0,
  isMarketingPermissionFixEnabled = false,
  isNavigatingWhenUnsaved = false,
  loading = false,
  mode = SegmentMode.Create,
  segment,
  segmentPropertyAttributes,
  onBackClick,
  onMenuOptionClick,
  onSaveClick,
  onSegmentChange,
}) => {
  const [isActionMenuVisible, setIsActionMenuVisible] = useState(false);
  const [isUnsaved, setIsUnsaved] = useState(false);
  const [notGrantedAcked, setNotGrantedAcked] = useState(false);

  const [errors, setErrors] = useState<Record<string, string>>({});

  const unsavedModal = useConfirmationModal();
  const deleteModal = useConfirmationModal();
  const noConsentModal = useConfirmationModal();
  const exportModal = useConfirmationModal();

  const actionExpressions = segment.expressions.filter(
    ({ attributeType }) => attributeType === SegmentAttributeType.Action
  );
  const propertyExpressions = segment.expressions.filter(
    ({ attributeType }) => attributeType === SegmentAttributeType.Property
  );

  const handlePropertyExpressionsChange = (
    expressions: SegmentExpression[]
  ) => {
    const updatedExpressions = [...actionExpressions, ...expressions];

    onSegmentChange({
      ...segment,
      expressions: updatedExpressions,
    });
  };

  const handleContactTypeChange = (selectedLabel: string) => {
    const contactTypeEntries = Object.entries(contactTypeOptionMap);
    const optionEntry = contactTypeEntries.find(
      ([_, label]) => label === selectedLabel
    );
    if (!optionEntry) return;

    const [option] = optionEntry;

    onSegmentChange({
      ...segment,
      contactType: option as keyof typeof contactTypeOptionMap,
    });
  };
  const handleMarketingChange = (selectedLabel: string) => {
    const marketingEntries = isMarketingPermissionFixEnabled
      ? Object.entries(emailMarketingOptionMap)
      : Object.entries(deprecatedOptionMarketingMap);

    const optionEntry = marketingEntries.find(
      ([_, label]) => label === selectedLabel
    );
    if (!optionEntry) return;

    const [option] = optionEntry;

    onSegmentChange({
      ...segment,
      marketingPermission: option as
        | MarketingPermission
        | DeprecatedMarketingPermission,
    });
  };
  const handleNameChange = (name: string) => {
    onSegmentChange({ ...segment, name });
  };

  const validateForm = () => {
    if (!segment.name) {
      setErrors({ name: "Segment name is required" });
      return false;
    }

    return true;
  };
  const saveForm = async () => {
    const isFormValid = validateForm();
    if (!isFormValid) return false;

    const saveResponse = await onSaveClick(segment);
    if (!saveResponse) return false;

    setIsUnsaved(false);
    return true;
  };

  const handleExitClick = () => {
    if (isUnsaved) {
      unsavedModal.open(
        unsavedModalContext({
          onConfirm: async () => {
            const saveResponse = await saveForm();
            if (saveResponse) onBackClick();
          },
          onCancel: () => {
            setIsUnsaved(false);
            onBackClick();
          },
        })
      );
    } else {
      onBackClick();
    }
  };
  const handleSaveClick = () => {
    if (
      !notGrantedAcked &&
      segment.marketingPermission !== MarketingPermission.EmailGranted
    ) {
      noConsentModal.open(
        noConsentModalContext({
          onConfirm: () => {
            setNotGrantedAcked(true);
            saveForm();
          },
        })
      );
    } else {
      saveForm();
    }
  };

  const handleMenuOptionsClick = ([actionOption]: SegmentMenuAction[]) => {
    switch (actionOption) {
      case SegmentMenuAction.Delete:
        return deleteModal.open(
          deleteModalContext({
            onConfirm: () => onMenuOptionClick(actionOption),
          })
        );

      case SegmentMenuAction.ExportCsv:
        return exportModal.open(
          exportModalContext({
            onConfirm: () => onMenuOptionClick(actionOption),
          })
        );

      default:
        return onMenuOptionClick(actionOption);
    }
  };

  /**
   * Handles unsaved navigation change.
   */
  useEffect(() => {
    if (isNavigatingWhenUnsaved) {
      unsavedModal.open(
        unsavedModalContext({
          onConfirm: () => {
            onSaveClick(segment);
          },
          onCancel: () => {
            onBackClick();
          },
        })
      );
    }
  }, [isNavigatingWhenUnsaved, segment, onBackClick, onSaveClick]);

  /**
   * Handles segment changes.
   */
  useUpdateEffect(() => {
    // Mark as unsaved if so
    setIsUnsaved(true);
  }, [segment]);

  const classNames = classnames("segment-page");
  const headingSuffixClassName = classnames("segment-page__more-icon", {
    "segment-page__more-icon--open": isActionMenuVisible,
  });

  return (
    <SubpageLayout
    onPrefixIconClick={handleExitClick}
    className={classNames}
    headingTitle="Edit Segment"
    headingSuffixIcon={
      <MultiSelect<SegmentMenuAction>
        options={segmentMenuActionOptions}
        isMultiselection={false}
        horzPosition={HorzPosition.Right}
        optionsClassName="segment-page__more-menu"
        wrapperClassName={headingSuffixClassName}
        onOptionValueSelectionChange={handleMenuOptionsClick}
        onVisibilityChange={setIsActionMenuVisible}
      >
        <MultiSelect.Toggle>
          <IconToggle name="more" width={24} height={24} className="segment-page__more-icon" />
        </MultiSelect.Toggle>
      </MultiSelect>
    }
  >
      <p className="segment-page__title">Audience</p>

      
      {/* <h4>Actions</h4>

      <InlineMessage
        className="segment-page__message-container"
        messageClassName="segment-page__message"
        message="Target audience members who have completed specific actions on your Komi page or campaigns."
      />
      <div className="segment-page__audience">
        <SegmentActionRule initialRule={initialRule} onSegmentChange={setRule} />
      </div> */}
     

      <p className="segment-page__subtitle">Properties</p>

      <InlineMessage
        className="segment-page__message-container"
        messageClassName="segment-page__message"
        message="Filter your audience based on demographic characteristics."
        closeable
      />

      {loading ? (
        <SegmentRuleSkeleton buttonName="Property" />
      ) : (
        <div className="segment-page__properties">
          <SegmentPropRule
            className="segment-page__properties-rule"
            segmentPropertyAttributes={segmentPropertyAttributes}
            expressions={propertyExpressions}
            onExpressionsChange={handlePropertyExpressionsChange}
          />
        </div>
      )}

      <div className="segment-page__contact-type">
        <p className="segment-page__subtitle">Contact Type</p>
        <RadioButtons
          containerClassName="segment-page__radios segment-page__contact-type-radios"
          options={Object.values(contactTypeOptionMap)}
          value={contactTypeOptionMap[segment.contactType]}
          onChange={handleContactTypeChange}
        />
      </div>
      <div className="segment-page__marketing">
        <p className="segment-page__subtitle">Marketing Permissions</p>
        <RadioButtons
          containerClassName="segment-page__radios segment-page__marketing-radios"
          options={
            isMarketingPermissionFixEnabled
              ? Object.values(emailMarketingOptionMap)
              : Object.values(deprecatedOptionMarketingMap)
          }
          value={
            isMarketingPermissionFixEnabled
              ? emailMarketingOptionMap[
                  segment.marketingPermission as MarketingPermission
                ]
              : deprecatedOptionMarketingMap[
                  segment.marketingPermission as DeprecatedMarketingPermission
                ]
          }
          onChange={handleMarketingChange}
        />
      </div>

      {segment.marketingPermission !== MarketingPermission.EmailGranted && (
        <InlineMessage
          className="segment-page__message-container"
          messageClassName="segment-page__message"
          type="warning"
          message={
            "In contacting individuals who haven't granted you marketing consents, you agree " +
            "to only do so in line with our terms of service, any applicable data sharing agreement, " +
            "your privacy policy and the relevant laws of your jurisdiction and the jurisdictions of " +
            "the individuals being contacted."
          }
        />
      )}

      <div
        className="segment-page__selection"
        data-testid="contact-count-block"
      >
        <p className="segment-page__selection-contact-count">
          {loading ? (
            <Skeleton
              className="segment-page__selection-contact-count-skeleton"
              width="182px"
              height="24px"
              highlightColor="#CEE9FF" // 20% between $color-blue-100 and white
              baseColor="#BBE1FF"
            />
          ) : (
            `${contactCount} contacts selected`
          )}
        </p>
        <p className="segment-page__selection-message">
          Future contacts that match the selected criteria will be added to this
          segment automatically.
        </p>
      </div>

      <div className="segment-page__name">
        <Input
          error={errors.name}
          value={segment.name}
          onValueChange={handleNameChange}
          className="segment-page__name-input"
          label="Segment name"
        />
      </div>

      <div className="segment-page__controls">
        <KomiButton onClick={handleExitClick} variant="light">
          Cancel
        </KomiButton>

        <KomiButton onClick={handleSaveClick} variant="dark">
          Save
        </KomiButton>
      </div>
    </SubpageLayout>
  );
};
