import React, { useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import dayjs from 'dayjs';
import { Add } from '@mui/icons-material';

import { DEMAND_TAG_PRICING_TYPE } from '@/modules/marketplace/account/constants';

import * as selectors from '../../../../redux/selectors';
import * as actions from '../../../../redux/slices';
import useLocalPagination from '@/modules/marketplace/account/helpers/useLocalPagination';
import { parseNumberWithRound } from '@/modules/marketplace/common/helpers';

import { Form, FormContent, FormRow, FormSection } from '@/modules/@common/Form';
import PricingFormLineItem from '../../../DemandSettings/components/PricingTab/components/FormLineItem';
import PricingLineItem from '../../../DemandSettings/components/PricingTab/components/LineItem';
import { Button, Stack, TablePagination } from '@/mui/components';

function AdvertiserPricingTab() {
  const dispatch = useDispatch();

  const advertiserSettings = useSelector(selectors.advertiserSettingsSelector);
  const { revShare } = advertiserSettings;

  const pageConfig = useSelector(selectors.pageConfigSelector);
  const isCreatingNew = pageConfig?.isCreatingNew;
  const isDuplicate = pageConfig?.isDuplicate;

  const [showNewRevShareForm, toggleNewRevShareForm] = useState(false);
  const paginationRevShare = useLocalPagination(25, 1);

  const onAddNewPrice = (key, data) => {
    const state = advertiserSettings[key];
    if (isCreatingNew || isDuplicate) {
      dispatch(
        actions.setAdvertiserSettingsTabAction({
          [key]: [
            {
              id: `${state.length}`,
              ...data,
            },
            ...state,
          ],
        }),
      );
    } else {
      // update with server
      dispatch(
        actions.updateAdvertiserAction({
          revShare: data,
        }),
      );
    }
  };

  const onEditPrice = (key, data) => {
    dispatch(
      actions.setAdvertiserSettingsTabAction({
        [key]: advertiserSettings[key]?.map((i) => (i.id === data.id ? { ...data } : i)),
      }),
    );
  };

  const onDeletePrice = (key, id) => {
    dispatch(
      actions.setAdvertiserSettingsTabAction({
        [key]: advertiserSettings[key]?.filter((i) => i.id !== id),
      }),
    );
  };

  return (
    <Form>
      <FormContent>
        <FormSection>
          <FormRow
            label="Buyer Rev-Share Fee:"
            tooltip="This line item represents the revenue share fee deducted by the buyer or demand partner from the clearing price. It should only be applied when the RPM rate reported to AnyClip reflects gross revenue. The value entered here should indicate the portion of the fee retained by the buyer/demand partner. Please note: Gross revenue generated by this demand partner will be displayed after the deduction of this rev-share fee, and these figures will not be reflected in the Marketplace tables."
            fullWidth
            justifyContent="flex-end"
          >
            {!!revShare.length && !isDuplicate && (
              <Button
                size="small"
                onClick={() => {
                  if (!isCreatingNew) {
                    paginationRevShare.setCurrentPage(1);
                  }
                  toggleNewRevShareForm(true);
                }}
                data-id="add-new-line-item"
                startIcon={<Add />}
                disabled={showNewRevShareForm || (isCreatingNew && revShare.length === 1)}
              >
                New
              </Button>
            )}
            {!revShare.length && !showNewRevShareForm && (
              <Button
                size="small"
                onClick={() => {
                  toggleNewRevShareForm(true);
                }}
                data-id="add-new-line-item"
                startIcon={<Add />}
              >
                Add Rev-Share Fee
              </Button>
            )}
          </FormRow>
          <FormRow fullWidth>
            <Stack fullWidth>
              <PricingLineItem
                id="title"
                rate="Rev-Share fee %"
                startDate="Start Date"
                endDate="End Date"
                updatedBy="Updated By"
                itemType={DEMAND_TAG_PRICING_TYPE.fee}
                isLabelRow
              />
              {showNewRevShareForm && (
                <PricingFormLineItem
                  isCreatingNew={isCreatingNew}
                  isEditableEndDate
                  itemType={DEMAND_TAG_PRICING_TYPE.fee}
                  prevStartDate={revShare[0] ? revShare[0].startDate : 0}
                  onSubmit={(data) => {
                    toggleNewRevShareForm(false);
                    onAddNewPrice('revShare', {
                      ...data,
                      value: parseNumberWithRound(data.rate / 100),
                    });
                  }}
                  onCancel={() => {
                    toggleNewRevShareForm(false);
                  }}
                />
              )}
              {revShare.slice(paginationRevShare.startIndex, paginationRevShare.endIndex).map((item, index) => {
                const canUpdateEndDate =
                  paginationRevShare.currentPage === 1 &&
                  index === 0 &&
                  ((item.endDate && dayjs(item.endDate).isAfter(new Date().getTime())) || !item.endDate);
                // only the last one can be edited and fee end date > current time
                // cannot be edited if fee is already closed
                return (
                  <PricingLineItem
                    key={item.startDate}
                    id={item.id}
                    rate={parseNumberWithRound(item.value * 100)}
                    startDate={item.startDate}
                    endDate={item.endDate}
                    status={item.status}
                    updatedBy={item.updatedBy}
                    rateMask="[NUMBER]%"
                    isCreatingNew={isCreatingNew}
                    itemType={DEMAND_TAG_PRICING_TYPE.fee}
                    isDuplicating={isDuplicate}
                    canUpdateEndDate={canUpdateEndDate}
                    onSubmit={(data) => {
                      onEditPrice('revShare', {
                        ...data,
                        value: parseNumberWithRound(data.rate / 100),
                      });
                      // updating end date for last fee
                      if (canUpdateEndDate && !isCreatingNew && !isDuplicate) {
                        onAddNewPrice('revShare', {
                          ...data,
                          startDate: null, // server update fee only without startDate
                          rate: null, // server update fee only without value
                        });
                      }
                    }}
                    onDelete={(id) => {
                      onDeletePrice('revShare', id);
                    }}
                  />
                );
              })}
              {!isCreatingNew && !isDuplicate && !!revShare.length && (
                <TablePagination
                  component="div"
                  rowsPerPageOptions={[5, 10, 25]}
                  count={revShare.length}
                  rowsPerPage={paginationRevShare.itemsPerPage}
                  page={paginationRevShare.currentPage}
                  onPageChange={(event, page) => {
                    paginationRevShare.setCurrentPage(page);
                  }}
                  onRowsPerPageChange={(event) => {
                    paginationRevShare.setItemsPerPage(+event.target.value);
                  }}
                />
              )}
            </Stack>
          </FormRow>
        </FormSection>
      </FormContent>
    </Form>
  );
}

export default AdvertiserPricingTab;
