import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import Toast from '@arcblock/ux/lib/Toast';
import {
  CustomerInvoiceList,
  formatError,
  getPrefix,
  getQueryParams,
  usePaymentContext,
  OverdueInvoicePayment,
} from '@blocklet/payment-react';
import type { TCustomerExpanded } from '@blocklet/payment-types';
import { ArrowBackOutlined } from '@mui/icons-material';
import { Alert, Box, Button, CircularProgress, Stack, Typography } from '@mui/material';
import { styled } from '@mui/system';
import { useRequest } from 'ahooks';
import { useEffect, useState } from 'react';
import { useSearchParams } from 'react-router-dom';
import { joinURL } from 'ufo';

import { isEmpty } from 'lodash';
import SectionHeader from '../../../components/section/header';
import { useSessionContext } from '../../../contexts/session';
import api from '../../../libs/api';
import { goBackOrFallback } from '../../../libs/util';
import { useArcsphere } from '../../../hooks/browser';

const fetchData = (): Promise<TCustomerExpanded> => {
  return api.get('/api/customers/me').then((res: any) => res.data);
};

export default function CustomerInvoicePastDue() {
  const { t, locale } = useLocaleContext();
  const { events } = useSessionContext();
  const { connect, session } = usePaymentContext();
  const [params] = useSearchParams();
  const inArcsphere = useArcsphere();
  const [hasUnpaidInvoices, setHasUnpaidInvoices] = useState(false);
  const [showOverduePayment, setShowOverduePayment] = useState(false);

  const { loading, error, data, runAsync } = useRequest(fetchData);

  useEffect(() => {
    events.on('switch-did', () => {
      runAsync().catch(console.error);
    });
  }, []);

  if (error) {
    return <Alert severity="error">{formatError(error)}</Alert>;
  }

  if (loading) {
    return <CircularProgress />;
  }

  if (!data) {
    return (
      <Alert sx={{ mt: 3 }} severity="info">
        {t('payment.customer.empty')}
      </Alert>
    );
  }

  const subscriptionId = params.get('subscription') || '';
  const currencyId = params.get('currency') || '';
  const handleBatchPay = () => {
    if (subscriptionId && currencyId) {
      connect.open({
        containerEl: undefined as unknown as Element,
        saveConnect: false,
        action: 'collect-batch',
        locale: locale as 'en' | 'zh',
        prefix: joinURL(getPrefix(), '/api/did'),
        extraParams: { subscriptionId, currencyId },
        messages: {
          scan: t('common.connect.defaultScan'),
          title: t('payment.customer.invoice.payBatch'),
          confirm: t('common.connect.confirm'),
        } as any,
        onSuccess: () => {
          connect.close();
        },
        onClose: () => {
          connect.close();
        },
        onError: (err: any) => {
          Toast.error(formatError(err));
        },
      });
    } else {
      setShowOverduePayment(true);
    }
  };

  const onTableDataChange = (tableData: any, prevData: any) => {
    if (isEmpty(tableData) || tableData?.count === 0) {
      setHasUnpaidInvoices(false);
      if (prevData?.count > 0) {
        // paid all invoices
        const referer = getQueryParams(window.location.href)?.referer;
        if (referer) {
          window.location.replace(referer);
        } else {
          goBackOrFallback('/customer');
        }
      }
      return;
    }
    setHasUnpaidInvoices(true);
  };

  return (
    <Stack direction="column" spacing={3} sx={{ my: 2 }}>
      <Stack
        direction="row"
        sx={{
          alignItems: 'center',
          justifyContent: 'space-between',
        }}>
        {!inArcsphere ? (
          <Stack
            direction="row"
            onClick={() => goBackOrFallback('/customer')}
            sx={{
              alignItems: 'center',
              fontWeight: 'normal',
              cursor: 'pointer',
            }}>
            <ArrowBackOutlined fontSize="small" sx={{ mr: 0.5, color: 'text.secondary' }} />
            <Typography variant="h6" sx={{ color: 'text.secondary', fontWeight: 'normal' }}>
              {t('common.previous')}
            </Typography>
          </Stack>
        ) : (
          <Box />
        )}
      </Stack>
      <Root direction="column" spacing={3}>
        {hasUnpaidInvoices && <Alert severity="error">{t('payment.customer.pastDue.warning')}</Alert>}
        {showOverduePayment && (
          <OverdueInvoicePayment
            customerId={session.user.did}
            subscriptionId={subscriptionId}
            onPaid={() => {
              setShowOverduePayment(false);
            }}
            successToast={false}
            dialogProps={{
              open: showOverduePayment,
              onClose: () => setShowOverduePayment(false),
            }}
            detailLinkOptions={{
              enabled: false,
            }}
          />
        )}

        <Box className="section">
          <SectionHeader title={t('payment.customer.pastDue.invoices')} mb={0}>
            {hasUnpaidInvoices && (
              <Button size="small" variant="contained" color="primary" onClick={handleBatchPay}>
                {t('admin.subscription.batchPay.button')}
              </Button>
            )}
          </SectionHeader>
          <Box className="section-body">
            <CustomerInvoiceList
              customer_id={data.id}
              subscription_id={subscriptionId}
              currency_id={currencyId}
              pageSize={10}
              status="uncollectible"
              target="_blank"
              action="pay"
              type="table"
              onTableDataChange={onTableDataChange}
              relatedSubscription
            />
          </Box>
        </Box>
      </Root>
    </Stack>
  );
}

const Root = styled(Stack)`
  a {
    text-decoration: underline;
  }
`;
