// Libs
// -----------------------------------------------------------------------------
import React, { FC } from 'react';
import {
  Form,
  FormInstance,
  Row,
  Col,
  Input,
  Switch,
  Select,
  Checkbox,
} from 'antd';

import { observer } from 'mobx-react-lite';
import moment, { Moment } from 'moment';

// App
// -----------------------------------------------------------------------------
import { TypeAccount } from 'types/default';
import { useAccountsDashboardLocale } from '../i18n';
import { useCommonMessages } from 'components/i18n';
import { timeZone } from 'assets/constants/timeZones';
import { validatePassword } from 'components/formValidators';
import { StringDatePicker } from 'components';
import { ValidateErrorEntity } from 'rc-field-form/lib/interface';

// Props
// -----------------------------------------------------------------------------
type AccountFormProps = {
  form: FormInstance<TypeAccount>;
  onFormSubmit: (values: TypeAccount) => void;
  onFormError: (errData: ValidateErrorEntity<TypeAccount>) => void;
  isCurrentUser: boolean;
  isFormDisabled: boolean;
  isNewUser: boolean;
  isFullSize: boolean;
  initialValues: TypeAccount | undefined;
};

export const AccountForm: FC<AccountFormProps> = observer(
  ({
    form,
    onFormSubmit,
    onFormError,
    isCurrentUser,
    isFormDisabled,
    isNewUser,
    isFullSize,
    initialValues,
  }) => {
    const pageLocale = useAccountsDashboardLocale();
    const commonLocale = useCommonMessages();

    const columnSpan = isFullSize ? 8 : 24;

    return (
      <Form<TypeAccount>
        form={form}
        layout="vertical"
        initialValues={initialValues}
        scrollToFirstError
        onFinish={onFormSubmit}
        onFinishFailed={onFormError}
        autoComplete="new-password"
      >
        <Form.Item hidden name={['user', 'id']}>
          <Input type="hidden" />
        </Form.Item>

        {isCurrentUser ? (
          <Form.Item
            name={['user', 'is_active']}
            valuePropName="checked"
            hidden
          >
            <Checkbox />
          </Form.Item>
        ) : (
          <Row gutter={[32, 0]}>
            <Col span={24}>
              <Form.Item
                label={pageLocale.isActive}
                name={['user', 'is_active']}
                valuePropName="checked"
                help={
                  isCurrentUser
                    ? pageLocale.cannotDeactivateCurrentUser
                    : undefined
                }
                extra={pageLocale.isActiveExtra}
              >
                <Switch
                  disabled={isFormDisabled || isCurrentUser}
                  checkedChildren={pageLocale.active}
                  unCheckedChildren={pageLocale.blocked}
                />
              </Form.Item>
            </Col>
          </Row>
        )}

        <Row gutter={[32, 0]}>
          <Col span={columnSpan}>
            <Form.Item
              label={pageLocale.login}
              name={['user', 'username']}
              rules={[
                {
                  type: 'string',
                  required: true,
                  // Как на бэкенде: только латинские буквы в обоих регистрах и цифры
                  pattern: /^[a-zA-Z0-9]*$/,
                  message: pageLocale.loginError,
                },
              ]}
            >
              <Input disabled={isFormDisabled} />
            </Form.Item>
          </Col>

          <Col span={columnSpan}>
            <Form.Item
              label={pageLocale.fio}
              name={['user', 'first_name']}
              rules={[
                {
                  type: 'string',
                  required: true,
                  // Юникодные буквы, пробелы и минусы (для составных фамилий)
                  pattern: /^[\p{Letter} -]+$/iu,
                  message: pageLocale.fioError,
                  whitespace: true,
                },
              ]}
            >
              <Input disabled={isFormDisabled} />
            </Form.Item>
          </Col>

          <Col span={columnSpan}>
            <Form.Item
              label={pageLocale.email}
              name={['user', 'email']}
              rules={[
                {
                  type: 'email',
                  required: true,
                  message: pageLocale.emailError,
                },
              ]}
            >
              <Input disabled={isFormDisabled} />
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={[32, 0]}>
          {isCurrentUser ? (
            <Col span={columnSpan}>
              <Form.Item
                label={pageLocale.oldPassword}
                name={['user', 'old_password']}
                dependencies={[['user', 'password']]}
                rules={[
                  ({ getFieldValue }) => ({
                    type: 'string',
                    required: !!getFieldValue(['user', 'password']),
                    message: pageLocale.fieldIsRequired,
                  }),
                ]}
              >
                <Input.Password disabled={isFormDisabled} />
              </Form.Item>
            </Col>
          ) : null}

          <Col span={columnSpan}>
            <Form.Item
              label={
                isCurrentUser ? pageLocale.newPassword : pageLocale.password
              }
              name={['user', 'password']}
              rules={[
                {
                  type: 'string',
                  required: isNewUser,
                  validator: validatePassword,
                  message: pageLocale.passwordError,
                },
              ]}
            >
              <Input.Password disabled={isFormDisabled} />
            </Form.Item>
          </Col>

          <Col span={columnSpan}>
            <Form.Item
              label={
                isCurrentUser
                  ? pageLocale.repeatNewPassword
                  : pageLocale.repeatPassword
              }
              name="_password_repeat"
              dependencies={[['user', 'password']]}
              rules={[
                ({ getFieldValue }) => ({
                  type: 'string',
                  required: isNewUser || !!getFieldValue(['user', 'password']),
                  message: pageLocale.fieldIsRequired,
                }),
                ({ getFieldValue }) => ({
                  validator: (_, value) =>
                    !value || getFieldValue(['user', 'password']) === value
                      ? Promise.resolve()
                      : Promise.reject(),
                  message: pageLocale.repeatPasswordError,
                }),
              ]}
            >
              <Input.Password disabled={isFormDisabled} />
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={[32, 0]}>
          <Col span={columnSpan}>
            <Form.Item
              label={pageLocale.timezone}
              name="timezone"
              rules={[
                {
                  type: 'string',
                  required: true,
                  message: pageLocale.fieldIsRequired,
                },
              ]}
            >
              <Select
                disabled={isFormDisabled}
                options={timeZone.map((tz) => ({
                  value: tz,
                }))}
                showSearch
              />
            </Form.Item>
          </Col>

          <Col span={columnSpan}>
            <Form.Item
              label={pageLocale.expireDate}
              name="expire_date"
              extra={pageLocale.expireDateExtra}
            >
              <StringDatePicker
                format="DD.MM.YYYY"
                disabled={isFormDisabled}
                style={{ width: '100%' }}
                disabledDate={(current: Moment) => {
                  // Нельзя выбрать сегодняшний день и ранее
                  return current && current < moment().endOf('day');
                }}
                allowClear
                inputReadOnly
              />
            </Form.Item>
          </Col>
        </Row>
      </Form>
    );
  },
);
