import { Fragment, useCallback, useMemo, useState } from 'react';

import { Container } from '@cleartrip/ct-design-container';
import { Typography, TypographyColorType } from '@cleartrip/ct-design-typography';
import { AlertCallout } from '@cleartrip/ct-design-alert-callout';
import { Segment, IOption } from '@cleartrip/ct-design-segment';
import { isEmpty } from '@cleartrip/ct-design-common-utils';

import { CouponSection } from './CouponSection';
import { GVSection } from './GVSection';
import { ICouponAndGv } from './type';
import { CALLOUT_TYPORAPHY_COLOR } from './constants';
import { couponAndGvStaticStyles } from './style';

const CouponAndGv: React.FC<ICouponAndGv> = ({ heading, activeTabId, gv, coupon, discountCallout, onTabChange }) => {
  const [activeTab, setActiveTab] = useState<string | number>(activeTabId || '');

  const {
    text: discountCalloutText,
    prefixIcon: discountCalloutPrefixIcon,
    variant: discountCalloutVariant = CALLOUT_TYPORAPHY_COLOR.success,
  } = discountCallout || {};

  const { tabId: couponTabId, tabTitle: couponTabTitle } = coupon || {};
  const { tabId: gvTabId, tabTitle: gvTabTitle } = gv || {};

  const segmentOptions = useMemo(() => {
    const options = [
      { text: couponTabTitle, tabId: couponTabId },
      { text: gvTabTitle, tabId: gvTabId },
    ] as IOption[];

    return options;
  }, [couponTabTitle, couponTabId, gvTabTitle, gvTabId]);

  const onTabClick = useCallback(
    (tabId: string | number) => {
      setActiveTab(tabId);
      onTabChange?.(tabId);
    },
    [onTabChange],
  );

  return (
    <Fragment>
      {!isEmpty(heading) && (
        <Container styleConfig={{ root: [couponAndGvStaticStyles.headingContainer] }}>
          <Typography variant='HM2'>{heading}</Typography>
        </Container>
      )}
      {!isEmpty(discountCallout) && (
        <AlertCallout
          textNode={
            <Typography variant='B2' color={CALLOUT_TYPORAPHY_COLOR[discountCalloutVariant] as TypographyColorType}>
              {discountCalloutText}
            </Typography>
          }
          variant={discountCalloutVariant as keyof typeof CALLOUT_TYPORAPHY_COLOR}
          prefixIconNode={discountCalloutPrefixIcon}
          styleConfig={{ root: [couponAndGvStaticStyles.discountCallout] }}
        />
      )}
      {!isEmpty(coupon) && !isEmpty(gv) && (
        <Container styleConfig={{ root: [couponAndGvStaticStyles.segmentContainer] }}>
          <Segment
            block
            activeTabId={activeTab as string}
            options={segmentOptions}
            onChange={onTabClick}
            animationDuration={500}
          />
        </Container>
      )}
      {/* @ts-ignore */}
      {activeTab === couponTabId && <CouponSection {...coupon} />}
      {activeTab === gvTabId && <GVSection {...gv} />}
    </Fragment>
  );
};

export default CouponAndGv;
