import Button from "antd/lib/button";
import Checkbox from "antd/lib/checkbox";
import DatePicker from "antd/lib/date-picker";
import Form from "antd/lib/form";
import { useForm } from "antd/lib/form/Form";
import FormItem from "antd/lib/form/FormItem";
import Input from "antd/lib/input";
import Radio from "antd/lib/radio";
import { Option, Select } from "components/Select";
import { Text } from "components/Typography";
import { countries } from "constants/nationality";
import { isValidPhoneNumber } from "libphonenumber-js";
import moment from "moment";
import { ReactComponent as DatePickerIcon } from "icons/datepicker.svg";
import { ReactComponent as LeftIcon } from "icons/arrow/sLeft.svg";
import { ReactComponent as RightIcon } from "icons/arrow/sRight.svg";
import React, { useEffect, useState } from "react";
import PhoneInput from "react-phone-input-2";
import { FieldItem, FieldType, OptionItem } from "redux/User/types";
import classNames from "classnames";
import "react-phone-input-2/lib/style.css";
import "./DataCaptureModalPreview.scss";
import { LegalsType } from "@komi-app/shared-types"

moment.updateLocale("en", {
  weekdaysMin: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
});

interface Props {
  title: string;
  subtitle: string;
  fields: FieldItem[];
  isDarken?: boolean;
  isMobile?: boolean;
}

const DataCaptureModalPreview: React.FC<Props> = ({
  fields,
  isDarken = false,
  title,
  subtitle,
  isMobile,
}) => {
  const [form] = useForm();

  const RequireMark = ({ required, children }: any) => {
    return required ? (
      <>
        {children}
        <span className="text--red">*</span>
      </>
    ) : (
      children
    );
  };

  const RenderPhoneInput = ({ name, label, required }: FieldItem) => {
    const [phone, setPhone] = useState("");

    const checkPhoneNumber = () => {
      if (!required) return Promise.resolve();
      if (!phone) {
        return Promise.reject("Please enter phone number");
      } else {
        if (!isValidPhoneNumber(`+${phone}`)) {
          return Promise.reject("Please enter a valid phone number");
        }
      }
      return Promise.resolve();
    };

    return (
      <Form.Item
        required={required}
        label={<RequireMark required={required}>{label}</RequireMark>}
        name={name}
        rules={[{ validator: checkPhoneNumber }]}
      >
        <PhoneInput
          country="us"
          buttonClass="phone-button-select"
          inputClass="phone-input"
          placeholder="Enter phone number"
          countryCodeEditable={false}
          onChange={(value) => setPhone(value)}
        />
      </Form.Item>
    );
  };

  const RenderCountryInput = ({ name, label, required }: FieldItem) => {
    return (
      <Form.Item
        className="m__t--4"
        label={<RequireMark required={required}>{label}</RequireMark>}
        name={name}
        rules={[
          {
            required: required,
            message: "Please select a country",
          },
        ]}
      >
        <Select
          placeholder="Select a country"
          dropdownClassName="country-dropdown"
          placement="bottomRight"
          getPopupContainer={(trigger) => trigger.parentNode}
        >
          {Object.keys(countries).map((key, index) => (
            <Option
              className="p__y--16 p__x--20"
              value={key?.toLowerCase()}
              key={index}
            >
              <img
                width={20}
                height={20}
                style={{ borderRadius: "100%", objectFit: "cover" }}
                className="m__r--8"
                alt={countries[key?.toUpperCase()]}
                src={`http://purecatamphetamine.github.io/country-flag-icons/3x2/${key.toUpperCase()}.svg`}
              />
              <Text preset="semibold14">{countries[key?.toUpperCase()]}</Text>
            </Option>
          ))}
        </Select>
      </Form.Item>
    );
  };

  const RenderDatePicker = ({ name, label, required }: FieldItem) => {
    const [visibleDatePickerModal, setVisibleDatePicker] = useState(false);
    return (
      <Form.Item
        className="m__t--4"
        name={name}
        label={<RequireMark required={required}>{label}</RequireMark>}
        rules={[
          {
            required: required,
            message: "Please select a date",
          },
        ]}
      >
        <DatePicker
          open={visibleDatePickerModal}
          onOpenChange={(val) => setVisibleDatePicker(val)}
          dropdownClassName="data-capture-form-datepicker"
          className="full-width p__y--0"
          placeholder="Select a date"
          format="MM/DD/YYYY"
          allowClear={false}
          suffixIcon={<DatePickerIcon />}
          showToday={false}
          nextIcon={<RightIcon />}
          prevIcon={<LeftIcon />}
          superNextIcon={<RightIcon />}
          superPrevIcon={<LeftIcon />}
        />
      </Form.Item>
    );
  };

  const RenderCheckboxGroup = ({
    name,
    label,
    required,
    options,
    checked = false,
    legalType,
  }: FieldItem) => {
    const optionsData: any = options?.map((option) => ({
      label: option.label,
      value: option?.label || Date.now().toString(),
    }));

    useEffect(() => {
      if (options && name) {
        const res: any = [];
        options?.forEach((option: any) => {
          if (option.checked) res.push(option.value);
        });
        form.setFieldsValue({ [name]: res });
      }
    }, [name, options]);

    return (
      <Form.Item
        className="checkbox-form"
        name={name}
        label={<RequireMark required={required}>{label}</RequireMark>}
        rules={[
          {
            required: required,
            message: "Please make a selection",
          },
        ]}
      >
        {legalType ? (
          options?.map((option: OptionItem, i) => (
            <Checkbox
              key={i}
              value={option.label}
              checked={checked}
              defaultChecked={checked}
            >
              {option.label}
            </Checkbox>
          ))
        ) : (
          <Checkbox.Group options={optionsData} />
        )}
      </Form.Item>
    );
  };

  const RenderRadioGroup = ({ name, label, required, options }: FieldItem) => {
    return (
      <Form.Item
        className="radio-form m__b--24"
        label={<RequireMark required={required}>{label}</RequireMark>}
        name={name}
        rules={[
          {
            required: required,
            message: "Please make a selection",
          },
        ]}
      >
        <Radio.Group size="large">
          {options?.map((option: OptionItem, i) => (
            <Radio key={i} value={option.label}>
              {option.label}
            </Radio>
          ))}
        </Radio.Group>
      </Form.Item>
    );
  };

  const RenderTextArea = ({ name, label, required }: FieldItem) => {
    return (
      <Form.Item
        name={name}
        label={<RequireMark required={required}>{label}</RequireMark>}
        rules={[
          {
            required: required,
            message: "Please fill this out",
          },
        ]}
      >
        <Input.TextArea
          autoSize={{ minRows: 5, maxRows: 5 }}
          placeholder="Please fill this out"
        />
      </Form.Item>
    );
  };

  const RenderInput = ({ name, label, required }: FieldItem) => {
    return (
      <FormItem
        name={name}
        label={<RequireMark required={required}>{label}</RequireMark>}
        rules={[
          {
            required: required,
            message: "Please fill this out",
          },
        ]}
      >
        <Input placeholder="Please fill this out" />
      </FormItem>
    );
  };

  const RenderEmailInput = ({ name, label, required }: FieldItem) => {
    return (
      <FormItem
        name={name}
        label={<RequireMark required={required}>{label}</RequireMark>}
        rules={[
          {
            type: "email",
            message: "Please enter a valid email",
          },
          {
            required: required,
            message: "Please enter your email address",
          },
        ]}
      >
        <Input placeholder="Enter your email address" />
      </FormItem>
    );
  };

  const RenderPlainText = ({ title, content }: any) => {
    return (
      <div className="m__b--16">
        <Text preset="semibold16">{title}</Text>
        {content && (
          <Text className="d--block m__t--4 opacity--80" preset="regular14">
            {content}
          </Text>
        )}
      </div>
    );
  };

  return (
    <div className="data-capture--preview">
      <div
        style={{
          background: isDarken
            ? "linear-gradient(0deg, rgba(18, 18, 18, 0.1), rgba(18, 18, 18, 0.1)), var(--ant-primary-color)"
            : "linear-gradient(0deg, rgba(255, 255, 255, 0.1), rgba(255, 255, 255, 0.1)), var(--ant-primary-color)",
          height: title ? "auto" : "24px",
          padding: title ? "24px" : "0",
        }}
        className="data-capture--preview--header"
      >
        <Text style={{ color: "var(--ant-info-color)" }} preset="semibold20">
          {title}
        </Text>
        {subtitle && (
          <Text
            style={{ color: "var(--ant-info-color)" }}
            className="d--block m__t--4 opacity-05"
          >
            {subtitle}
          </Text>
        )}
      </div>
      <div
        className={
          isMobile
            ? classNames(
                "p__x--16 p__y--24 bg--white data-capture--preview--body",
                {
                  "has-title": !!title && !subtitle,
                  "has-subtitle": !!subtitle && !!title,
                }
              )
            : "p--24"
        }
      >
        <Form requiredMark={false} form={form} layout="vertical">
          {fields?.map((field) => {
            switch (field.type) {
              case FieldType.INPUT:
                return (
                  <RenderInput
                    key={field.name}
                    name={field.name}
                    label={field.label}
                    required={field.required}
                  />
                );
              case FieldType.TEXTAREA:
                return (
                  <RenderTextArea
                    key={field.name}
                    name={field.name}
                    label={field.label}
                    required={field.required}
                  />
                );
              case FieldType.EMAIL_ADDRESS:
                return (
                  <RenderEmailInput
                    key={field.name}
                    name={field.name}
                    label={field.label}
                    required={field.required}
                  />
                );
              case FieldType.PHONE_NUMBER:
                return (
                  <RenderPhoneInput
                    key={field.name}
                    name={field.name}
                    label={field.label}
                    required={field.required}
                  />
                );
              case FieldType.SELECT_COUNTRY:
                return (
                  <RenderCountryInput
                    key={field.name}
                    name={field.name}
                    label={field.label}
                    required={field.required}
                  />
                );
              case FieldType.SELECT_DATE:
                return (
                  <RenderDatePicker
                    key={field.name}
                    name={field.name}
                    label={field.label}
                    required={field.required}
                  />
                );
              case FieldType.SELECT_MULTIPLE:
                return (
                  <RenderCheckboxGroup
                    key={field?.name || Date.now().toString()}
                    name={field.name}
                    label={field.label}
                    required={field.required}
                    options={field.options}
                  />
                );
              case FieldType.SELECT_SINGLE:
                return (
                  <RenderRadioGroup
                    key={field.name}
                    name={field.name}
                    label={field.label}
                    required={field.required}
                    options={field.options}
                  />
                );
              case FieldType.LEGALS:
                return field?.legalType === LegalsType.PLAIN_TEXT ? (
                  <RenderPlainText
                    key={field?.name || Date.now().toString()}
                    title={field?.label}
                    content={field?.text}
                  />
                ) : (
                  <RenderCheckboxGroup
                    key={field?.name || Date.now().toString()}
                    name={field.name}
                    label={field.label}
                    required={field.required}
                    options={field.options}
                    checked={field?.legalType === LegalsType.DEFAULT_CHECK}
                    legalType={field?.legalType}
                  />
                );
            }
          })}
          <Form.Item className="m__t--24">
            <Button type="primary" block className="data-capture--preview--btn">
              Submit
            </Button>
          </Form.Item>

          <Button className="ant-btn-back data-capture--preview--btn" block>
            CANCEL
          </Button>
        </Form>
      </div>
    </div>
  );
};

export default DataCaptureModalPreview;
