import { FC, useCallback, useEffect, useState } from 'react';
import { useStore } from 'stores/StoreProvider';
import { observer } from 'mobx-react-lite';
import { openNotificationSuccess } from 'components/Messages';
import { useNCIRCCMessages } from '../i18n';
import { Button, Checkbox, Form, Input, Select } from 'antd';
import { affectedSystemFunctions } from './helpers';
import { RootStore } from 'stores/RootStore';
import { Company, CompanyCreateUpdate, LocationCodeList } from 'myApi';

import styles from './OrganizationCard.module.scss';

export const OrganizationCard: FC = observer(() => {
  const rootStore: RootStore = useStore();
  const ncirccStore = rootStore.ncirccStore;

  const { organizationCardMessages } = useNCIRCCMessages();

  const [organizationInfo, setOrganizationInfo] = useState<Company | null>(
    null,
  );
  const [locationMap, setLocationMap] = useState<LocationCodeList>([]);
  const [locationLoading, setLocationLoading] = useState(false);

  const [form] = Form.useForm();

  const onFinish = async (values: CompanyCreateUpdate): Promise<void> => {
    try {
      await ncirccStore.postCompanyInfo(values);
      openNotificationSuccess({
        messageTitle: organizationCardMessages.notification.saveSuccess,
      });
    } catch (e) {
      console.error(e);
    }
  };

  // Получение данных о компании о локации
  const fetchAllDataForOrganizationCard =
    useCallback(async (): Promise<void> => {
      try {
        setLocationLoading(true);
        const response = await Promise.allSettled([
          ncirccStore.fetchCompanyInfo(),
          ncirccStore.fetchLocation(),
        ]);
        const cardInfo = response[0];
        const location = response[1];

        if (cardInfo.status === 'fulfilled') {
          setOrganizationInfo(cardInfo.value);
        }

        if (location.status === 'fulfilled') {
          if (Array.isArray(location.value)) {
            setLocationMap(location.value);
            setLocationLoading(false);
          }
        }
      } catch (e) {
        console.error(e);
      }
    }, [ncirccStore]);

  useEffect(() => {
    fetchAllDataForOrganizationCard();
  }, [fetchAllDataForOrganizationCard]);

  useEffect(() => {
    form.setFieldsValue({
      affected_system_function: organizationInfo?.affected_system_function,
      api_key: organizationInfo?.api_key,
      city: organizationInfo?.city,
      is_cii: organizationInfo?.is_cii,
      name: organizationInfo?.name,
    });
    if (locationMap.length) {
      form.setFieldsValue({
        location: organizationInfo?.location?.id,
      });
    }
  }, [
    form,
    locationMap,
    organizationInfo?.affected_system_function,
    organizationInfo?.api_key,
    organizationInfo?.city,
    organizationInfo?.is_cii,
    organizationInfo?.location?.id,
    organizationInfo?.name,
  ]);

  return (
    <div className={styles['container']}>
      <Form
        className={styles['form']}
        layout="vertical"
        form={form}
        onFinish={onFinish}
      >
        <div className={styles['wrapper']}>
          <div>
            <div className={styles['ncircc-text--link']}>
              <Button
                type="primary"
                href={process.env.REACT_APP_NCIRCC_AUTHORIZATION_LINK}
                target="_blank"
                rel="noopener noreferrer"
              >
                {organizationCardMessages.personal_account_NCCC}
              </Button>
            </div>
            <Form.Item
              label={organizationCardMessages.name.title}
              name="name"
              rules={[
                {
                  required: !locationLoading,
                  message: organizationCardMessages.name.validateMessage,
                  whitespace: true,
                },
              ]}
              style={{ maxWidth: '44%' }}
            >
              <Input disabled={!locationMap.length} />
            </Form.Item>
            <Form.Item name="is_cii" valuePropName="checked">
              <Checkbox disabled={!locationMap.length}>
                {organizationCardMessages.subject_CII}
              </Checkbox>
            </Form.Item>
          </div>

          <div className="grid-column-2-gap24">
            <Form.Item
              label={organizationCardMessages.location.title}
              name="location"
              rules={[
                {
                  required: !locationLoading,
                  message: organizationCardMessages.location.validateMessage,
                },
              ]}
              style={{ maxWidth: '90%' }}
            >
              <Select
                disabled={!locationMap.length}
                loading={locationLoading}
                options={locationMap.map((locationData) => ({
                  label: locationData.code,
                  value: locationData.id,
                }))}
              />
            </Form.Item>
            <Form.Item
              label={organizationCardMessages.city.title}
              name="city"
              rules={[
                {
                  required: !locationLoading,
                  message: organizationCardMessages.city.validateMessage,
                  whitespace: true,
                },
              ]}
              style={{ maxWidth: '90%' }}
            >
              <Input disabled={!locationMap.length} />
            </Form.Item>
            <Form.Item
              label={organizationCardMessages.sphere_func_subject.title}
              name="affected_system_function"
              rules={[
                {
                  required: !locationLoading,
                  message:
                    organizationCardMessages.sphere_func_subject
                      .validateMessage,
                },
              ]}
              style={{ maxWidth: '90%' }}
            >
              <Select
                disabled={!locationMap.length}
                options={affectedSystemFunctions}
              />
            </Form.Item>
          </div>
        </div>

        <div className={styles['wrapper']}>
          <Form.Item
            label={organizationCardMessages.api_key.title}
            name="api_key"
            rules={[
              {
                required: !locationLoading,
                message: organizationCardMessages.api_key.validateMessage,
                whitespace: true,
              },
              {
                max: 128,
                message:
                  'Длинна апи токена не может быть больше чем 128 символов',
              },
            ]}
          >
            <Input disabled={!locationMap.length} />
          </Form.Item>
        </div>
        <Form.Item wrapperCol={{ offset: 0, span: 1 }}>
          <Button type="primary" htmlType="submit">
            {organizationCardMessages.save}
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
});
