'use client';

import { Display } from '@/components/display';
import StripePayment from '@/components/payment/stripe';
import { SubscribeBilling } from '@/components/subscribe/billing';
import useGlobalStore from '@/config/use-global';
import { queryOrderDetail } from '@/services/user/order';
import { purchaseCheckout } from '@/services/user/portal';
import { useQuery } from '@tanstack/react-query';
import { AiroButton } from '@workspace/airo-ui/components/AiroButton';
import { Card, CardContent } from '@workspace/airo-ui/components/card';
import { Separator } from '@workspace/airo-ui/components/separator';
import { formatDate } from '@workspace/airo-ui/utils';
import { useCountDown } from 'ahooks';
import { addMinutes, format } from 'date-fns';
import { useTranslations } from 'next-intl';
import Image from 'next/image';
import Link from 'next/link';
import { QRCodeCanvas } from 'qrcode.react';
import { useEffect, useState } from 'react';

export default function Page() {
  const t = useTranslations('order');
  const { getUserInfo } = useGlobalStore();
  const [orderNo, setOrderNo] = useState<string>();
  const [enabled, setEnabled] = useState<boolean>(false);

  const { data } = useQuery({
    enabled: enabled,
    queryKey: ['queryOrderDetail', orderNo],
    queryFn: async () => {
      const { data } = await queryOrderDetail({ order_no: orderNo! });
      if (data?.data?.status !== 1) {
        await getUserInfo();
        setEnabled(false);
      }
      return data?.data;
    },
    refetchInterval: 3000,
  });

  const { data: payment } = useQuery({
    enabled: !!orderNo && data?.status === 1,
    queryKey: ['purchaseCheckout', orderNo],
    queryFn: async () => {
      const { data } = await purchaseCheckout({
        orderNo: orderNo!,
        returnUrl: window.location.href,
      });
      if (data.data?.type === 'url' && data.data.checkout_url) {
        window.open(data.data.checkout_url, '_blank');
      }
      return data?.data;
    },
    refetchOnWindowFocus: false,
  });

  useEffect(() => {
    const searchParams = new URLSearchParams(location.search);
    if (searchParams.get('order_no')) {
      setOrderNo(searchParams.get('order_no')!);
      setEnabled(true);
    }
  }, []);

  const [countDown, formattedRes] = useCountDown({
    targetDate: data && format(addMinutes(data?.created_at, 15), "yyyy-MM-dd'T'HH:mm:ss.SSSxxx"),
  });

  const { hours, minutes, seconds } = formattedRes;

  const countdownDisplay =
    countDown > 0 ? (
      <>
        {hours.toString().length === 1 ? `0${hours}` : hours} :{' '}
        {minutes.toString().length === 1 ? `0${minutes}` : minutes} :{' '}
        {seconds.toString().length === 1 ? `0${seconds}` : seconds}
      </>
    ) : (
      <>{t('timeExpired')}</>
    );

  return (
    <div className='max-w-[490px]'>
      <Card className='border-none shadow-none sm:border sm:shadow'>
        <CardContent className='grid gap-2 p-6 text-sm'>
          <div className='relative'>
            <div className={'absolute flex gap-3'}>
              <div
                className={
                  'flex items-center justify-between rounded-md border-2 border-[#225BA9] p-0.5'
                }
              >
                <Image
                  src={data?.payment.icon || `/payment/balance.svg`}
                  width={32}
                  height={32}
                  alt={data?.payment.name}
                />
              </div>
              <div className={'mt-1 text-sm font-medium text-[#666666]'}>
                {data?.payment.name || data?.payment.platform}
              </div>
            </div>

            {data?.status && [2, 5].includes(data?.status) && (
              <div className='flex flex-col gap-4 sm:gap-8'>
                <div className='flex justify-end gap-2'>
                  <AiroButton variant={'primary'} asChild>
                    <Link href='/dashboard'>{t('subscribeNow')}</Link>
                  </AiroButton>
                  <AiroButton variant='outline'>
                    <Link href='/document'>{t('viewDocument')}</Link>
                  </AiroButton>
                </div>
                <h3 className='text-xl font-bold tracking-tight text-[#666666]'>
                  {t('paymentSuccess')}
                </h3>
              </div>
            )}
            {data?.status === 1 && payment?.type === 'url' && (
              <div className='flex flex-col gap-4 sm:gap-8'>
                <div className='flex justify-end gap-2'>
                  <AiroButton
                    variant={'primary'}
                    onClick={() => {
                      if (payment?.checkout_url) {
                        window.location.href = payment?.checkout_url;
                      }
                    }}
                  >
                    {t('goToPayment')}
                  </AiroButton>
                  <AiroButton variant='outline'>
                    <Link href='/subscribe'>{t('productList')}</Link>
                  </AiroButton>
                </div>
                <div className={'flex items-center'}>
                  <h3 className='text-xl font-bold tracking-tight text-[#666666]'>
                    {t('waitingForPayment')}
                  </h3>
                  <p className='ml-3 flex items-center text-xl font-bold text-[#E22C2E]'>
                    {countdownDisplay}
                  </p>
                </div>
              </div>
            )}

            {data?.status === 1 && payment?.type === 'qr' && (
              <div className='flex flex-col gap-4 sm:gap-8'>
                <div className='flex justify-end gap-2'>
                  <AiroButton asChild variant={'primary'}>
                    <Link href='/subscribe'>{t('productList')}</Link>
                  </AiroButton>
                  <AiroButton asChild variant='outline'>
                    <Link href='/order'>{t('orderList')}</Link>
                  </AiroButton>
                </div>
                <h3 className='text-2xl font-bold tracking-tight'>{t('scanToPay')}</h3>
                <p className='flex items-center text-3xl font-bold'>{countdownDisplay}</p>
                <QRCodeCanvas
                  value={payment?.checkout_url || ''}
                  size={208}
                  imageSettings={{
                    src: `/payment/alipay_f2f.svg`,
                    width: 24,
                    height: 24,
                    excavate: true,
                  }}
                />
              </div>
            )}

            {data?.status === 1 && payment?.type === 'stripe' && (
              <div className='flex flex-col items-center gap-4 text-center sm:gap-8'>
                <h3 className='text-2xl font-bold tracking-tight'>{t('waitingForPayment')}</h3>
                <p className='ml-3 flex items-center text-3xl font-bold'>{countdownDisplay}</p>
                {payment.stripe && <StripePayment {...payment.stripe} />}
              </div>
            )}

            {data?.status && [3, 4].includes(data?.status) && (
              <div className='flex flex-col gap-4 sm:gap-8'>
                <div className='flex justify-end gap-2'>
                  <AiroButton variant={'primary'} asChild>
                    <Link href='/subscribe'>{t('productList')}</Link>
                  </AiroButton>
                  <AiroButton asChild variant='outline'>
                    <Link href='/order'>{t('orderList')}</Link>
                  </AiroButton>
                </div>
                <h3 className='text-xl font-bold tracking-tight text-[#666666]'>
                  {t('orderClosed')}
                </h3>
              </div>
            )}
          </div>
          <Separator className='mb-3 mt-0 bg-[#225BA9] sm:mt-4' />
          <div className={'mb-4'}>
            <div className={'font-bold text-[#666]'}>{t('orderNumber')}</div>
            <div className={'text-xs text-[#4D4D4D]'}>{data?.order_no}</div>
          </div>
          {data?.type && [1, 2].includes(data.type) && (
            <div>
              <div className={'font-normal text-[#225BA9]'}>名称</div>
              <div className={'font-semibold'}>{data?.subscribe?.name}</div>
            </div>
          )}
          {data?.type === 3 && (
            <>
              <div className='font-semibold'>{t('resetTraffic')}</div>
              <ul className='grid grid-cols-2 gap-3 *:flex *:items-center *:justify-between lg:grid-cols-1'>
                <li className='flex items-center justify-between'>
                  <span className='text-muted-foreground line-clamp-2 flex-1'>
                    {t('resetPrice')}
                  </span>
                  <span>
                    <Display type='currency' value={data.amount} />
                  </span>
                </li>
              </ul>
            </>
          )}

          {data?.type === 4 && (
            <>
              <div className='font-semibold'>{t('balanceRecharge')}</div>
              <ul className='grid grid-cols-2 gap-3 *:flex *:items-center *:justify-between lg:grid-cols-1'>
                <li className='flex items-center justify-between'>
                  <span className='text-muted-foreground line-clamp-2 flex-1'>
                    {t('rechargeAmount')}
                  </span>
                  <span>
                    <Display type='currency' value={data.amount} />
                  </span>
                </li>
              </ul>
            </>
          )}
          <div>
            <div className={'font-normal text-[#225BA9]'}>{t('createdAt')}</div>
            <div className={'font-semibold'}>{formatDate(data?.created_at)}</div>
          </div>
          <Separator className='mb-3 mt-4 bg-[#225BA9]' />
          <SubscribeBilling
            order={{
              ...data,
              unit_price: data?.subscribe?.unit_price,
            }}
          />
        </CardContent>
      </Card>
    </div>
  );
}
