import React from 'react';
import { Input, Button, FormItem, FormContainer, Alert, InputGroup, Select } from '@/components/ui';
import { PasswordInput, ActionLink } from '@/components/shared';
import useTimeOutMessage from '@/utils/hooks/useTimeOutMessage';
import { Field, Form, Formik } from 'formik';
import * as Yup from 'yup';
import useAuth from '@/utils/hooks/useAuth';
import { getCountryList } from '@/constants/countries.constant';

import { useTranslation } from 'react-i18next';
import LanguageSelector from '@/components/template/LanguageSelector';
import NumberFormat from 'react-number-format';
import { components } from 'react-select';
import { HiOutlineMail, HiOutlinePhone } from 'react-icons/hi';

const { SingleValue } = components;

const NumberInput = (props) => {
  return <Input {...props} value={props.field.value} />;
};

const NumberFormatInput = ({ onValueChange, ...rest }) => {
  return (
    <NumberFormat
      customInput={Input}
      type="text"
      onValueChange={onValueChange}
      autoComplete="off"
      {...rest}
      allowNegative={false}
      decimalScale={0}
    />
  );
};

const PhoneSelectOption = ({ innerProps, data, isSelected }) => {
  return (
    <div
      className={`cursor-pointer flex items-center justify-between p-2 ${
        isSelected ? 'bg-gray-100 dark:bg-gray-500' : 'hover:bg-gray-50 dark:hover:bg-gray-600'
      }`}
      {...innerProps}
    >
      <div className="flex items-center gap-2">
        <span>
          ({data.value}) {data.dialCode}
        </span>
      </div>
    </div>
  );
};

const PhoneControl = ({ children, ...props }) => {
  const selected = props.getValue()[0];
  return <SingleValue {...props}>{selected && <span>{selected.dialCode}</span>}</SingleValue>;
};

const SignInForm = (props) => {
  const { t, i18n } = useTranslation();
  const countryList = getCountryList(t);
  const validationSchema = Yup.object().shape({
    // userName: Yup.string().required(t('Please enter your user name')),
    password: Yup.string()
      .matches(
        // eslint-disable-next-line no-useless-escape
        /^[A-Za-z\d!@#$%^&*()_\-+=\[\]{}|;:,.<>?]+$/,
        t('INVALID_PASSWORD'),
      )
      .required(t('Please enter your password')),
    rememberMe: Yup.bool(),
    mobileNumber: Yup.string().required(t('PLEASE_ENTER_YOUR_MOBILE_NUMBER')),
    dialCode: Yup.string().required(t('PLEASE_SELECT_DIAL_CODE')),
  });

  const { disableSubmit = false, className, forgotPasswordUrl = '/forgot-password', signUpUrl = '/sign-up' } = props;

  const [message, setMessage] = useTimeOutMessage();

  const { signIn } = useAuth();

  const onSignIn = async (values, setSubmitting) => {
    values.userName = values.dialCode + values.mobileNumber;
    const { userName, password } = values;
    setSubmitting(true);

    const result = await signIn({ userName, password });

    if (result.status === 'failed') {
      setMessage(result.message[0].errorMessages);
    }

    setSubmitting(false);
  };

  return (
    <div className={className}>
      {message && (
        <Alert className="mb-4" type="danger" showIcon>
          {t(message)}
        </Alert>
      )}
      <Formik
        // Remove this initial value
        initialValues={{
          //userName: '',
          password: '',
          rememberMe: true,
          mobileNumber: '',
          dialCode: '+968',
        }}
        validationSchema={validationSchema}
        onSubmit={(values, { setSubmitting }) => {
          if (!disableSubmit) {
            onSignIn(values, setSubmitting);
          } else {
            setSubmitting(false);
          }
        }}
      >
        {({ values, touched, errors, isSubmitting }) => (
          <Form>
            <FormContainer>
              {/* <FormItem
                label={t('User Name')}
                invalid={errors.userName && touched.userName}
                errorMessage={errors.userName}
              >
                <Field type="text" autoComplete="off" name="userName" placeholder={t('User Name')} component={Input} />
              </FormItem> */}

              <FormItem
                label={t('MOBILE_NUMBER')}
                invalid={(errors.dialCode && touched.dialCode) || (errors.mobileNumber && touched.mobileNumber)}
                errorMessage={errors.dialCode && touched.dialCode ? errors.dialCode : errors.mobileNumber}
              >
                <InputGroup className={i18n.dir() === 'rtl' && 'ltr-direction'}>
                  <Field name="dialCode">
                    {({ field, form }) => (
                      <Select
                        className="min-w-[120px] max-w-[120px]"
                        placeholder={t('DIAL_CODE')}
                        aria-label={t('DIAL_CODE')}
                        components={{
                          Option: PhoneSelectOption,
                          SingleValue: PhoneControl,
                        }}
                        field={field}
                        form={form}
                        options={countryList}
                        value={countryList.filter((country) => country.dialCode === values.dialCode)}
                        onChange={(country) => form.setFieldValue(field.name, country.dialCode)}
                      />
                    )}
                  </Field>
                  <Field name="mobileNumber">
                    {({ field, form }) => {
                      return (
                        <NumberFormatInput
                          form={form}
                          field={field}
                          maxLength={12}
                          customInput={NumberInput}
                          placeholder={t('MOBILE_NUMBER')}
                          onValueChange={(e) => {
                            form.setFieldValue(field.name, e.value);
                          }}
                        />
                      );
                    }}
                  </Field>
                </InputGroup>
              </FormItem>

              <FormItem
                label={t('Password')}
                invalid={errors.password && touched.password}
                errorMessage={errors.password}
              >
                <Field autoComplete="off" name="password" placeholder={t('Password')} component={PasswordInput} />
              </FormItem>
              <div className="flex justify-between mb-6">
                <ActionLink className="mt-2" to={forgotPasswordUrl}>
                  {t('Forgot Password?')}
                </ActionLink>
                <div className="flex flex-row   h-full text-center  ">
                  <div className="flex-auto"></div>
                  <div className="flex-auto pt-2 h-full "></div>
                  <div className="flex-2  border-white">
                    <LanguageSelector />
                  </div>
                  <div className="flex-auto"></div>
                </div>
                {/*<Field className="mb-0" name="rememberMe" component={Checkbox} children={t('Remember Me')} />*/}
              </div>
              <Button block loading={isSubmitting} variant="solid" type="submit">
                {isSubmitting ? t('SIGN_IN') + '...' : t('SIGN_IN')}
              </Button>
              <div className="mt-4 text-center">
                <span>{t("Don't have an account yet?")} </span>
                <ActionLink to={signUpUrl}>{t('Sign up')}</ActionLink>
              </div>
            </FormContainer>
            {/* add full line */}
            <div className="border-t border-gray-300 dark:border-gray-700 mt-2" />
            <div className="mt-4 flex flex-col justify-center items-center">
              <span>{t('FOR_HELP_CONTACT_US')}</span>
              <div className="flex flex-col justify-center items-center mt-2">
                <div className="flex items-center">
                  <HiOutlinePhone className="mx-2 text-sky-800 dark:text-white" />
                  <div className="flex items-center gap-1">
                    <a
                      className="text-sky-800 dark:text-white hover:text-sky-500 dark:hover:text-gray-300"
                      href="tel:71001271"
                    >
                      71001271
                    </a>
                    <span> - </span>
                    <a
                      className="text-sky-800 dark:text-white hover:text-sky-500 dark:hover:text-gray-300"
                      href="tel:71001291"
                    >
                      71001291
                    </a>
                  </div>
                </div>
                {/* <span>, </span> */}
              </div>
              <a
                className="text-sky-800 dark:text-white hover:text-sky-500 dark:hover:text-gray-300 text-center"
                href="mailto:onewb@nafith.com"
              >
                <span className="flex items-center">
                  <HiOutlineMail className="mx-2" />
                  onewb@nafith.com
                </span>
              </a>
            </div>
          </Form>
        )}
      </Formik>
    </div>
  );
};

export default SignInForm;
