import React, { useMemo, useState, useEffect } from 'react';

// Hooks
import { useDispatch, useSelector } from 'react-redux';
import { RootState } from '~/redux/reducers';
import { AppDispatch } from '~/redux/store';

// Actions
import { SET_ROS_OFFER_PERCENTAGE } from '../../../redux/actions/action-types';
import { failure } from '../../../redux/actions/snackbarActions';

// Utils
import { MESSAGES } from '../../../utils/message';
import { getEnv, getIsSandbox, getPublicApiKey } from '../../../utils/helper';
import { DEMO_PO_GENERATOR_URL, PROD_PO_GENERATOR_URL, STAGE_PO_GENERATOR_URL } from '../../../utils/constants';

// Components
import Dialog from '../../GenericUIBlocks/Dialog';
import DialogV2 from '../../GenericUIBlocks/Dialog/V2';
import Input from '../../GenericUIBlocks/Input';

// Icons
import Save from '../../../assets/images/modal-icons/save';

// Styles
import './styles.scss';


/**
 * Renders a modal dialog for deleting a template.
 *
 * @param {function} handleSave - Callback function to handle the save action.
 * @param {function} handleClose - Callback function to handle the close action.
 * @param {boolean} open - Boolean value indicating whether the modal is open or not.
 * @returns {JSX.Element} The delete template modal component.
 */

const saveDialogStyles = {
  maxWidth: '433px',
  minHeight: '280px',
};

interface SaveTemplateModelProps {
  open: boolean;
  loading: boolean;
  handleClose: () => void;
  handleSave: () => void;
  store: any; // StoreType if available
  allowedAddOns?: any;
  currentTheme?: string | null | undefined;
}

const SaveTemplateModel: React.FC<SaveTemplateModelProps> = ({
  handleSave,
  handleClose,
  open,
  loading,
  store,
  allowedAddOns,
  currentTheme,
}) => {
  const [customRosInput, setCustomRosInput] = useState("");

  const dispatch: AppDispatch = useDispatch();

  const currentOfferPercentage = useSelector(
    (state: RootState) => state.templates.offerPercentage
  ) as string;

  const propertyOfferGeneratorURL: string =
    (getEnv() === 'local' || getEnv() === 'staging'
      ? STAGE_PO_GENERATOR_URL
      : getIsSandbox()
        ? DEMO_PO_GENERATOR_URL
        : PROD_PO_GENERATOR_URL) + `?apiKey=${getPublicApiKey()}`;

  const enableCustomRos = allowedAddOns?.includes('custom_property_offer');

  const rosFieldExists = useMemo(() => {
    if (!enableCustomRos || !store?.pages) return false;
    for (const page of store.pages) {
      for (const el of page.children) {
        if (el.text === '{{ROS.PROPERTY_OFFER}}' ) {
          return true
        }
      }
    }
    return false;
  }, [enableCustomRos, store]);

  const handleCustomRosChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const val = e.target.value;
    if (val === "") {
      setCustomRosInput("");
      dispatch({ type: SET_ROS_OFFER_PERCENTAGE, payload: "" });
      return;
    }
    const num = Number(val);
    if (!isNaN(num) && num >= 1 && num <= 100) {
      setCustomRosInput(val);
      dispatch({ type: SET_ROS_OFFER_PERCENTAGE, payload: val });
    } else {
      dispatch(failure("Please enter a number between 1 and 100"));
    }
  };

  useEffect(() => {
    if (!enableCustomRos) return;
    setCustomRosInput(currentOfferPercentage || "");
  }, []);

  // Custom content for the dialog
  const customContent = (
    enableCustomRos ? (
      <div style={{ display: "flex", flexDirection: "column", gap: 0, marginBottom: 32 }}>
        <div>
          {MESSAGES.TEMPLATE.SAVE.PARAGRAPH}
        </div>
        <div style={{ marginTop: 10, marginBottom: 35}}>
          <label style={{ fontWeight: 500, marginBottom: 4, display: "block", textAlign: 'center' }}>
            Confirm Custom ROS Value
          </label>
          <div className='plain-text' style={{
            textAlign: 'center',
          }}>
            <a href={propertyOfferGeneratorURL} target='_blank'
            style={{
              color: 'var(--primary-color)',
            }}
              onClick={(e) => {
                e.stopPropagation()
              }}
            >
              {MESSAGES.TEMPLATE.CUSTOM_ADD_ONS.PROPERTY_OFFER.CUSTOM.CLICK}
            </a>{' '}
            {MESSAGES.TEMPLATE.CUSTOM_ADD_ONS.PROPERTY_OFFER.CUSTOM.CSV_IMPORT}
          </div>
          <Input
            type="number"
            onlyNumber={true}
            placeholder="Type in a Number between 1-100"
            value={customRosInput}
            onChange={handleCustomRosChange}
          />
        </div>
      </div>
    ) : null
  );

  // Custom submit handler with validation
  const handleSubmit = () => {
    if (enableCustomRos && rosFieldExists && !customRosInput) {
      dispatch(failure("Please enter the offer percentage before saving the template"))
      return;
    }
    handleSave();
  };

  return (
    currentTheme === 'v2' ?
      <DialogV2
        icon={<Save fill="var(--primary-color)" />}
        open={open}
        loading={loading}
        handleClose={handleClose}
        title={MESSAGES.TEMPLATE.SAVE.TITLE}
        subHeading={MESSAGES.TEMPLATE.SAVE.HEADING}
        // Show custom content if rosCustomValue exists, else default description
        description={enableCustomRos && rosFieldExists ? undefined : MESSAGES.TEMPLATE.SAVE.PARAGRAPH}
        cancelText={MESSAGES.TEMPLATE.SAVE.CANCEL_BUTTON}
        submitText={MESSAGES.TEMPLATE.SAVE.SUBMIT_BUTTON}
        customStyles={{...saveDialogStyles, padding: '40px', maxWidth: enableCustomRos && rosFieldExists ? '620px' : '550px'}}
        onSubmit={handleSubmit}
        onCancel={handleClose}
        currentTheme="v2"
        isGallery={false}
      >
        {enableCustomRos && rosFieldExists && customContent}
      </DialogV2>
      :
      <Dialog
        icon={<Save fill="var(--primary-color)" />}
        open={open}
        loading={loading}
        handleClose={handleClose}
        title={MESSAGES.TEMPLATE.SAVE.TITLE}
        subHeading={MESSAGES.TEMPLATE.SAVE.HEADING}
        // Show custom content if rosCustomValue exists, else default description
        description={enableCustomRos && rosFieldExists ? undefined : MESSAGES.TEMPLATE.SAVE.PARAGRAPH}
        cancelText={MESSAGES.TEMPLATE.SAVE.CANCEL_BUTTON}
        submitText={MESSAGES.TEMPLATE.SAVE.SUBMIT_BUTTON}
        customStyles={{...saveDialogStyles, maxWidth: enableCustomRos && rosFieldExists ? '620px' : '433px'}}
        onSubmit={handleSubmit}
        onCancel={handleClose}
      >
        {enableCustomRos && rosFieldExists && customContent}
      </Dialog>
  );
};

export default SaveTemplateModel;
