import React, { useEffect, useState } from 'react';
import { useDispatch } from 'react-redux';
import { useRouter } from 'next/router';

import {
  // demand pages
  DEMAND_ACCOUNT_PAGE_CONFIG,
  DEMAND_ACCOUNT_PAGE_PATHNAME,
  DEMAND_ADVERTISER_PAGE_CHANGE_AD_FEE_MODAL,
  DEMAND_ADVERTISER_PAGE_CHANGE_VIEWABILITY_THRESHOLD_MODAL,
  DEMAND_ADVERTISER_PAGE_CONFIG,
  DEMAND_ADVERTISER_PAGE_PATHNAME,
  DEMAND_TAG_PAGE_ADD_SUPPLY_TAG_MODAL,
  DEMAND_TAG_PAGE_CONFIG,
  DEMAND_TAG_PAGE_TYPE_VALUES,
  // pages
  // supply pages
  SUPPLY_ACCOUNT_PAGE_CONFIG,
  SUPPLY_ACCOUNT_PAGE_PATHNAME,
  SUPPLY_SITE_PAGE_CHANGE_EXPENSES_MODAL,
  SUPPLY_SITE_PAGE_CHANGE_REV_SHARE_MODAL,
  SUPPLY_SITE_PAGE_CONFIG,
  SUPPLY_SITE_PAGE_PATHNAME,
  SUPPLY_TAG_PAGE_ADD_DEMAND_TAG_MODAL,
  SUPPLY_TAG_PAGE_CHANGE_TIER_MODAL,
  SUPPLY_TAG_PAGE_CONFIG,
  TIERS,
} from '../constants';

import { validateTextfieldDigits } from '../helpers/validate';
import {
  bulkUpdateDemandTagAction,
  bulkUpdateSupplyTagAction,
  createAdvertiserAction,
  createDemandTagAction,
  createSupplyTagAction,
  deleteWaterfallAction,
  duplicateDemandTagAction,
  duplicateSupplyTagAction,
  initializeAdvertiserFormDataAction,
  initializeDemandFormDataAction,
  initializeSupplyFormDataAction,
  openModalAction,
  resetDemandFormAction,
  resetSupplyFormAction,
  showConfirmModalAction,
  updateAdvertiserAction,
  updateDemandTagAction,
  updateSupplyTagAction,
  updateWaterfallAction,
  validateAdvertiserAction,
  validateTagAction,
} from '../redux/slices';
import { showNotificationAction } from '@/modules/layout/redux/slices';
import {
  getAdvertiserLink,
  getDemandTagLink,
  getSiteLink,
  getSupplyTagLink,
} from '@/modules/marketplace/common/helpers/supplyDemandTransitionLinks';

import CopyCell from '../../common/Cells/CopyCell';
import StatusCell from '../../common/Cells/StatusCell';
import IdCell from './Cells/IdCell';
import NameCell from './Cells/NameCell';
import TargetingCell from './Cells/TargetingCell';
import TextFieldCell from './Cells/TextFieldCell';
import TierCell from './Cells/TierCell';

function usePageConfig(params) {
  const isAdminMP = params?.isAdminMP;
  const router = useRouter();
  const [accountId, , siteAdvertiserId, , tagId] = router.query.params;
  const dispatch = useDispatch();

  const definePage = () => {
    const queries = router.query;
    const isSupplyPages = router.pathname.includes(SUPPLY_ACCOUNT_PAGE_PATHNAME);
    const isDemandPages = router.pathname.includes(DEMAND_ACCOUNT_PAGE_PATHNAME);

    const isDuplicate = 'duplicate' in queries;

    // supply pages
    if (isSupplyPages && accountId && siteAdvertiserId && tagId) {
      // specific supply tag page
      return {
        ...SUPPLY_TAG_PAGE_CONFIG,
        // redefine config for Self Serve
        ...(!isAdminMP ? SUPPLY_TAG_PAGE_CONFIG.selfServeConfig : {}),
        defaultConfig: {
          ...SUPPLY_TAG_PAGE_CONFIG.defaultConfig,
          // redefine config for Self Serve
          ...(!isAdminMP ? SUPPLY_TAG_PAGE_CONFIG.selfServeConfig?.defaultConfig : {}),
          activeTabIndex: tagId === 'new' || isDuplicate ? 1 : 0,
        },
        isCreatingNew: tagId === 'new',
        cellRenderer: {
          id: (props) => (
            <IdCell {...props} showNotification={(notification) => dispatch(showNotificationAction(notification))} />
          ),
          [['name', 'dtPriority']]: (props) => <NameCell {...props} />,
          tier: (props) => (
            <TierCell
              options={TIERS}
              onChange={({ value, id }) => {
                dispatch(
                  updateWaterfallAction({
                    tier: value,
                    supplyIds: [tagId],
                    demandIds: [id],
                  }),
                );
              }}
              {...props}
            />
          ),
          priority: (values) => (
            <TextFieldCell
              validate={(value) => validateTextfieldDigits({ value, min: 0, max: 100 })}
              onChange={({ value, id }) => {
                dispatch(
                  updateWaterfallAction({
                    priority: value,
                    supplyIds: [tagId],
                    demandIds: [id],
                  }),
                );
              }}
              disabled={values?.row?.type === DEMAND_TAG_PAGE_TYPE_VALUES.hb}
              {...values}
            />
          ),
          [[
            'include',
            'exclude',
            'frequency',
            'advertiserInclude',
            'advertiserExclude',
            'waterfallSkip',
            'viewabilityThreshold',
            'kvTargeting',
          ]]: (props) => <TargetingCell {...props} />,
          status: (props) => <StatusCell {...props} />,
        },
        id: tagId,
        plusButton: {
          label: 'Demand Tag',
          onClick: () => {
            dispatch(openModalAction({ id: SUPPLY_TAG_PAGE_ADD_DEMAND_TAG_MODAL }));
          },
        },
        bulkActions: [
          ...(isAdminMP
            ? [
                {
                  label: 'Change Tier',
                  onClick: ({ selected }) => {
                    if (selected?.length) {
                      dispatch(
                        openModalAction({
                          id: SUPPLY_TAG_PAGE_CHANGE_TIER_MODAL,
                          demandIds: selected,
                          supplyIds: [tagId],
                        }),
                      );
                    }
                  },
                },
              ]
            : []),
          {
            label: 'Remove',
            onClick: ({ selected }) => {
              if (selected?.length) {
                dispatch(
                  deleteWaterfallAction({
                    demandIds: selected.filter((item) => item),
                    supplyIds: [tagId],
                  }),
                );
              }
            },
          },
        ],
        breadcrumbs: isAdminMP
          ? [
              { label: 'Supply Accounts', link: SUPPLY_ACCOUNT_PAGE_PATHNAME },
              {
                label: queries?.accountName,
                link: `${SUPPLY_ACCOUNT_PAGE_PATHNAME}/${accountId}?accountName=${queries?.accountName}`,
              },
              {
                label: queries?.siteName,

                link: `${SUPPLY_ACCOUNT_PAGE_PATHNAME}/${accountId}${SUPPLY_SITE_PAGE_PATHNAME}/${siteAdvertiserId}?accountName=${queries?.accountName}&siteName=${queries?.siteName}`,
              },
              { label: queries?.tagName },
            ]
          : [
              { label: 'Sites', link: SUPPLY_ACCOUNT_PAGE_PATHNAME },
              {
                label: queries?.siteName,

                link: `${SUPPLY_ACCOUNT_PAGE_PATHNAME}/${accountId}${SUPPLY_SITE_PAGE_PATHNAME}/${siteAdvertiserId}?accountName=${queries?.accountName}&siteName=${queries?.siteName}`,
              },
              { label: queries?.tagName },
            ],
        supplyAccount: {
          id: accountId,
          name: queries?.accountName,
          accountType: queries?.accountType,
        },
        site: {
          id: siteAdvertiserId,
          name: queries?.siteName,
        },
        upsertAction: () => {
          const actions = [
            {
              action: createSupplyTagAction,
              isActive: tagId === 'new',
            },
            {
              action: updateSupplyTagAction,
              isActive: tagId !== 'new' && !isDuplicate,
            },
            {
              action: duplicateSupplyTagAction,
              isActive: isDuplicate,
            },
          ];

          const selected = actions.find((action) => action.isActive);

          if (selected) {
            dispatch(validateTagAction(selected.action));
          }
        },
        getNewLink: (tag, duplicate = isDuplicate) => getSupplyTagLink(tag, duplicate),
        cancelAction: (tag) => {
          const actions = [
            {
              action: () => router.back(),
              isActive: tagId === 'new',
            },
            {
              action: () => {
                dispatch(resetSupplyFormAction());
                dispatch(initializeSupplyFormDataAction());
              },
              isActive: tagId !== 'new' && !isDuplicate,
            },
            {
              action: () => {
                const link = getSupplyTagLink(tag);
                router.push(link);
              },
              isActive: isDuplicate,
            },
          ];

          const selected = actions.find((action) => action.isActive);

          if (selected) {
            selected.action();
          }
        },
        getTableTagLink: (tag) => getDemandTagLink(tag),
        isDuplicate,
      };
    }
    if (isSupplyPages && accountId && siteAdvertiserId) {
      // specific site page
      return {
        ...SUPPLY_SITE_PAGE_CONFIG,
        // redefine config for Self Serve
        ...(!isAdminMP ? SUPPLY_SITE_PAGE_CONFIG.selfServeConfig : {}),
        defaultConfig: {
          ...SUPPLY_SITE_PAGE_CONFIG.defaultConfig,
          // redefine config for Self Serve
          ...(!isAdminMP ? SUPPLY_SITE_PAGE_CONFIG.selfServeConfig?.defaultConfig : {}),
        },
        id: siteAdvertiserId,
        cellRenderer: {
          id: (props) => (
            <IdCell {...props} showNotification={(notification) => dispatch(showNotificationAction(notification))} />
          ),
          name: (props) => <NameCell {...props} />,
          status: (props) => <StatusCell {...props} />,
          copy: (props) => <CopyCell {...props} buildCopyLinkFunction={getSupplyTagLink} />,
        },
        bulkActions: [
          {
            label: 'Activate',
            onClick: ({ selected }) => {
              const tags = selected.map((item) => ({ id: item, status: 'ACTIVE' }));
              dispatch(bulkUpdateSupplyTagAction({ tags }));
            },
          },
          {
            label: 'Disable',
            onClick: ({ selected }) => {
              const tags = selected.map((item) => ({ id: item, status: 'DISABLED' }));
              dispatch(bulkUpdateSupplyTagAction({ tags }));
            },
          },
          ...(isAdminMP
            ? [
                {
                  label: 'Update Rev-Share',
                  onClick: ({ selected }) => {
                    if (selected?.length) {
                      dispatch(
                        openModalAction({
                          id: SUPPLY_SITE_PAGE_CHANGE_REV_SHARE_MODAL,
                          supplyIds: selected,
                        }),
                      );
                    }
                  },
                },
              ]
            : []),
          ...(isAdminMP
            ? [
                {
                  label: 'Update Expenses',
                  onClick: ({ selected }) => {
                    if (selected?.length) {
                      dispatch(
                        openModalAction({
                          id: SUPPLY_SITE_PAGE_CHANGE_EXPENSES_MODAL,
                          supplyIds: selected,
                        }),
                      );
                    }
                  },
                },
              ]
            : []),
        ],
        plusButton: isAdminMP
          ? {
              label: 'Supply Tag',
              onClick: ({ queries: additionalQueries = {} }) => {
                router.push({
                  pathname: `${router.pathname}/tags/new`,
                  query: {
                    ...router.query,
                    ...additionalQueries,
                  },
                });
              },
            }
          : null,
        getNewLink: (info) => getSiteLink(info),
        breadcrumbs: isAdminMP
          ? [
              {
                label: 'Supply Accounts',
                link: SUPPLY_ACCOUNT_PAGE_PATHNAME,
              },
              {
                label: queries?.accountName,
                link: `${SUPPLY_ACCOUNT_PAGE_PATHNAME}/${accountId}?accountName=${queries?.accountName}`,
              },
              { label: queries?.siteName },
            ]
          : [
              {
                label: 'Sites',
                link: SUPPLY_ACCOUNT_PAGE_PATHNAME,
              },
              { label: queries?.siteName },
            ],
      };
    }
    if (isSupplyPages && accountId) {
      // specific supply account page
      return {
        ...SUPPLY_ACCOUNT_PAGE_CONFIG,
        ...(!isAdminMP ? SUPPLY_ACCOUNT_PAGE_CONFIG.selfServeConfig : {}),
        id: accountId,
        cellRenderer: {
          id: (props) => (
            <IdCell {...props} showNotification={(notification) => dispatch(showNotificationAction(notification))} />
          ),
          name: (props) => <NameCell {...props} />,
        },
        breadcrumbs: [
          { label: 'Supply Accounts', link: SUPPLY_ACCOUNT_PAGE_PATHNAME },
          { label: queries?.accountName },
        ],
      };
    }

    if (isDemandPages && tagId && accountId && siteAdvertiserId) {
      // specific demand tag page
      return {
        ...DEMAND_TAG_PAGE_CONFIG,
        // redefine config for Self Serve
        ...(!isAdminMP ? DEMAND_TAG_PAGE_CONFIG.selfServeConfig : {}),
        defaultConfig: {
          ...DEMAND_TAG_PAGE_CONFIG.defaultConfig,
          // redefine config for Self Serve
          ...(!isAdminMP ? DEMAND_TAG_PAGE_CONFIG.selfServeConfig?.defaultConfig : {}),
          activeTabIndex: tagId === 'new' || isDuplicate ? 1 : 0,
        },
        isCreatingNew: tagId === 'new',
        id: tagId,
        demandAccount: {
          id: accountId,
          name: queries?.accountName,
          publisherDemand:
            queries?.publisherDemand === 'true' || queries?.publisherDemand === 'false'
              ? JSON.parse(queries.publisherDemand)
              : null,
        },
        advertiser: {
          id: siteAdvertiserId,
          name: queries?.advertiserName,
          tier: queries?.advertiserTier,
        },
        cellRenderer: {
          id: (props) => (
            <IdCell {...props} showNotification={(notification) => dispatch(showNotificationAction(notification))} />
          ),
          name: (props) => <NameCell {...props} />,
          status: (props) => <StatusCell {...props} />,
        },
        plusButton: {
          label: 'Supply Tag',
          onClick: () => {
            dispatch(openModalAction({ id: DEMAND_TAG_PAGE_ADD_SUPPLY_TAG_MODAL }));
          },
        },
        bulkActions: [
          {
            label: 'Remove',
            onClick: ({ selected }) => {
              if (selected?.length) {
                dispatch(
                  deleteWaterfallAction({
                    demandIds: [tagId],
                    supplyIds: selected,
                  }),
                );
              }
            },
          },
        ],
        breadcrumbs: isAdminMP
          ? [
              { label: 'Demand Accounts', link: DEMAND_ACCOUNT_PAGE_PATHNAME },
              {
                label: queries?.accountName,
                link: `${DEMAND_ACCOUNT_PAGE_PATHNAME}/${accountId}?accountName=${queries?.accountName}`,
              },
              {
                label: queries?.advertiserName,

                link: `${DEMAND_ACCOUNT_PAGE_PATHNAME}/${accountId}${DEMAND_ADVERTISER_PAGE_PATHNAME}/${siteAdvertiserId}?accountName=${queries?.accountName}&advertiserName=${queries?.advertiserName}`,
              },
              { label: queries?.tagName },
            ]
          : [
              { label: 'Advertisers', link: DEMAND_ACCOUNT_PAGE_PATHNAME },
              {
                label: queries?.advertiserName,

                link: `${DEMAND_ACCOUNT_PAGE_PATHNAME}/${accountId}${DEMAND_ADVERTISER_PAGE_PATHNAME}/${siteAdvertiserId}?accountName=${queries?.accountName}&advertiserName=${queries?.advertiserName}`,
              },
              { label: queries?.tagName },
            ],
        upsertAction: () => {
          const actions = [
            {
              action: createDemandTagAction,
              isActive: tagId === 'new',
            },
            {
              action: isAdminMP ? updateDemandTagAction : showConfirmModalAction,
              isActive: tagId !== 'new' && !isDuplicate,
            },
            {
              action: duplicateDemandTagAction,
              isActive: tagId !== 'new' && isDuplicate,
            },
          ];

          const selected = actions.find((action) => action.isActive);

          if (selected) {
            dispatch(validateTagAction(selected.action));
          }
        },
        cancelAction: (tag) => {
          const actions = [
            {
              action: () => router.back(),
              isActive: tagId === 'new',
            },
            {
              action: () => {
                dispatch(resetDemandFormAction());
                dispatch(initializeDemandFormDataAction());
              },
              isActive: tagId !== 'new' && !isDuplicate,
            },
            {
              action: () => {
                const link = getDemandTagLink(tag);
                router.push(link);
              },
              isActive: isDuplicate,
            },
          ];

          const selected = actions.find((action) => action.isActive);

          if (selected) {
            selected.action();
          }
        },
        getTableTagLink: (tag) => getSupplyTagLink(tag),
        getNewLink: (tag, duplicate = isDuplicate) => getDemandTagLink(tag, duplicate),
        isDuplicate,
      };
    }
    if (isDemandPages && accountId && siteAdvertiserId) {
      // specific demand advertiser page
      return {
        ...DEMAND_ADVERTISER_PAGE_CONFIG,
        // redefine config for Self Serve
        ...(!isAdminMP ? DEMAND_ADVERTISER_PAGE_CONFIG.selfServeConfig : {}),
        defaultConfig: {
          ...DEMAND_ADVERTISER_PAGE_CONFIG.defaultConfig,
          // redefine config for Self Serve
          ...(!isAdminMP ? DEMAND_ADVERTISER_PAGE_CONFIG.selfServeConfig?.defaultConfig : {}),
          activeTabIndex: siteAdvertiserId === 'new' || isDuplicate ? 1 : 0,
        },
        cellRenderer: {
          id: (props) => (
            <IdCell {...props} showNotification={(notification) => dispatch(showNotificationAction(notification))} />
          ),
          name: (props) => <NameCell {...props} />,
          [[
            'include',
            'exclude',
            'frequency',
            'advertiserInclude',
            'advertiserExclude',
            'waterfallSkip',
            'viewabilityThreshold',
            'kvTargeting',
          ]]: (props) => <TargetingCell {...props} />,
          copy: (props) => <CopyCell {...props} buildCopyLinkFunction={getDemandTagLink} />,
        },
        bulkActions: [
          {
            label: 'Activate',
            onClick: ({ selected }) => {
              const tags = selected.map((item) => ({ id: item, status: 'ACTIVE' }));
              dispatch(bulkUpdateDemandTagAction({ tags }));
            },
          },
          {
            label: 'Disable',
            onClick: ({ selected }) => {
              const tags = selected.map((item) => ({ id: item, status: 'DISABLED' }));
              dispatch(bulkUpdateDemandTagAction({ tags }));
            },
          },
          {
            label: 'Update Viewability Threshold',
            onClick: ({ selected }) => {
              if (selected?.length) {
                dispatch(
                  openModalAction({
                    id: DEMAND_ADVERTISER_PAGE_CHANGE_VIEWABILITY_THRESHOLD_MODAL,
                    demandIds: selected,
                  }),
                );
              }
            },
          },
          ...(isAdminMP
            ? [
                {
                  label: 'Update Additional Fees',
                  onClick: ({ selected }) => {
                    if (selected?.length) {
                      dispatch(
                        openModalAction({
                          id: DEMAND_ADVERTISER_PAGE_CHANGE_AD_FEE_MODAL,
                          demandIds: selected,
                        }),
                      );
                    }
                  },
                },
              ]
            : []),
        ],
        plusButton: {
          label: 'Demand Tag',
          onClick: ({ queries: additionalQueries = {} }) => {
            router.push({
              pathname: `${router.pathname}/tags/new`,
              query: {
                ...router.query,
                ...additionalQueries,
              },
            });
          },
        },
        isCreatingNew: siteAdvertiserId === 'new',
        id: siteAdvertiserId,
        getNewLink: (info) => getAdvertiserLink(info),
        breadcrumbs: isAdminMP
          ? [
              { label: 'Demand Accounts', link: DEMAND_ACCOUNT_PAGE_PATHNAME },
              {
                label: queries?.accountName,
                link: `${DEMAND_ACCOUNT_PAGE_PATHNAME}/${accountId}?accountName=${queries?.accountName}`,
              },
              { label: queries?.advertiserName },
            ]
          : [{ label: 'Advertisers', link: DEMAND_ACCOUNT_PAGE_PATHNAME }, { label: queries?.advertiserName }],
        upsertAction: () => {
          const actions = [
            {
              action: createAdvertiserAction,
              isActive: siteAdvertiserId === 'new',
            },
            {
              action: updateAdvertiserAction,
              isActive: siteAdvertiserId !== 'new',
            },
          ];

          const selected = actions.find((action) => action.isActive);

          if (selected) {
            dispatch(validateAdvertiserAction(selected.action));
          }
        },
        cancelAction: () => {
          const actions = [
            {
              action: () => router.back(),
              isActive: siteAdvertiserId === 'new',
            },
            {
              action: () => {
                dispatch(initializeAdvertiserFormDataAction());
              },
              isActive: siteAdvertiserId !== 'new',
            },
          ];

          const selected = actions.find((action) => action.isActive);

          if (selected) {
            selected.action();
          }
        },
        disableDuplicate: true,
      };
    }
    if (isDemandPages && accountId) {
      // specific demand account page
      return {
        ...DEMAND_ACCOUNT_PAGE_CONFIG,
        id: accountId,
        cellRenderer: {
          id: (props) => (
            <IdCell {...props} showNotification={(notification) => dispatch(showNotificationAction(notification))} />
          ),
          name: (props) => <NameCell {...props} />,
        },
        breadcrumbs: [
          { label: 'Demand Accounts', link: DEMAND_ACCOUNT_PAGE_PATHNAME },
          { label: queries?.accountName },
        ],
      };
    }

    return null;
  };

  const [result, setResult] = useState(definePage());

  useEffect(() => {
    setResult(definePage());
  }, [router.pathname, router.query]);

  return result;
}

export default usePageConfig;
