import { useMutation } from '@tanstack/react-query';
import { format, parseISO } from 'date-fns';
import { ReactNode, useMemo } from 'react';

import { GlassBanner } from '@/components/GlassBanner/GlassBanner';
import Button, { ButtonShape, ButtonVariant } from '@/components/button/Button';
import { RotateReverseIcon } from '@/icons';
import { useApiClient } from '@/lib/apiClient';
import logWebUserEvent from '@/logging/logWebUserEvent';
import { SubscriptionInfo } from '@/state/sessionStore';
import { SubscriptionPeriod } from '@/utils/session';

import { SUBSCRIPTION_PAGE_VERSIONS } from '../constants';
import { CancelChangesButton } from './modals/CancelChangesFlow';
import CreditsPurchaseModalContent from './modals/CreditsPurchaseModalContent';
import { RenewButton } from './modals/RenewFlow';

export const CurrentSubscription = ({
  sub,
  isMobileSubscription,
  onCancelSubscription,
  showCancelButton,
}: {
  sub: SubscriptionInfo;
  isMobileSubscription: boolean;
  onCancelSubscription?: () => void;
  showCancelButton?: boolean;
}) => {
  const apiClient = useApiClient();

  const getBillingUrl = async (): Promise<{ url: string }> => {
    const { data, error } = await apiClient.POST('/api/billing/create-portal/');
    if (error) {
      throw error;
    }
    return data;
  };

  const mutation = useMutation({
    mutationFn: getBillingUrl,
    onSuccess: (data) => {
      window.location.href = data.url;
    },
  });

  return (
    <div className='flex w-full flex-col gap-3'>
      <GlassBanner>
        <div className='flex w-full flex-col items-center gap-4 max-[1125px]:justify-center min-[1125px]:justify-between md:flex-row md:flex-wrap'>
          <CurrentPlanInfo sub={sub} />
          <div className='flex flex-row justify-center gap-2'>
            {sub.cancel_on ? (
              <RenewButton sub={sub} />
            ) : (
              sub.changing_to && (
                <PlanInfoItem
                  label={`Changing to ${sub.changing_to}`}
                  value={<CancelChangesButton sub={sub} />}
                />
              )
            )}
            {showCancelButton && onCancelSubscription && !sub.cancel_on && (
              <Button
                onClick={() => {
                  logWebUserEvent({
                    actionName: 'SubCancelFlowFeaturesAboutToLoseStepShown',
                    context: {
                      currentPeriod: sub.period || '',
                      currentUsagePlanId: sub?.plan?.id || '',
                      modalStep: 1,
                    },
                  });
                  onCancelSubscription();
                }}
                disabled={isMobileSubscription}
                variant={ButtonVariant.Secondary}
                shape={ButtonShape.Pill}
              >
                Cancel subscription
              </Button>
            )}
            <Button
              onClick={() => {
                logWebUserEvent({
                  actionName: 'EditBillingDetailsButtonClicked',
                  context: {
                    currentUsagePlanId: sub?.plan?.id || '',
                    currentPeriod: sub.period || '',
                    subPageVersion: SUBSCRIPTION_PAGE_VERSIONS.aura,
                  },
                });
                mutation.mutate();
              }}
              disabled={isMobileSubscription}
              variant={ButtonVariant.Secondary}
              shape={ButtonShape.Pill}
            >
              Update payment
            </Button>
            <CreditsPurchaseModalContent
              isDisabled={sub.is_past_due || isMobileSubscription}
            />
          </div>
        </div>
      </GlassBanner>
      {(sub.plan?.plan_key === 'pro_20250501' ||
        sub.plan?.plan_key === 'basic') && (
        <div className='w-full rounded-lg border border-yellow-400/20 bg-yellow-400/10 p-3 text-center font-sans text-sm text-yellow-400/90'>
          Your {sub.plan?.plan_key === 'basic' ? 'Basic' : 'Pro'} tier is no
          longer purchasable. Your subscription will continue to renew until you
          choose to change tiers or cancel.
        </div>
      )}
      <div className='w-full text-center font-sans text-xs text-white/30'>
        Need help? For support, issues with credits, or Discord account linking,
        email us at{' '}
        <a className='' href='mailto:billing@suno.com'>
          billing@suno.com
        </a>
        .
      </div>
    </div>
  );
};

const CurrentPlanInfo = ({ sub }: { sub: SubscriptionInfo }) => {
  const planItems = useMemo(
    () => [
      { label: 'Current Plan', value: sub?.plan?.name },
      {
        label: 'Billing Period',
        value: sub?.period === SubscriptionPeriod.Monthly ? 'Month' : 'Annual',
      },
      sub.cancel_on
        ? {
            label: 'Plan End Date',
            value: (
              <span className='flex w-full flex-row items-center gap-2'>
                {formatDate(sub.cancel_on)}
              </span>
            ),
          }
        : {
            label: 'Next Billing Date',
            value: (
              <span className='flex w-full flex-row items-center gap-2'>
                <RotateReverseIcon className='hidden md:block' />
                {formatDate(sub.renews_on)}
              </span>
            ),
          },
      { label: 'Credits Remaining', value: sub.total_credits_left },
    ],
    [sub]
  );

  return (
    <div className='space-between flex flex-row divide-x divide-white/10'>
      {planItems.map((item) => (
        <PlanInfoItem key={item.label} {...item} />
      ))}
    </div>
  );
};

const formatDate = (date: string | null) => {
  return format(parseISO(date || ''), 'MMM d, y');
};

const PlanInfoItem = ({
  label,
  value,
}: {
  label: string;
  value: string | ReactNode;
}) => {
  return (
    <div className='items-left flex flex-col gap-1 px-4 first:pl-0 last:pr-0'>
      <span className='text-xs text-gray-800/60'>{label}</span>
      <span className='text-sm text-gray-950/90'>{value}</span>
    </div>
  );
};
