import { Card } from "antd";
import classNames from "classnames";
import React, { useEffect, useState } from "react";
import "./DataCaptureCreationPreview.scss";
import {
  DataCaptureCard,
  DataCaptureMethod,
  InlineMessage,
  Theme,
  ThemeType,
} from "@komi-app/components";
import { useTypedSelector } from "redux/rootReducer";
import { selectUserData } from "redux/User/selector";
import { TalentProfileThemeTypes } from "redux/User/types";
import { DataCaptureType } from "@komi-app/components";
import { DCAFormStepsProps, getPrivacyPolicyContent } from "./schemas";
import { cleanAndAggregateMethods } from "../Util";
import copyToClipboard from "copy-to-clipboard";
import notification from "utils/notification";
import { ModuleType } from "@komi-app/shared-types"

const DataCaptureCreationPreview = ({
  type,
  imagePath,
  title,
  subtitle,
  secretLink,
  secretCode,
  countdownExpiry,
  contactMethods,
  additionalContactMethods,
  isImageVisible,
  talentName,
}: DCAFormStepsProps) => {
  const [methods, setMethods] = useState<DataCaptureMethod[]>(contactMethods);
  useEffect(() => {
    const aggregatedMethod = cleanAndAggregateMethods(
      contactMethods,
      additionalContactMethods,
      talentName
    );
    setMethods(aggregatedMethod);
  }, [contactMethods]);

  const [previousSubmission, setPreviousSubmission] = useState([{}]);
  const [locked, setLocked] = useState(true);
  const showLock = type !== ModuleType.DATA_CAPTURE_SIGNUP;
  const user = useTypedSelector(selectUserData);

  const theme = {
    overlayColor: user?.talentProfile?.themeColor?.overlayColor as string,
    overlayOpacity: user?.talentProfile?.themeColor?.overlayOpacity as number,
    typographyColor: user?.talentProfile?.themeColor?.typographyColor as string,
    backgroundColor: user?.talentProfile?.themeColor?.backgroundColor as string,
    type: ThemeType[user?.talentProfile?.themeType as TalentProfileThemeTypes],
  } as Theme;

  /**
   * Handle each form submission here.
   */
  const onSubmitButtonClick = () => async (responses: any) => {
    const fieldTypeName = Object.keys(responses).includes("email")
      ? "email"
      : "SMS";

    const submissionField =
      fieldTypeName === "email" ? "marketing_email" : "marketing_sms";
    setPreviousSubmission([
      { ...previousSubmission[0], [submissionField]: "test" },
    ]);
    //If the card is in preview, we do not submit data,
    // We just show the toasts.
    notification.success({
      message: `You successfully signed up for ${fieldTypeName} updates.`,
    });
  };

  /**
   *
   */
  methods.forEach((method: DataCaptureMethod) => {
    const { talentName, talentPrivacyPolicyText, talentPrivacyPolicyURL } =
      getPrivacyPolicyContent(user?.talentProfile);
    method.talentName = talentName;
    method.talentPrivacyPolicyText = talentPrivacyPolicyText;
    method.talentPrivacyPolicyURL = talentPrivacyPolicyURL;
    method.onSubmit = onSubmitButtonClick();
  });

  return (
    <Card className="preview-card">
      <div className="preview">
        {showLock && (
          <div className="header" data-testid="header">
            <div
              className={classNames(
                { selected: locked },
                { unselected: !locked },
                "button"
              )}
              onClick={() => setLocked(true)}
            >
              <span className="label">LOCKED</span>
            </div>
            <div
              className={classNames(
                { selected: !locked },
                { unselected: locked },
                "button"
              )}
              onClick={() => setLocked(false)}
            >
              <span className="label">UNLOCKED</span>
            </div>
          </div>
        )}
        <div
          className={classNames(
            "display",
            { "display-with-lock": showLock },
            { "display-without-lock": !showLock }
          )}
          style={{
            backgroundColor: theme.backgroundColor,
          }}
        >
          <InlineMessage message="This is an interactive preview" closeable />
          <DataCaptureCard
            key={countdownExpiry}
            moduleType={type as unknown as DataCaptureType}
            imagePath={imagePath}
            title={title}
            subtitle={subtitle}
            countdownExpiry={countdownExpiry}
            methods={methods}
            theme={theme}
            secretLink={locked ? undefined : secretLink}
            secretCode={locked ? undefined : secretCode}
            isPaused={false}
            isImageVisible={isImageVisible}
            onCodeClick={(code) => {
              copyToClipboard(code);
              notification.success({
                message: `Secret Code copied successfully.`,
              });
            }}
            onLinkClick={(link) => {
              window.open(link, "_system");
            }}
            previousSubmission={previousSubmission}
          />
        </div>
      </div>
    </Card>
  );
};

export default DataCaptureCreationPreview;
