// Hooks
import { useEffect, useMemo } from 'react';
import { useStore } from 'stores/StoreProvider';
import { observer } from 'mobx-react-lite';
import { useAsyncEffect } from 'hooks/useAsyncEffect';
import { useIncidentDashboardMessage } from './i18n';

// Components
import { makeIncidentsColumns } from './makeIncidentsColumns';
import { collectionButtonForIncidentsCollectiveActions } from './helpers';
import { IncidentsCardInfo } from './IncidentsCardInfo';
import { openNotificationError } from 'components/Messages';
import useActionsWithSelectedCards from 'components/DashboardTable/components/useActionsWithSelectedCards';
import Dashboard from 'components/Dashboard';

// Types
import { RootStore } from 'stores/RootStore';
import { Incident } from 'myApi';
import { TypeActionButtonsConfig } from 'components/DashboardTable/components/useActionsWithSelectedCards/types';
import { ColumnsType } from 'antd/es/table';

// Styles
import './Incidents.scss';
import { TypeNCIRCCStatusButtonText } from './IncidentsCardInfo/types';

export const IncidentsDashboard = observer(() => {
  const rootStore: RootStore = useStore();
  const incidentsUiStore = rootStore.incidentsUiStore;
  const incidentsStore = rootStore.incidentsStore;
  const ncirccStore = rootStore.ncirccStore;

  const { table, leftSidebar } = useIncidentDashboardMessage();

  const onEditIncident = async (id: string): Promise<void> => {
    try {
      await incidentsStore.fetchIncidentById(id);
      incidentsUiStore.setIncidentCardSize('small');
      incidentsUiStore.setIsDisabledForm(false);
    } catch (e) {
      console.error(e);
    }
  };
  const onResolveIncident = async (id: string): Promise<void> => {
    try {
      await incidentsUiStore.resolveIncident(id);
      incidentsStore.resetSelectedIncident();
    } catch (e) {
      console.error(e);
    }
  };

  useEffect(() => {
    return () => {
      incidentsUiStore.setIncidentCardSize(undefined);
      incidentsUiStore.setNcirccNotificationCard(undefined);
    };
  });

  const incidentsTableColumns: ColumnsType<Incident> = makeIncidentsColumns(
    { columnMessages: table },
    {
      onEditIncident: onEditIncident,
      onResolveIncident: onResolveIncident,
    },
  );

  const onSearch = (): void => {};

  useAsyncEffect(async () => {
    await incidentsUiStore.fetchAllIncidents();
  }, [
    incidentsUiStore.dashboardState.current,
    incidentsUiStore.dashboardState.pageSize,
    incidentsUiStore.getSorterField,
  ]);

  const onRowEvent = async (card: Incident): Promise<void> => {
    try {
      ncirccStore.resetNotificationById();
      ncirccStore.setIsAdditionNotification(TypeNCIRCCStatusButtonText.Send);
      incidentsUiStore.setIncidentCardSize('small');
      await incidentsStore.fetchIncidentById(card.incident_id);
      if (incidentsStore.incident?.notification_id) {
        await ncirccStore.getNotificationById(
          incidentsStore.incident.notification_id,
        );
      }
    } catch (e) {
      openNotificationError({ messageTitle: 'Загрузка инцидента не удалась.' });
      incidentsUiStore.setIncidentCardSize(undefined);
    }
  };

  const leftSideBarContent = [
    {
      title: leftSidebar.title,
      key: 0,
    },
    {
      title: leftSidebar.list,
      path: '/incidents',
      key: 1,
    },
  ];

  const currentAction = useMemo((): TypeActionButtonsConfig[] => {
    const action = collectionButtonForIncidentsCollectiveActions({
      exportCSV: incidentsUiStore.exportCSV,
    });

    return [action.exports];
  }, [incidentsUiStore.exportCSV]);

  return (
    <Dashboard
      loading={incidentsUiStore.loading}
      columns={incidentsTableColumns}
      cards={incidentsUiStore.incidentsList}
      onRowEvent={onRowEvent}
      changeRowCount={incidentsUiStore.setIncidentsDashboardState}
      leftSideBarContent={leftSideBarContent}
      setCheckedColumns={incidentsUiStore.setCheckedColumns}
      getCheckedColumns={incidentsUiStore.getCheckedColumns}
      setSorterField={incidentsUiStore.setSorterField}
      onSearch={onSearch}
      pageState={incidentsUiStore.dashboardState}
      actionsWithCards={useActionsWithSelectedCards(currentAction)}
      filters={null}
      cardInfoComponent={<IncidentsCardInfo parentPage="incidentsDashboard" />}
    />
  );
});
