import React, { useMemo } from 'react';

import { ButtonVariant } from '@/components/button/Button';
import SpinnerSVG from '@/components/svg/SpinnerSVG';
import { useUsagePlanDescriptionsResponse } from '@/hooks/usePricing';
import { CloseIcon } from '@/icons';
import {
  FeatureDescription,
  SubscriptionInfo,
  UsagePlanDescription,
} from '@/state/sessionStore';

import { ModalButton } from '../../shared/ModalButton';

interface Props {
  currentSubscription: SubscriptionInfo;
  isCancelLoading: boolean;
  onKeep: () => void;
  onConfirmCancel: () => void;
  customMessage?: string | null;
}

const getFeatureDescriptions = (
  descriptions: Record<string, UsagePlanDescription>,
  planKey: string | undefined,
  limit: number = 5
): FeatureDescription[] => {
  if (!planKey || !descriptions) return [];

  const planDescription = descriptions[planKey];
  if (!planDescription?.feature_descriptions) return [];

  return planDescription.feature_descriptions.slice(0, limit);
};

const CancelConfirmStep: React.FC<Props> = ({
  currentSubscription,
  isCancelLoading,
  onKeep,
  onConfirmCancel,
  customMessage,
}) => {
  const { data: descriptionsResponse } = useUsagePlanDescriptionsResponse();
  const usagePlanDescriptions = descriptionsResponse?.usage_plan_descriptions;
  const features = useMemo(
    () =>
      getFeatureDescriptions(
        usagePlanDescriptions || {},
        currentSubscription?.plan?.plan_key
      ),
    [usagePlanDescriptions, currentSubscription?.plan?.plan_key]
  );

  return (
    <div>
      {!customMessage && (
        <p className='mb-4 text-white/80'>
          Your subscription will be canceled at the end of the current billing
          period. Afterward, you will lose:
        </p>
      )}

      <div className='mb-6 flex flex-col gap-3 rounded-3xl bg-white/10 p-4 text-left'>
        {customMessage ? (
          <p className='text-white/80'>{customMessage}</p>
        ) : (
          <>
            {features.map((feature, index) => (
              <div key={index} className='flex items-start space-x-2'>
                <span className='mt-[3px] flex h-4 w-4 items-center justify-center rounded-full border border-white/15 bg-white/4'>
                  <CloseIcon className='h-3 w-3 text-accent-error' />
                </span>
                <span>{feature.text}</span>
              </div>
            ))}
          </>
        )}
      </div>

      <div className='flex justify-center gap-3'>
        <ModalButton variant={ButtonVariant.Secondary} onClick={onKeep}>
          Back
        </ModalButton>
        <ModalButton
          variant={ButtonVariant.Primary}
          onClick={onConfirmCancel}
          disabled={isCancelLoading}
          icon={isCancelLoading ? <SpinnerSVG className='fill-black' /> : null}
        >
          {isCancelLoading ? 'Confirming...' : 'Confirm Cancellation'}
        </ModalButton>
      </div>
    </div>
  );
};

export default CancelConfirmStep;
