// Hooks
import { FC, useCallback, useEffect, useState } from 'react';
import { useStore } from 'stores/StoreProvider';
import { observer } from 'mobx-react-lite';

// Antd
import { Form, Row, Col } from 'antd';

// Components
import EventCardInfo from 'pages/EventsJournalDashboard/EventCardInfo';
import { CardInfoDrawer } from 'components/Modals/CardInfoDrawer/CardInfoDrawer';
import { DrawerHeader } from './DrawerHeader';
import { DrawerFooter } from './DrawerFooter';

// Types
import { TypeIncidentsCardInfo } from './types';
import { Event, IncidentEdit } from 'myApi';
import { RootStore } from 'stores/RootStore';
import { DefaultFields } from '../types';

// Apps
import {
  incidentCardInfoFormLargeTemplate,
  incidentCardInfoFormSmallTemplate,
} from './IncidentCardInfoFormTemplate';
import { prepareDataForSubmit, TSubmitData } from './helpers';
import { NCIRCCNotificationForm } from '../NCIRCCNotificationForm';
import { openNotificationError } from 'components/Messages';
import { useIncidentDashboardMessage } from '../i18n';
import { useEventsJournalMessages } from 'pages/EventsJournalDashboard/i18n';
import EventsTable from './EventsTable';
import moment from 'moment';

// Constants
import { DEFAULT_FIELDS } from '../constants';
import RecommendationAndEffectsTable from './CardWithPagination';

// Styles
import classNames from 'classnames';
import styles from './IncidentsCardInfo.module.scss';

export const IncidentsCardInfo: FC<TypeIncidentsCardInfo> = observer(
  ({ parentPage }) => {
    // Store
    const rootStore: RootStore = useStore();
    const ncirccStore = rootStore.ncirccStore;
    const incidentsUiStore = rootStore.incidentsUiStore;
    const incidentsStore = rootStore.incidentsStore;

    const { incidentsCardInfo } = useIncidentDashboardMessage();
    const {
      table: { cardInfo },
    } = useEventsJournalMessages();

    const { incidentById } = incidentsUiStore;

    const [isShowEventsCardInfo, setIsShowEventsCardInfo] =
      useState<boolean>(false);

    const [form] = Form.useForm();

    useEffect(() => {
      return () => incidentsStore.resetSelectedIncident();
    }, [incidentsStore, incidentsStore.resetSelectedIncident]);

    const fetchData = useCallback(async (): Promise<void> => {
      if (parentPage === 'incidentsDashboard') {
        // Загрузка информации о компании
        try {
          await ncirccStore.fetchCompanyInfo();
        } catch (e) {
          openNotificationError({
            messageTitle: incidentsCardInfo.notification.failedFetchCompanyInfo,
          });
        }
      }
    }, [ncirccStore, parentPage]);

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

    const {
      formItem: { smallCardMessages, largeCardMessages },
      ...translation
    } = incidentsCardInfo;

    useEffect(() => {
      if (incidentsStore.incident)
        form.setFieldsValue({
          importance: incidentsStore.incident.importance,
          title: incidentsStore.incident.title,
          assigned_to:
            incidentsStore.incident.status === 0
              ? null
              : incidentsStore.incident.assigned_to,
          events: !Array.isArray(incidentsStore.incident.events)
            ? null
            : incidentsStore.incident.events
                .map((item: Event) => item.sign_name)
                .join(', '),
          status: incidentsStore.incident.status,
          deadline:
            incidentsStore.incident.deadline &&
            (moment(
              incidentsStore.incident.deadline,
              'YYYY-MM-DD',
            ) as unknown as string),
          comment: incidentsStore.incident.comment,
          created: moment(incidentsStore.incident.created).format(
            'D.MM.YYYY HH:mm:ss',
          ),
        });
    }, [form, incidentsStore.incident]);

    const onFinish = async (editedCardInfo: TSubmitData): Promise<void> => {
      const data: IncidentEdit = prepareDataForSubmit(editedCardInfo);
      if (incidentsStore.incident?.incident_id) {
        try {
          await incidentsUiStore.patchIncident(
            incidentsStore.incident.incident_id,
            data,
          );
        } catch (e) {
          openNotificationError({
            messageTitle: incidentsCardInfo.notification.failedPatchIncident,
          });
        }
      }
    };

    const layout = {
      labelCol: {
        span: incidentsUiStore.incidentCardSize === 'large' ? 24 : 8,
      },
      wrapperCol: {
        span: incidentsUiStore.incidentCardSize === 'large' ? 24 : 14,
      },
    };
    const colSpanStyle = incidentsUiStore.incidentCardSize === 'large' ? 8 : 24;

    const renderBlocks = (
      block: string,
    ): JSX.Element | JSX.Element[] | null => {
      if (incidentById) {
        switch (block) {
          case DefaultFields.EFFECTS: {
            if (incidentById?.effects) {
              return (
                <RecommendationAndEffectsTable
                  data={incidentById?.effects}
                  translations={largeCardMessages.recommendationAndEffectsTable}
                />
              );
            } else return null;
          }
          case DefaultFields.RECOMMENDATION: {
            if (incidentById?.close_recommendations) {
              return (
                <RecommendationAndEffectsTable
                  data={incidentById?.close_recommendations}
                  translations={largeCardMessages.recommendationAndEffectsTable}
                />
              );
            } else {
              return null;
            }
          }
          case DefaultFields.EVENTS: {
            if (incidentsStore.incident) {
              return (
                <EventsTable
                  cardInfo={incidentsStore.incident}
                  translations={largeCardMessages.eventsTable}
                  setIsShowEventsCardInfo={setIsShowEventsCardInfo}
                />
              );
            } else {
              return null;
            }
          }

          default: {
            return incidentCardInfoFormLargeTemplate(
              !incidentsUiStore.isFormDisabled,
              incidentsUiStore.setIsAssignTo,
              largeCardMessages,
            )[block].map((elem, index) => (
              <div
                key={index}
                style={{
                  width: '100%',
                }}
              >
                {elem}
              </div>
            ));
          }
        }
      } else {
        return null;
      }
    };

    return (
      <>
        <CardInfoDrawer
          loading={incidentsStore.isIncidentLoading}
          cardSize={incidentsUiStore.incidentCardSize}
          onToggleCardSize={
            parentPage === 'incidentsDashboard'
              ? incidentsUiStore.toggleIncidentCardSize
              : undefined
          }
          onCloseCard={incidentsUiStore.closeIncidentCard}
          title={<DrawerHeader form={form} translation={translation} />}
          drawerFooter={
            incidentsUiStore.incidentCardSize === 'small' &&
            parentPage === 'incidentsDashboard' ? (
              <DrawerFooter form={form} translation={translation} />
            ) : null
          }
        >
          <Form
            {...layout}
            form={form}
            onFinish={onFinish}
            className={classNames(styles['formItem'], {
              [styles['smallFormItem']]:
                incidentsUiStore.incidentCardSize === 'small',
            })}
          >
            <Row gutter={24}>
              {incidentsUiStore.incidentCardSize === 'large'
                ? DEFAULT_FIELDS.map((item, index) => {
                    return (
                      <div
                        key={index}
                        style={{
                          width: '100%',
                          margin: '0 10px 10px 10px',
                        }}
                      >
                        <span style={{ fontWeight: 'bold' }}>
                          {largeCardMessages[item].name}
                        </span>
                        <div
                          style={{
                            display: 'grid',
                            gridTemplateColumns: 'repeat(3, 1fr)',
                            gap: '20px',
                            background: 'rgba(242, 242, 242, 0.3)',
                            boxShadow: '0px 4px 4px rgba(0, 0, 0, 0.25)',
                            borderRadius: '8px',
                            padding: 30,
                          }}
                        >
                          {renderBlocks(item)}
                        </div>
                      </div>
                    );
                  })
                : incidentCardInfoFormSmallTemplate(
                    !incidentsUiStore.isFormDisabled,
                    incidentsUiStore.setIsAssignTo,
                    smallCardMessages,
                  ).map((elem, index) => (
                    <Col key={index} span={colSpanStyle}>
                      {elem}
                    </Col>
                  ))}
            </Row>
          </Form>
        </CardInfoDrawer>
        <NCIRCCNotificationForm />
        {isShowEventsCardInfo && (
          <EventCardInfo
            cardInfo={incidentById?.events[0]}
            translations={cardInfo}
            setCardInfo={setIsShowEventsCardInfo}
            isLarge={false}
          />
        )}
      </>
    );
  },
);
