'use client';
import React, { useState, useCallback } from 'react';
import Image from 'next/image';
import { skipToken } from '@tanstack/react-query';
import { toast } from 'sonner';
import { Loader2 } from 'lucide-react';
import { usePurchaseStore } from '@/lib/purchase-store';
import { StepItem } from '@/components/payment/step-item';
import { api } from '@/lib/trpc/client';
import { PlanType } from '@/server/modules/payment/types/plan-type.enum';
import { SubscriptionProvider } from '@/server/modules/payment/types/subscription-provider.enum';

type PurchaseStepProps = {
  step: string;
};

export const PurchaseStep: React.FC<PurchaseStepProps> = (props) => {
  const { step } = props;

  const { state } = usePurchaseStore();

  const [provider, setProvider] = useState<SubscriptionProvider>();

  const {
    isEnabled,
    isPending,
    data: price
  } = api.payment.planPrice.get.useQuery(
    state.priceId
      ? {
          with: ['plan'],
          id: state.priceId
        }
      : skipToken
  );

  const purchaseMutation = api.payment.subscription.purchase.useMutation({
    onSuccess(data) {
      if (data.url) {
        window.open(data.url, '_self');
      }
    },
    onError(error) {
      if (error.message) {
        toast.error('Fejl ved oprettelse af abonnement: ' + error.message);
        return;
      }

      toast.error('Der opstod en fejl ved oprettelse af abonnementet');
    }
  });

  const handlePurchase = useCallback(
    async (provider: SubscriptionProvider) => {
      setProvider(provider);

      await purchaseMutation.mutateAsync({
        provider,
        priceId: state.priceId!,
        organizationId: state.organizationId,
        seats: state.seats!
      });
    },
    [purchaseMutation, state]
  );

  if (!state.priceId || !isEnabled) {
    return null;
  }

  if (isPending || !price) {
    return (
      <div className='m-4 flex items-center justify-center gap-2'>
        <Loader2 className='size-8 animate-spin' /> Indlæser...
      </div>
    );
  }

  if (
    price.plan?.type === PlanType.BUSINESS &&
    (!state.priceId || !state.organizationId || !state.seats)
  ) {
    return null;
  }

  return (
    <StepItem step={step} title='Vælg Betalingsmetode'>
      <div className='text-center'>
        <button
          className='transition hover:opacity-90'
          title='MobilePay'
          disabled={purchaseMutation.isPending}
          onClick={() => handlePurchase(SubscriptionProvider.MOBILEPAY)}
        >
          {purchaseMutation.isPending &&
          provider === SubscriptionProvider.MOBILEPAY ? (
            <div className='flex items-center justify-center gap-2 rounded bg-white px-8 py-3'>
              <Loader2 className='h-4 w-4 animate-spin' />
              <span>Opretter abonnement...</span>
            </div>
          ) : (
            <Image
              width={240}
              height={42}
              alt='MobilePay'
              src='/images/purchase/mobpay.png'
            />
          )}
        </button>

        <div className='before:height-1 relative my-2 block text-center text-sm before:absolute before:top-[50%] before:left-0 before:z-0 before:w-full before:border-t before:border-neutral-300'>
          <span className='relative inline-block bg-neutral-100 p-4'>
            Eller
          </span>
        </div>

        <button
          className='transition hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-50'
          title='Betalingskort'
          disabled={purchaseMutation.isPending}
          onClick={() => handlePurchase(SubscriptionProvider.STRIPE)}
        >
          {purchaseMutation.isPending &&
          provider === SubscriptionProvider.STRIPE ? (
            <div className='flex items-center justify-center gap-2 rounded bg-white px-8 py-3'>
              <Loader2 className='h-4 w-4 animate-spin' />
              <span>Opretter abonnement...</span>
            </div>
          ) : (
            <Image
              width={240}
              height={42}
              alt='Betalingskort'
              src='/images/purchase/stripe.png'
            />
          )}
        </button>
      </div>
    </StepItem>
  );
};
