import { DataCaptureType } from "@komi-app/components";
import { Timestamp } from "components/TimezoneSelect/utilities/timestamp";
import {
  BaseItem,
  DataCaptureActivationItemNew,
} from "models/talent/talent-profile-module.model";
import { DCAFormStepsProps } from "./CreationModalForms/schemas";
import { cleanAndAggregateMethods, spreadMethods } from "./Util";

export function dcaItemToFormValues(
  item: DataCaptureActivationItemNew
): DCAFormStepsProps {
  const countdownExpiryParts = {
    showCountdown: false,
    countdownExpiryPlainDate: 0,
    countdownExpiryPlainTime: 0,
    countdownExpiryTimezone: "Europe/London",
  };

  if (item.countdownExpiry) {
    countdownExpiryParts.showCountdown = true;
    const { plaindate, plaintime, timezoneName } =
      Timestamp.timestampToPlainParts({
        timestamp: item.countdownExpiry,
        timezoneName: item.countdownTimeZone as string,
      });
    countdownExpiryParts.countdownExpiryPlainDate = plaindate;
    countdownExpiryParts.countdownExpiryPlainTime = plaintime;
    countdownExpiryParts.countdownExpiryTimezone = timezoneName;
  }
  const { contactMethods, additionalContactMethods } = spreadMethods(
    item.methods
  );
  return {
    type: item.type,
    title: item.title,
    subtitle: item.subtitle as string,
    secretLink: item.secretLink as string,
    secretCode: item.secretCode as string,
    isImageVisible: item.isImageVisible,
    imagePath: item.imagePath as string,
    countdownExpiryPlainDate: countdownExpiryParts.countdownExpiryPlainDate,
    countdownExpiryPlainTime: countdownExpiryParts.countdownExpiryPlainTime,
    countdownExpiryTimezone: countdownExpiryParts.countdownExpiryTimezone,
    contactMethods: contactMethods,
    additionalContactMethods: additionalContactMethods,
    countdownExpiry: 0,
    showCountdown: countdownExpiryParts.showCountdown,
  };
}
export function dcaFormValuesToItem(
  values: DCAFormStepsProps,
  moduleValues: BaseItem & { name: string; order: number }
): DataCaptureActivationItemNew {
  let countdownExpiry = 0;
  let timeZone = "";
  if (values.showCountdown) {
    const { timestamp, timezoneName } = Timestamp.plainPartsToTimestamp({
      plaindate: values.countdownExpiryPlainDate as number,
      plaintime: values.countdownExpiryPlainTime as number,
      timezoneName: values.countdownExpiryTimezone,
    });
    countdownExpiry = timestamp;
    timeZone = timezoneName;
  }

  const methods = cleanAndAggregateMethods(
    values.contactMethods,
    values.additionalContactMethods,
    values.talentName
  );

  return {
    ...moduleValues,
    type: values.type,
    secretCode: values.secretCode,
    secretLink: values.secretLink,
    imagePath: values.imagePath,
    isImageVisible: values.isImageVisible,
    title: values.title,
    subtitle: values.subtitle,
    countdownExpiry: countdownExpiry,
    methods,
    moduleType: values.type as unknown as DataCaptureType,
    countdownTimeZone: timeZone,
  };
}
