import { useStyles } from './styles/planDetailsStyles';
import { useEffect, useMemo, useState } from 'react';
import {
  FEATURES,
  NOTIFICATION,
  PLAN_STATUS_TYPE,
  SUBSCRIPTIONS_WARNING_LIMIT_IN_PERCENTAGE,
} from '../../../constants';
import SimpleDataTable from '../../../components/SimpleDataTable';
import { Box, Chip, Typography } from '@mui/material';
import CircleIcon from '@mui/icons-material/Circle';
import FormSectionHeading from '../../../components/FormSectionHeading';
import { LoadingButton } from '@mui/lab';
import { differenceInDays, format } from 'date-fns';
import { updateCompanyCustomPlanStatus } from '../../../services/plan.services';
import { pushNotification } from '../../../utils/notification';
import CustomModal from '../../Modal/Modal';
import OfflinePaymentForm from '../../../components/OfflinePaymentForm';

const PlanDetails = ({ companyData, reFetchData }) => {
  const classes = useStyles();
  const [isStatusUpdateLoading, setIsStatusUpdateLoading] = useState(false);
  const [lastPlanRows, setLastPlanRows] = useState([]);
  const [planHistoryRows, setPlanHistoryRows] = useState([]);
  const [topUpPlanRows, setTopUpPlanRows] = useState([]);
  const [
    showTopUpPlanOfflinePaymentModel,
    setShowTopUpPlanOfflinePaymentModel,
  ] = useState(false);

  useEffect(() => {
    setTopUpPlanRows(
      companyData?.hasActivePlan ? [companyData?.hasActivePlan] : []
    );
    setLastPlanRows(companyData?.accounts ? [companyData?.accounts] : []);
    setPlanHistoryRows(
      companyData?.planHistory ? companyData?.planHistory : []
    );
  }, [companyData]);

  const checkValueIsInWarning = (
    firstValues,
    secondValues,
    extraAppendString
  ) => {
    const difference = (firstValues / secondValues) * 100;

    if (firstValues === null || secondValues === null) {
      return (
        <span className={classes.warning}>
          {0} {'/'} {0} remaining
        </span>
      );
    }

    if (firstValues === 0 && secondValues === 0) {
      return (
        <span className={classes.warning}>
          {firstValues} {'/'} {secondValues} remaining
        </span>
      );
    }
    if (firstValues < 0 || secondValues < 0) {
      return (
        <span className={classes.warning}>
          {0} {'/'} {0} {extraAppendString} remaining
        </span>
      );
    }
    if (firstValues === 0 && secondValues > 0) {
      return (
        <span className={classes.success}>
          {firstValues} {'/'} {secondValues} {extraAppendString} remaining
        </span>
      );
    }

    return (
      <>
        <span
          className={
            difference <= SUBSCRIPTIONS_WARNING_LIMIT_IN_PERCENTAGE
              ? classes.warning
              : classes.success
          }
        >
          {firstValues} {'/'} {secondValues} {extraAppendString} remaining
        </span>
      </>
    );
  };

  const lastPlanColumns = useMemo(
    () => [
      {
        header: 'Plan Validity(days)',
        isBold: true,
        Cell: ({ row }) => (
          <div>
            {checkValueIsInWarning(
              differenceInDays(new Date(row?.endTime), new Date()),
              differenceInDays(
                new Date(new Date(row?.endTime).setHours(0, 0, 0, 0)),
                new Date(new Date(row?.startTime).setHours(0, 0, 0, 0))
              ),
              'days'
            )}
          </div>
        ),
      },
      {
        accessorKey: 'maxResumeDownloads',
        header: 'View Resume',
        isBold: true,
        Cell: ({ row }) => (
          <div>
            {checkValueIsInWarning(
              row?.maxResumeDownloads,
              companyData?.totalMaxResumeDownloads
            )}
          </div>
        ),
      },
      {
        accessorKey: 'maxJobPostings',
        header: 'Job Posting',
        isBold: true,
        Cell: ({ row }) => (
          <div>
            {checkValueIsInWarning(
              row?.maxJobPostings,
              companyData?.totalMaxJobPostings
            )}
          </div>
        ),
      },
      {
        accessorKey: 'features',
        header: 'Candidate Search',
        isBold: true,
        Cell: ({ row }) => (
          <div
            className={
              row?.features?.includes(FEATURES.SEARCH_CANDIDATE)
                ? classes.success
                : classes.warning
            }
          >
            {row?.features?.includes(FEATURES.SEARCH_CANDIDATE) ? 'Yes' : 'No'}
          </div>
        ),
      },
    ],
    [classes]
  );

  const planHistoryColumn = useMemo(
    () => [
      {
        header: 'Plan Start And End Date',
        isBold: true,
        Cell: ({ row }) => (
          <div>
            {format(new Date(row?.startTime), 'dd MMM yyyy')} -
            {format(new Date(row?.endTime), 'dd MMM yyyy')}
          </div>
        ),
      },
      {
        header: 'Plan Validity(days)',
        isBold: true,
        Cell: ({ row }) => (
          <div className={classes.success}>
            {differenceInDays(
              new Date(new Date(row?.endTime).setHours(0, 0, 0, 0)),
              new Date(new Date(row?.startTime).setHours(0, 0, 0, 0))
            )}{' '}
            days
          </div>
        ),
      },
      {
        accessorKey: 'maxResumeDownloads',
        isBold: true,
        header: 'View Resume',
        Cell: ({ row }) => (
          <div className={classes.success}>{row?.maxResumeDownloads}</div>
        ),
      },
      {
        accessorKey: 'maxJobPostings',
        header: 'Job Posting',
        isBold: true,
        Cell: ({ row }) => (
          <div className={classes.success}>{row?.maxJobPostings}</div>
        ),
      },
      {
        accessorKey: 'features',
        header: 'Candidate Search',
        isBold: true,
        Cell: ({ row }) => (
          <div className={classes.success}>
            {row?.features?.includes(FEATURES.SEARCH_CANDIDATE) ? 'Yes' : 'No'}
          </div>
        ),
      },
    ],
    [classes]
  );

  const topUpPlanColumns = useMemo(
    () => [
      {
        header: 'Plan Validity(days)',
        isBold: true,
        Cell: ({ row }) => (
          <div className={classes.success}>{row?.validityInDays} days</div>
        ),
      },
      {
        accessorKey: 'maxResumeDownloads',
        isBold: true,
        header: 'View Resume',
        Cell: ({ row }) => (
          <div className={classes.success}>{row?.maxResumeDownloads}</div>
        ),
      },
      {
        accessorKey: 'maxJobPostings',
        header: 'Job Posting',
        isBold: true,
        Cell: ({ row }) => (
          <div className={classes.success}>{row?.maxJobPostings}</div>
        ),
      },
      {
        accessorKey: 'features',
        header: 'Candidate Search',
        isBold: true,
        Cell: ({ row }) => (
          <div className={classes.success}>
            {row?.features?.includes(FEATURES.SEARCH_CANDIDATE) ? 'Yes' : 'No'}
          </div>
        ),
      },
    ],
    [classes]
  );

  const handleTopUpPlanStatusUpdate = async () => {
    try {
      setIsStatusUpdateLoading(true);
      const updateStatus =
        companyData?.hasActivePlan?.status === PLAN_STATUS_TYPE.ACTIVATED
          ? PLAN_STATUS_TYPE.DEACTIVATED
          : PLAN_STATUS_TYPE.ACTIVATED;

      const body = { status: updateStatus };
      const resp = await updateCompanyCustomPlanStatus(
        companyData?.hasActivePlan?.id,
        body
      );

      if (resp?.data?.error) {
        pushNotification(resp?.data?.error, NOTIFICATION.ERROR);
      } else {
        pushNotification(resp?.data?.message, NOTIFICATION.SUCCESS);
      }
    } catch (error) {
      // eslint-disable-next-line no-console
      console.error('Error will status update:', error);
    } finally {
      setIsStatusUpdateLoading(false);
      reFetchData();
    }
  };

  const handleOfflinePayment = () => {
    setShowTopUpPlanOfflinePaymentModel(true);
  };

  const handleModelClose = () => {
    reFetchData();
    setShowTopUpPlanOfflinePaymentModel(false);
  };

  return (
    <Box>
      {companyData?.hasActivePlan?.status !== PLAN_STATUS_TYPE.PURCHASED && (
        <Box className={classes.topUpPlanBox}>
          <Box className={classes.topUpPlanHeadingBox}>
            <Typography className={classes.topUpPlanHeading}>
              {companyData?.planHistory?.length === 0
                ? 'Added Custom Plan'
                : 'Top Up Plan'}
            </Typography>
            {companyData?.hasActivePlan?.status ===
              PLAN_STATUS_TYPE.ACTIVATED && (
              <Chip
                className={classes.topUpPlanPaymentStatusChip}
                label={
                  <span>
                    <CircleIcon className={classes.dotIcon} />
                    Payment Awaited
                  </span>
                }
              />
            )}
          </Box>
          <SimpleDataTable columns={topUpPlanColumns} rows={topUpPlanRows} />
          <Box className={classes.topUpButtonBox} gap={2}>
            {companyData?.hasActivePlan?.status ===
              PLAN_STATUS_TYPE.ACTIVATED && (
              <LoadingButton
                variant="contained"
                color="secondary"
                className={classes.topUpButtonClass}
                onClick={handleTopUpPlanStatusUpdate}
                loading={isStatusUpdateLoading}
              >
                Deactivate Plan
              </LoadingButton>
            )}
            {companyData?.hasActivePlan?.status ===
              PLAN_STATUS_TYPE.DEACTIVATED && (
              <LoadingButton
                variant="contained"
                color="secondary"
                className={classes.reactivateButtonClass}
                onClick={handleTopUpPlanStatusUpdate}
                loading={isStatusUpdateLoading}
              >
                Reactivate Plan
              </LoadingButton>
            )}
            {companyData?.hasActivePlan?.status ===
              PLAN_STATUS_TYPE.ACTIVATED && (
              <LoadingButton
                variant="outlined"
                className={classes.topUpButtonClass}
                onClick={handleOfflinePayment}
              >
                Offline Payment
              </LoadingButton>
            )}
          </Box>
        </Box>
      )}
      {/* ................last plan data table......... */}
      <Box className={classes.lastPlanBox}>
        <FormSectionHeading
          title="LAst PLan"
          className={classes.lastPlanHeading}
        />
        <SimpleDataTable columns={lastPlanColumns} rows={lastPlanRows} />
      </Box>
      <Box className={classes.planHistoryBox}>
        <FormSectionHeading
          title="plan History"
          className={classes.lastPlanHeading}
        />
        <SimpleDataTable columns={planHistoryColumn} rows={planHistoryRows} />
      </Box>
      {showTopUpPlanOfflinePaymentModel && (
        <>
          <CustomModal
            // open={showModel}
            title="Top Up Plan Payment Details"
            isTitleLeft
            // isScrolling
            showCloseButton={true}
            onClose={handleModelClose}
            className={classes.customModel}
            modalBodyFunction={() => (
              <OfflinePaymentForm
                handleModelClose={handleModelClose}
                companyId={companyData?.id}
                planId={companyData?.hasActivePlan?.id}
                isTopUpModel={true}
              />
            )}
          />
        </>
      )}
    </Box>
  );
};

export default PlanDetails;
