import { useField } from "formik";
import React, { useCallback } from "react";

import theme from "mazlo-theme";

import { Text, View } from "../../index";
import { Icon } from "../Icon";
import styles from "./styles";

type Props = {
  children: React.ReactNode;
  defaultValue?: any;
  disabled?: boolean;
  hint?: string;
  label?: string;
  name: string;
  required?: boolean;
  size?: "lg" | "sm";
  dark?: boolean;
};

const FormItem = ({
  children,
  defaultValue,
  disabled,
  hint,
  label,
  name,
  required,
  size,
  dark,
}: Props) => {
  const [field, meta, helpers] = useField({ name });
  const child: any = React.Children.only(children);
  const onChange = useCallback(
    (value: any) => {
      if (disabled) return;
      helpers.setValue(value);
      if (child.props.onChange) {
        child.props.onChange(value);
      }
    },
    [helpers, children, disabled]
  );
  const isError = Array.isArray(meta.error)
    ? meta.error.some((error) => !!error)
    : !!meta.error;

  return (
    <View
      style={[
        styles.container,
        size === "lg" && styles.containerLarge,
        size === "sm" && styles.containerSmall,
      ]}
    >
      {!!label && (
        <View row style={styles.labelContainer}>
          <Text
            style={[
              styles.label,
              size === "lg" && styles.labelLarge,
              dark && styles.labelDark,
            ]}
            variant="label"
          >
            {label}
          </Text>
          {required && (
            <Text
              style={[
                styles.requiredText,
                !!meta.value && !isError && styles.requiredTextFilled,
              ]}
            >
              <Icon
                name="check"
                color={
                  meta.value && !isError ? theme.colors.green : theme.colors.red
                }
              />{" "}
              Required *
            </Text>
          )}
        </View>
      )}
      {React.cloneElement(child, {
        ...field,
        defaultValue,
        disabled,
        onChange,
        dark,
      })}
      {!!hint && (
        <Text style={styles.hintText} variant="muted">
          {hint}
        </Text>
      )}
      {meta.touched && meta.error && typeof meta.error === "string" ? (
        <Text style={styles.error} variant="error">
          {meta.error}
        </Text>
      ) : null}
    </View>
  );
};

export default FormItem;
