import {
  DropdownCalendar,
  DropdownTimeSelector,
  Modal,
  TalentButton,
  TimezoneSelect,
} from "@komi-app/components";
import { Typography } from "antd";
import { Timezone } from "components/TimezoneSelect/utilities/timezone";
import React, { useEffect, useState } from "react";
import { Schedule } from "types/campaigns";
import { mapToScheduleForm } from "./mappers";
import { Timestamp } from "components/TimezoneSelect/utilities/timestamp";

import "./ScheduleCampaignModal.scss";
import "./Modal.scss";

export interface ScheduleCampaignModalProps {
  existingSchedule: Schedule;
  modalOpen: boolean;
  onScheduleSubmitted: (schedule: Schedule) => Promise<void>;
  setModalOpen: (visibility: boolean) => void;
}

const ScheduleCampaignModal: React.FC<ScheduleCampaignModalProps> = ({
  existingSchedule,
  modalOpen,
  onScheduleSubmitted,
  setModalOpen,
}) => {
  const initialSchedule = mapToScheduleForm(existingSchedule);

  const [timezone, setTimezone] = useState<string | undefined>(
    initialSchedule.timezone || undefined
  );
  const [date, setDate] = useState<number | null>(
    initialSchedule.startPlainDate
  );
  const [touchedFields, setTouchedFields] = useState<Record<string, boolean>>({
    date: false,
    time: false,
    timezone: false,
  });
  const [time, setTime] = useState<number | null>(
    initialSchedule.startPlainTime
  );

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

  /**
   * Validate all fields and set errors if any
   * Checks:
   *      All fields are filled,
   *      start time is in the future
   * @returns boolean
   */
  const validateFields = (): boolean => {
    //Check if all fields are filled
    if (!date || time === null || !timezone) {
      setErrors({
        date: !date && !touchedFields.date ? "Start date is required" : "",
        time: !time && !touchedFields.time ? "Start time is required" : "",
        timezone:
          !timezone && !touchedFields.timezone ? "Timezone is required" : "",
      });
      return false;
    }

    //Once all fields are filled,Check if start time is in the future
    const now = Date.now();

    const startTimestamp = Timestamp.plainPartsToTimestamp({
      plaindate: date,
      plaintime: time,
      timezoneName: timezone,
    }).timestamp;

    if (startTimestamp < now) {
      setErrors({
        time: "Start time must be in the future",
      });
      return false;
    } else {
      setErrors({
        time: "",
      });
      return true;
    }
  };

  //On event 1. set touched fields 2. clear errors 3. set value
  const onTimezoneChange = (timezone: Timezone) => {
    setTouchedFields({ ...touchedFields, timezone: true });
    setErrors({ ...errors, timezone: "" });
    setTimezone(timezone.primaryName);
  };

  //On event 1. set touched fields 2. clear errors 3. set value
  const onTimeSelect = (time: number | null) => {
    setTouchedFields({ ...touchedFields, time: true });
    setErrors({ ...errors, time: "" });

    setTime(time);
  };

  //On event 1. set touched fields 2. clear errors 3. set value
  const onDateSelect = (date: number | null) => {
    setTouchedFields({ ...touchedFields, date: true });
    setErrors({ ...errors, date: "" });
    setDate(date);
  };

  const submitSchedule = async () => {
    //Check form errors. if any, don't submit.
    const isFormValid = validateFields();
    if (!isFormValid) {
      return;
    }

    //Check if all fields are filled
    if (!date || time === null || !timezone) {
      return;
    }

    const startTimestamp = Timestamp.plainPartsToTimestamp({
      plaindate: date,
      plaintime: time,
      timezoneName: timezone,
    }).timestamp;

    const schedule = {
      ...existingSchedule,
      startTimestamp,
      timezone: timezone,
    };

    // TODO: Use normal state and pass
    await onScheduleSubmitted(schedule);
    setModalOpen(false);
  };

  const buttonText = existingSchedule.startTimestamp
    ? "EDIT SCHEDULE"
    : "SCHEDULE";

  return (
    <Modal
      className="schedule-campaign-modal"
      visible={modalOpen}
      onCancel={() => setModalOpen(false)}
      title=""
      closeIcon={false}
      width={700}
    >
      <div>
        <div>
          <div className="header">
            <Typography.Title level={4}>Schedule Send</Typography.Title>
          </div>
          <div className="section">
            <Typography.Title level={5}>Start Time</Typography.Title>
            <div className="date-pickers">
              <DropdownCalendar
                label="Date"
                placeholder="Select a date"
                value={date}
                onValueChange={onDateSelect}
                error={errors.date}
                minDate={Date.now()}
              />
              <DropdownTimeSelector
                label="Time"
                placeholder="Select a time"
                error={errors.time}
                onValueChange={onTimeSelect}
                value={time}
              />
            </div>
            <TimezoneSelect
              showLabel
              handleSelect={onTimezoneChange}
              error={errors.timezone}
              initialValue={timezone}
            />
          </div>
          <div className="footer">
            <TalentButton
              variant="secondary"
              onClick={() => setModalOpen(false)}
            >
              CANCEL
            </TalentButton>

            <TalentButton variant="primary" onClick={submitSchedule}>
              {buttonText}
            </TalentButton>
          </div>
        </div>
      </div>
    </Modal>
  );
};

export default ScheduleCampaignModal;
