import React, { useContext, useEffect } from 'react';
import {
  Field,
  ErrorMessage,
  FormikContext,
  FormikContextType,
} from 'formik/dist/index';
import { FormSelect } from 'components/form/form-select';
import { FormTextField } from 'components/form/form-textfield';
import { useFetch } from 'utils/use-fetch';
import { User } from 'common/types';
import { userAdministrationInitialValues } from './user-formular';
import { CustomButton } from 'components/button/custom-button';

interface BasicProps {
  createFormular: boolean;
}

function transformUsersIntoOptions(users: User[]) {
  return users.map(({ login }) => ({
    label: login,
    value: login,
  }));
}

function preFillUserData(
  user: User | null,
  setFieldValue: (
    field: string,
    value: any,
    shouldValidate?: boolean | undefined
  ) => void
) {
  if (user) {
    setFieldValue('firstName', user.firstName);
    setFieldValue('surName', user.surName);
    setFieldValue('role', { value: user.role, label: user.role });
  }
}

function clearUserData(
  setFieldValue: (
    field: string,
    value: any,
    shouldValidate?: boolean | undefined
  ) => void
) {
  setFieldValue('login', undefined);
  setFieldValue('firstName', undefined);
  setFieldValue('surName', undefined);
  setFieldValue('role', undefined);
  setFieldValue('password', undefined);
}

export const UserAdministrationBasic = ({ createFormular }: BasicProps) => {
  const { values, setFieldValue } = useContext<
    FormikContextType<userAdministrationInitialValues>
  >(FormikContext);

  const users = transformUsersIntoOptions(
    useFetch('http://localhost:8000/user').response ?? []
  );

  const user = (useFetch(`http://localhost:8000/user/${values.login}`)
    .response ?? [])[0];

  useEffect(() => {
    if (!createFormular && values.login) {
      preFillUserData(user, setFieldValue);
    }

    if (createFormular) {
      clearUserData(setFieldValue);
    }
  }, [createFormular, values.login, user, setFieldValue]);

  return (
    <>
      {createFormular ? (
        <Field
          name="login"
          type="text"
          component={FormTextField}
          label="Přihlašovací jméno"
        />
      ) : (
        <Field
          name="login"
          type="select"
          component={FormSelect}
          label="Přihlašovací jméno"
          options={users}
        />
      )}

      <ErrorMessage
        name="login"
        render={msg => (
          <span style={{ color: '#F55044', marginBottom: 20 }}>{msg}</span>
        )}
      />

      <Field
        name="firstName"
        type="text"
        component={FormTextField}
        label="Jméno"
      />
      <ErrorMessage
        name="tariff"
        render={msg => (
          <span style={{ color: '#F55044', marginBottom: 20 }}>{msg}</span>
        )}
      />

      <Field
        name="surName"
        type="text"
        component={FormTextField}
        label="Přijmení"
      />

      <ErrorMessage
        name="surName"
        render={msg => (
          <span style={{ color: '#F55044', marginBottom: 20 }}>{msg}</span>
        )}
      />

      <Field
        name="password"
        type="text"
        component={FormTextField}
        label="Přihlašovací heslo"
      />
      <ErrorMessage
        name="password"
        render={msg => (
          <span style={{ color: '#F55044', marginBottom: 20 }}>{msg}</span>
        )}
      />

      <Field
        name="role"
        type="select"
        component={FormSelect}
        label="Typ"
        options={[
          {
            label: 'Správce',
            value: 'Admin',
          },
          {
            label: 'Běžný uživatel',
            value: 'User',
          },
        ]}
      />
      <ErrorMessage
        name="role"
        render={msg => (
          <span style={{ color: '#F55044', marginBottom: 20 }}>{msg}</span>
        )}
      />

      <CustomButton
        label={`${createFormular ? 'Vytvořit' : 'Upravit'} uživatele`}
        variant="outlined"
        size="medium"
        type="submit"
      />
    </>
  );
};
