import axios from 'axios';
import React, { useState } from 'react';
import { useForm } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
import { useRouter } from 'next/router';
import { CustomResponse } from '../../../model/common';
import { User } from '../../../model/user';
import {
  MyProfileProps,
  PasswordFormData,
  ProfileFormData,
  ProfileParams,
} from '../../../model/components/profile';
import Field from '../../common/Field';
import RoundedButton from '../../common/RoundedButton';
import ProfileIcon from '../../icons/Profile';
import logout from '../../../utils/logout';
// import CloseSmall from '../../icons/CloseSmall';

const MyProfile: React.FC<MyProfileProps> = ({
  departments,
  user,
  onChangeUser,
  // onChangeTeam,
}) => {
  const {
    register: profileRegister,
    formState: { errors: profileErrors },
    handleSubmit: handleProfileSubmit,
    setError: setProfileError,
    clearErrors: clearProfileErrors,
  } = useForm<ProfileFormData>();

  const {
    register: passwordRegister,
    formState: { errors: passwordErrors },
    handleSubmit: handlePasswordSubmit,
    setError: setPasswordError,
    getValues: getPasswordValues,
    setValue: setPasswordValue,
    clearErrors: clearPasswordErrors,
  } = useForm<PasswordFormData>();

  const { t } = useTranslation();
  const router = useRouter();

  const [editing, setEditing] = useState<boolean>(false);
  // const [abandonTeam, setAbandonTeam] = useState<boolean>(false);

  // const onConfirmAbandonTeam = async (): Promise<void> => {
  //   await axios
  //     .post<CustomResponse<string>>('/api/deleteUserFromTeam', {
  //       userId: user._id,
  //     })
  //     .then(({ data: { ok } }) => {
  //       if (ok) {
  //         onChangeTeam(null);
  //       }
  //       setAbandonTeam(false);
  //     });
  // };

  const onProfileSubmit = async (data: ProfileFormData): Promise<void> => {
    const { email, username, department, licenseNumber } = data;
    const response = await axios.post<CustomResponse<User>>(
      '/api/updateProfile',
      {
        _id: user._id,
        email,
        username,
        licenseNumber,
        department,
      } as ProfileParams,
    );

    if (response.data?.ok) {
      onChangeUser(response.data.data);
      clearPasswordErrors();
      setEditing(false);
    } else if (response.data?.error) {
      setProfileError('username', { message: response.data.error });
    }
  };

  const onPasswordSubmit = async (data: PasswordFormData): Promise<void> => {
    const { password, newPassword } = data;
    const response = await axios.post<CustomResponse<User>>(
      '/api/updatePassword',
      {
        _id: user._id,
        email: user.email,
        password,
        newPassword,
      } as ProfileParams,
    );

    if (response.data?.ok) {
      clearProfileErrors();
      setPasswordValue('password', '');
      setPasswordValue('newPassword', '');
      setPasswordValue('repeatNewPassword', '');
      setEditing(false);
    } else if (response.data?.error) {
      setPasswordError('password', { message: response.data.error });
    }
  };

  const logOutAndRedirect = (): void => {
    logout();
    router.push('/login');
  };

  return (
    <div className="myProfile">
      <div className="titleWrapper">
        <div className="title">
          <ProfileIcon size="medium" />
          <h2>{t('YOUR_PROFILE')}</h2>
        </div>
        <button
          type="button"
          className="textClick"
          onClick={(): void => {
            setEditing(!editing);
            clearProfileErrors();
            clearPasswordErrors();
          }}
        >
          {editing ? 'Cancelar' : 'Editar'}
        </button>
      </div>
      <div className="infoWrapper">
        <form onSubmit={handleProfileSubmit(onProfileSubmit)} noValidate>
          <fieldset>
            <Field
              label="Nombre"
              htmlFor="username"
              errorMessage={t(profileErrors.username?.message)}
              error={!!profileErrors.username}
              vertical
            >
              <input
                type="text"
                name="username"
                defaultValue={user.username}
                readOnly={!editing}
                {...profileRegister('username', { required: 'REQUIRED_NAME' })}
              />
            </Field>
            <Field
              label="Nº Colegiado"
              htmlFor="collegeNumber"
              errorMessage={t(profileErrors.licenseNumber?.message)}
              error={!!profileErrors.licenseNumber}
              vertical
            >
              <input
                type="text"
                name="collegeNumber"
                defaultValue={user.licenseNumber}
                readOnly={!editing}
                {...profileRegister('licenseNumber', {
                  required: 'REQUIRED_LICENSE',
                })}
              />
            </Field>
            <Field
              label="Email"
              htmlFor="email"
              errorMessage={t(profileErrors.email?.message)}
              error={!!profileErrors.email}
              vertical
            >
              <input
                type="email"
                name="email"
                defaultValue={user.email}
                readOnly={!editing}
                {...profileRegister('email', {
                  required: 'REQUIRED_EMAIL',
                  pattern: { message: 'INVALID_EMAIL', value: /^\S+@\S+.\S$/i },
                })}
              />
            </Field>
            <Field
              label="Especialidad"
              htmlFor="specialty"
              errorMessage={t(profileErrors.department?.message)}
              error={!!profileErrors.department}
              vertical
            >
              <select
                name="specialty"
                defaultValue={user.department.id}
                disabled={!editing}
                {...profileRegister('department', {
                  validate: (value) => {
                    if (value === 'none') {
                      return 'REQUIRED_DEPARTMENT';
                    }
                    return undefined;
                  },
                })}
              >
                {departments.map((d) => (
                  <option key={d.id} value={d.id}>
                    {d.name}
                  </option>
                ))}
              </select>
            </Field>
            {editing && (
              <RoundedButton
                title={t('SAVE_CHANGES')}
                type="submit"
                size="small"
              />
            )}
          </fieldset>
        </form>
        {editing ? (
          <form onSubmit={handlePasswordSubmit(onPasswordSubmit)} noValidate>
            <fieldset>
              <span className="divider" />
              <Field
                label="Contraseña Actual"
                htmlFor="password"
                errorMessage={t(passwordErrors.password?.message)}
                error={!!passwordErrors.password}
                className="small"
                vertical
              >
                <input
                  type="password"
                  name="password"
                  {...passwordRegister('password', {
                    required: 'REQUIRED_PASSWORD',
                  })}
                />
              </Field>
              <Field
                label="Nueva Contraseña"
                htmlFor="newPassword"
                errorMessage={t(passwordErrors.newPassword?.message)}
                error={!!passwordErrors.newPassword}
                className="small"
                vertical
              >
                <input
                  type="password"
                  name="newPassword"
                  {...passwordRegister('newPassword', {
                    required: 'REQUIRED_PASSWORD',
                    pattern: {
                      message: 'INVALID_PASSWORD',
                      value: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)\S{8,}$/,
                    },
                  })}
                />
              </Field>
              <Field
                label="Repetir Nueva Contraseña"
                htmlFor="repeatNewPassword"
                errorMessage={t(passwordErrors.repeatNewPassword?.message)}
                error={!!passwordErrors.repeatNewPassword}
                className="small"
                vertical
              >
                <input
                  type="password"
                  name="repeatNewPassword"
                  {...passwordRegister('repeatNewPassword', {
                    required: 'REQUIRED_REPEAT_PASSWORD',
                    pattern: {
                      message: 'INVALID_PASSWORD',
                      value: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)\S{8,}$/,
                    },
                    validate: (value) =>
                      value !== getPasswordValues('newPassword')
                        ? 'PASSWORDS_DONT_MATCH'
                        : undefined,
                  })}
                />
              </Field>
              <RoundedButton
                title={t('SAVE_PASSWORD')}
                type="submit"
                size="small"
              />
              <span className="divider" />
            </fieldset>
          </form>
        ) : null}
        <div className="actions">
          {/* {abandonTeam ? (
            <>
              <RoundedButton
                title="Confirmar"
                size="small"
                onClick={onConfirmAbandonTeam}
              />
              <RoundedButton
                title="Cancelar"
                size="small"
                className="grey"
                onClick={(): void => setAbandonTeam(false)}
              />
            </>
          ) : (
            <RoundedButton
              title={t('ABANDON_TEAM')}
              size="small"
              className="grey"
              rightIcon={<CloseSmall />}
              onClick={(): void => setAbandonTeam(true)}
            />
          )} */}

          <div className="bottom">
            <RoundedButton
              title="Ver bases legales y política de privacidad"
              size="small"
            />
            <RoundedButton
              title={t('CLOSE_SESSION')}
              size="small"
              onClick={logOutAndRedirect}
            />
          </div>
        </div>
      </div>
    </div>
  );
};

export default MyProfile;
