import { useEffect, useMemo, useState } from 'react';
import { useStore } from 'stores/StoreProvider';
import { observer } from 'mobx-react-lite';
import { getCards } from './converter';
import { usePathName } from 'components/DashboardTable';
import { useAssetsColumns } from './useAssetsColumns';
import { useAssetsLeftSideBarContents } from './AssetsLeftSideBarContent';
import { TagDrawer } from 'components/Modals/TagDrawer/TagDrawer';
import { CardInfoDrawer } from 'components/Modals/CardInfoDrawer/CardInfoDrawer';
import { AssetCardInfoForm } from './AssetsCardInfo/FormItems';
import { AssetCardInfoLargeForm } from './AssetsCardInfo/FormItemsLarge';
import { useNavigate, useParams } from 'react-router-dom';
import {
  openNotificationSuccess,
  openNotificationError,
} from 'components/Messages';
import { openNotificationWithIcon } from 'components/Notification/notification';
import { collectionButtonForAssetsCollectiveActions } from './helpers';
import { AssetPatchIncoming } from './types';
import { TypeTags } from 'types/default';
import { TCommonMessages, useCommonMessages } from 'components/i18n';
import { TAssetsMessages, useAssetsMessages } from './i18n';
import { TypeDashboardPaginationState } from 'components/Dashboard/types';
import { TypeActionButtonsConfig } from 'components/DashboardTable/components/useActionsWithSelectedCards/types';
import { Form } from 'antd';
import Dashboard from 'components/Dashboard';
import useActionsWithSelectedCards from 'components/DashboardTable/components/useActionsWithSelectedCards';
import { AxiosResponse } from 'axios';
export const AssetsDashboard = observer(() => {
  const translation: TAssetsMessages = useAssetsMessages();
  const commonTranslation: TCommonMessages = useCommonMessages();

  const {
    table: { collectiveActionsMessages },
  }: TAssetsMessages = translation;

  const pathName = usePathName();
  const { id: idx } = useParams();

  const pathStringToArray = pathName.split('/');
  const navigate = useNavigate();
  const {
    loading,
    loadingCard,
    assetsList,
    osList,
    countAssets,
    countGroups,
    tagsList,
    putGroupsList,
    loadingOSList,
    loadingAssetsList,
    loadingGroupsList,
    setSelectedTag,
    deleteGroupsRecord,
    deleteAssetsRecord,
    getSelectedTagId,
    postGroupsList,
    patchGroupsList,
    getSelectedTag,
    setSelectedCard,
    getSelectedCard,
    loadingManufacturersList,
    postOsList,
    changeCardSize,
    cardSize,
    loadingAssetRecord,
    patchAssetsRecord,
    changeAssetsRecord,
    manufacturersList,
    exportCSV,
    setCheckedColumns,
    getCheckedColumns,
  } = useStore().assetsUiStore;

  const columns = useAssetsColumns(translation, pathName);

  const [disabledForm, setDisabledForm] = useState<boolean>(true);

  const [sorterField, setSorterField] = useState<string>('');

  const [nameTable, setNameTable] = useState<'assetsTable' | 'assetsGroups'>(
    'assetsTable',
  );

  const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([]);

  const [dashboardState, setDashboardState] =
    useState<TypeDashboardPaginationState>({
      current: 1,
      pageSize: 10,
      total: nameTable === 'assetsTable' ? countAssets : countGroups,
    });

  useEffect(() => {
    loadingOSList();
    loadingManufacturersList();
  }, [loadingOSList]);

  useEffect(() => {
    const masPath = pathName.split('/');
    // Изменение названия карточки, для остлеживания где мы находимся, на странце ассетов или на страци групп. /assets и /assets/1 - одна и таже страница
    if (
      masPath[masPath.length - 1] === 'assets' ||
      (idx &&
        masPath[masPath.length - 2] === 'assets' &&
        Number.isInteger(+idx))
    ) {
      setNameTable('assetsTable');
      setSelectedRowKeys([]);
      setDashboardState({
        current: 1,
        pageSize: 10,
        total: countAssets,
      });
    }

    if (
      masPath[masPath.length - 1] === 'groups' &&
      masPath[masPath.length - 2] === 'assets'
    ) {
      setNameTable('assetsGroups');
      setSelectedRowKeys([]);
      setDashboardState({
        current: 1,
        pageSize: 10,
        total: countGroups,
      });
    }
    // Изменение размера карточки, в зависимоти от страницы где мы находимся, на странце ассетов или на страци групп. /assets и /assets/1 - одна и таже страница

    if (
      pathStringToArray[pathStringToArray.length - 2] === 'assets' &&
      Number.isInteger(
        parseInt(pathStringToArray[pathStringToArray.length - 1]),
      )
    ) {
      if (!getSelectedCard)
        loadingAssetRecord(
          parseInt(pathStringToArray[pathStringToArray.length - 1]),
        );
      changeCardSize('large');
    }
    if (
      pathStringToArray[pathStringToArray.length - 1] === 'assets' &&
      getSelectedCard
    ) {
      changeCardSize('small');
    }
  }, [pathName]);

  useEffect(() => {
    setSelectedTag(null);
    setSelectedCard(null);
    setCheckedColumns(columns);
    setSorterField('');
    setDisabledForm(true);
  }, [nameTable]);

  useEffect(() => {
    if (nameTable === 'assetsTable') {
      loadingAssetsList(
        dashboardState.current,
        dashboardState.pageSize,
        sorterField,
      );
      loadingGroupsList(1, 1000, '');
    }
    if (nameTable === 'assetsGroups')
      loadingGroupsList(
        dashboardState.current,
        dashboardState.pageSize,
        sorterField,
      );
  }, [
    sorterField,
    nameTable,
    loadingAssetsList,
    loadingGroupsList,
    dashboardState.current,
    dashboardState.pageSize,
  ]);

  useEffect((): void => {
    if (nameTable)
      setDashboardState((prevState) => ({
        ...prevState,
        total: nameTable === 'assetsTable' ? countAssets : countGroups,
      }));
  }, [countAssets, countGroups, nameTable]);

  const currentLeftSideBarTab = isNaN(
    +pathStringToArray[pathStringToArray.length - 1],
  )
    ? pathStringToArray[pathStringToArray.length - 1]
    : pathStringToArray[pathStringToArray.length - 2];

  const onSearch = (value: any): void => console.log(value);

  const onRowEvent = (card: any): void => {
    loadingAssetRecord(card.id);
    changeCardSize('small');
  };

  const rowSelection: {
    selectedRowKeys: number[];
    onSetSelectedRowItem: (ids: number[]) => void;
  } = {
    selectedRowKeys,
    onSetSelectedRowItem: setSelectedRowKeys,
  };

  const hasSelected = selectedRowKeys.length > 0;

  const changeRowCount = (current: number, pageSize: number): void => {
    setDashboardState((prevState) => ({
      ...prevState,
      current,
      pageSize,
    }));
  };

  const addGroupRecord = (name: string, description: string): void => {
    putGroupsList(name, description);
  };

  const setSelectTag = (id: number | undefined | null): void => {
    setSelectedTag(id);
  };

  // Групповые действия с активами
  //-----------------------------------------------------------

  const onExports = async (): Promise<void> => {
    await exportCSV();
    openNotificationSuccess({
      messageTitle: translation.notification.titleDownload,
      messageDescription: translation.notification.descriptionDownload,
    });
  };
  const onCollectiveAssetsDelete = async (): Promise<void> => {
    await deleteAssetsRecord(selectedRowKeys);
    if (selectedRowKeys.length < assetsList.length) {
      await loadingAssetsList(
        dashboardState.current,
        dashboardState.pageSize,
        sorterField,
        selectedRowKeys.length,
      );
    } else {
      setDashboardState((prevState) => {
        return {
          ...prevState,
          current: Math.ceil(
            (prevState.total - selectedRowKeys.length) / prevState.pageSize,
          ),
        };
      });
    }
    openNotificationSuccess({
      messageTitle: translation.notification.titleDeleted,
      messageDescription: translation.notification.descriptionDeleted,
    });
    setSelectedRowKeys([]);
  };

  const onCollectiveAssetsChangeStatus = async (): Promise<void> => {
    await changeAssetsRecord(selectedRowKeys);
    setSelectedRowKeys([]);
    openNotificationSuccess({
      messageTitle: translation.notification.changeStatus,
    });
  };

  const ctActions = async (props: any): Promise<void> => {
    switch (props.action) {
      case 'delete':
        if (nameTable === 'assetsGroups') {
          await deleteGroupsRecord(props?.id ? props.id : selectedRowKeys).then(
            () => {
              if (
                (!props?.id && selectedRowKeys.length < tagsList.length) ||
                (props?.id && tagsList.length > 1)
              ) {
                loadingGroupsList(
                  dashboardState.current,
                  dashboardState.pageSize,
                  sorterField,
                );
              } else {
                setDashboardState((prevState: TypeDashboardPaginationState) => {
                  return {
                    ...prevState,
                    current: prevState.current - 1,
                  };
                });
              }
              openNotificationSuccess({
                messageTitle: translation.notification.titleDeleted,
                messageDescription:
                  translation.notification.descriptionDeletedGroups,
              });
              setSelectedRowKeys([]);
            },
          );
        }
        break;
      case 'edit':
        setSelectedTag(props.id);
    }
  };
  const cards = getCards(
    assetsList,
    tagsList,
    currentLeftSideBarTab,
    ctActions,
    translation.table.collectiveActionsMessages.deleteSelectedGroupQuestion,
    commonTranslation.confirmText.ok,
    commonTranslation.confirmText.cancel,
  );

  // Todo -------- Работа с карточкой Юзера --------
  const [form] = Form.useForm();

  useEffect(() => {
    if (getSelectedCard)
      form.setFieldsValue({
        name: getSelectedCard.name,
        asset_type: getSelectedCard.asset_type,
        status: getSelectedCard.status,
        ip: getSelectedCard.ip,
        description: getSelectedCard.description,
        model: getSelectedCard.model,
        mac: getSelectedCard.mac,
        ports: getSelectedCard.ports,
        os: getSelectedCard.os?.id,
        manufacturer:
          getSelectedCard.manufacturer?.id ?? getSelectedCard.manufacturer,
        group: getSelectedCard.group?.id,
      });
  }, [form, getSelectedCard]);

  const onFinish = (data: AssetPatchIncoming): void => {
    patchAssetsRecord(getSelectedCard.id, data);
    setDisabledForm(true);
    navigate('/assets');
  };

  const onToggleCardSize = (): void => {
    if (cardSize === 'small') {
      navigate(`/assets/${getSelectedCard.id}`);
      changeCardSize('large');
    }
    if (cardSize === 'large') {
      navigate(`/assets`);
      changeCardSize('small');
    }
  };
  const onValuesChange = (formField: any): void => {};

  const onFinishFailed = (e: any): void => {
    if (e.errorFields.length !== 0)
      openNotificationWithIcon('error', {
        message: translation.notification.pleaseCheckData,
      });
  };

  const handlePostGroupsList = async (values: TypeTags): Promise<void> => {
    try {
      await postGroupsList(values);
      openNotificationSuccess({
        messageTitle:
          commonTranslation.groupsMessages.notification.success.post,
      });
      if (dashboardState.pageSize === tagsList.length) {
        setDashboardState((prevState) => {
          return {
            ...prevState,
            current: prevState.current + 1,
          };
        });
      }
    } catch (e) {
      const err = e as AxiosResponse;
      if (err.status === 400)
        openNotificationError({
          messageTitle: commonTranslation.genericGroupsDashboard.creationError,
          messageDescription:
            commonTranslation.groupsMessages.notification.error.duplicateName,
        });
      else
        openNotificationError({
          messageTitle: commonTranslation.genericGroupsDashboard.creationError,
        });
    }
  };

  const handlePatchGroupsList = async (
    values: TypeTags,
    id: number,
  ): Promise<void> => {
    try {
      await patchGroupsList(values, id);
      openNotificationSuccess({
        messageTitle: commonTranslation.genericGroupsDashboard.updateSuccess,
      });
    } catch (e) {
      if (e) {
        const err = e as AxiosResponse;
        if (err.status === 400)
          openNotificationError({
            messageTitle: commonTranslation.genericGroupsDashboard.updateError,
            messageDescription:
              commonTranslation.groupsMessages.notification.error.duplicateName,
          });
        else
          openNotificationError({
            messageTitle: commonTranslation.genericGroupsDashboard.updateError,
          });
      }
    }
  };

  const onCloseCard = (): void => {
    setSelectedCard(null);
    changeCardSize(undefined);
    setDisabledForm(true);
    navigate(`/assets`);
  };

  const currentAction = useMemo((): TypeActionButtonsConfig[] | null => {
    const action = collectionButtonForAssetsCollectiveActions(
      collectiveActionsMessages,
      {
        onExports,
        onCollectiveAssetsDelete,
        onCollectiveAssetsChangeStatus,
      },
      hasSelected,
    );
    switch (pathName) {
      case '/assets':
        return [action.exports, action.delete, action.changeStatus];
      default:
        return null;
    }
  }, [collectiveActionsMessages, hasSelected, pathName]);

  return (
    <Dashboard
      nameTable={nameTable}
      title={translation.title}
      cards={cards}
      setCheckedColumns={setCheckedColumns}
      getCheckedColumns={getCheckedColumns}
      setSorterField={setSorterField}
      dashboardState={dashboardState}
      columns={columns}
      setSelectedInfoCard={setSelectedCard}
      setSelectedTag={setSelectTag}
      actionsWithCards={useActionsWithSelectedCards(
        pathName === '/assets' ? currentAction : null,
      )}
      onRowEvent={onRowEvent}
      loading={loading}
      onSearch={onSearch}
      leftSideBarContent={useAssetsLeftSideBarContents()}
      filters={null}
      setDisabledForm={setDisabledForm}
      tagDrawer={
        <TagDrawer
          translations={commonTranslation}
          title={
            getSelectedTag?.id
              ? getSelectedTag.name
              : translation.cardInfoFields.createNewGroups
          }
          getSelectedTagId={getSelectedTagId}
          getSelectedTag={getSelectedTag}
          setSelectedTag={setSelectedTag}
          postGroupsList={handlePostGroupsList}
          patchGroupsList={handlePatchGroupsList}
          disabled={disabledForm}
          setDisabled={setDisabledForm}
        />
      }
      rowSelection={pathName === '/assets' ? rowSelection : null}
      changeRowCount={changeRowCount}
      hasSelected={hasSelected}
      pageState={dashboardState}
      addRecordAction={addGroupRecord}
      cardInfoComponent={
        <CardInfoDrawer
          title={
            getSelectedCard?.id
              ? getSelectedCard.name
              : translation.cardInfoFields.createNewAsset
          }
          updated={getSelectedCard?.updated}
          loading={loadingCard}
          formProps={form}
          cardSize={cardSize}
          disabled={disabledForm}
          setDisabled={setDisabledForm}
          onToggleCardSize={onToggleCardSize}
          onCloseCard={onCloseCard}
        >
          {cardSize === 'large' ? (
            <AssetCardInfoLargeForm
              manufacturersList={manufacturersList}
              form={form}
              onFinish={onFinish}
              osList={osList}
              tagsList={tagsList}
              postOsList={postOsList}
              disabled={disabledForm}
              onFinishFailed={onFinishFailed}
            />
          ) : (
            <AssetCardInfoForm
              manufacturersList={manufacturersList}
              form={form}
              onFinish={onFinish}
              osList={osList}
              tagsList={tagsList}
              postOsList={postOsList}
              disabled={disabledForm}
              onValuesChange={onValuesChange}
              onFinishFailed={onFinishFailed}
            />
          )}
        </CardInfoDrawer>
      }
    />
  );
});
