/* eslint-disable react/no-unstable-nested-components */
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import Toast from '@arcblock/ux/lib/Toast';
import {
  PaymentBeneficiaries,
  Status,
  TxGas,
  TxLink,
  api,
  formatAmount,
  formatError,
  formatTime,
  getInvoiceStatusColor,
  useMobile,
} from '@blocklet/payment-react';
import type {
  TCheckoutSession,
  TCreditGrantExpanded,
  TInvoice,
  TInvoiceExpanded,
  TPaymentLink,
} from '@blocklet/payment-types';
import { ArrowBackOutlined } from '@mui/icons-material';
import { Alert, Box, Button, CircularProgress, Divider, Stack, Tooltip, Typography } from '@mui/material';
import { styled } from '@mui/system';
import { useRequest, useSetState } from 'ahooks';
import { Link } from 'react-router-dom';

import { isEmpty } from 'lodash';
import Copyable from '../../../../components/copyable';
import Currency from '../../../../components/currency';
import CustomerLink from '../../../../components/customer/link';
import EventList from '../../../../components/event/list';
import InfoRow from '../../../../components/info-row';
import { Download } from '../../../../components/invoice-pdf/pdf';
import InvoiceActions from '../../../../components/invoice/action';
import InvoiceTable from '../../../../components/invoice/table';
import MetadataEditor from '../../../../components/metadata/editor';
import MetadataList from '../../../../components/metadata/list';
import PaymentList from '../../../../components/payment-intent/list';
import RefundList from '../../../../components/refund/list';
import SectionHeader from '../../../../components/section/header';
import { goBackOrFallback } from '../../../../libs/util';
import InfoMetric from '../../../../components/info-metric';
import InfoRowGroup from '../../../../components/info-row-group';
import RelatedCreditGrants from '../../../../components/customer/related-credit-grants';

const fetchData = (
  id: string
): Promise<
  TInvoiceExpanded & {
    relatedInvoice?: TInvoiceExpanded;
    checkoutSession: TCheckoutSession;
    paymentLink: TPaymentLink;
    relatedCreditGrants?: TCreditGrantExpanded[];
    quotes?: any[];
  }
> => {
  return api.get(`/api/invoices/${id}?sync=true`).then((res: any) => res.data);
};

const InfoDirection = 'column';
const InfoAlignItems = 'flex-start';

export default function InvoiceDetail(props: { id: string }) {
  const { t } = useLocaleContext();
  const { isMobile } = useMobile();
  const [state, setState] = useSetState({
    adding: {
      price: false,
    },
    editing: {
      metadata: false,
      product: false,
    },
    loading: {
      metadata: false,
      price: false,
      product: false,
    },
  });

  const { loading, error, data, runAsync } = useRequest(() => fetchData(props.id));

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

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

  const createUpdater = (key: string) => async (updates: TInvoice) => {
    try {
      setState((prev) => ({ loading: { ...prev.loading, [key]: true } }));
      await api.put(`/api/invoices/${props.id}`, updates).then((res: any) => res.data);
      Toast.success(t('common.saved'));
      runAsync();
    } catch (err) {
      console.error(err);
      Toast.error(formatError(err));
    } finally {
      setState((prev) => ({ loading: { ...prev.loading, [key]: false } }));
    }
  };

  const onUpdateMetadata = createUpdater('metadata');
  const handleEditMetadata = () => {
    setState((prev) => ({ editing: { ...prev.editing, metadata: true } }));
  };

  const getDescription = (description: string) => {
    let desc = description;
    if (desc.startsWith('Slash stake')) {
      desc = t('payment.invoice.reason.slashStake');
    }
    if (desc.startsWith('Subscription ')) {
      desc = t(`payment.invoice.reason.${desc.replace('Subscription ', '')}`);
    }
    return desc;
  };
  // @ts-ignore
  const isDonation = data?.checkoutSession?.submit_type === 'donate';
  const showDownloadButton =
    ['open', 'paid', 'uncollectible'].includes(data.status) && !isDonation && !isEmpty(data.lines);
  return (
    <Root direction="column" spacing={2.5} sx={{ mb: 4 }}>
      <Box>
        <Stack
          className="page-header"
          direction="row"
          sx={{
            justifyContent: 'space-between',
            alignItems: 'center',
          }}>
          <Stack
            direction="row"
            onClick={() => goBackOrFallback('/admin/billing/invoices')}
            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('admin.invoices')}
            </Typography>
          </Stack>
          <Box style={{ display: 'flex', gap: '10px' }}>
            {showDownloadButton && <Download data={data} />}
            <InvoiceActions data={data} onChange={runAsync} variant="normal" />
          </Box>
        </Stack>
        {data.status === 'uncollectible' && data.metadata?.slippage?.below_threshold && (
          <Alert severity="warning" sx={{ mt: 2 }}>
            <Typography variant="body2">
              {t('payment.customer.invoice.slippageExceededDetail', {
                currentRate: data.metadata.slippage.rate_at_invoice || '—',
                minRate: data.metadata.slippage.min_acceptable_rate || '—',
              })}
            </Typography>
          </Alert>
        )}
        <Box
          sx={{
            mt: 4,
            mb: 3,
            display: 'flex',

            gap: {
              xs: 2,
              sm: 2,
              md: 5,
            },

            flexWrap: 'wrap',

            flexDirection: {
              xs: 'column',
              sm: 'column',
              md: 'row',
            },

            alignItems: {
              xs: 'flex-start',
              sm: 'flex-start',
              md: 'center',
            },
          }}>
          <Stack
            direction="column"
            sx={{
              gap: 1,
            }}>
            <Stack
              direction="row"
              sx={{
                alignItems: 'center',
              }}>
              <Typography variant="h2" sx={{ fontWeight: 600 }}>
                {data.number}
              </Typography>
              <Typography variant="h2" sx={{ fontWeight: 600, mx: 1 }}>
                for
              </Typography>
              <Typography variant="h2" sx={{ fontWeight: 600 }}>
                {formatAmount(data.total, data.paymentCurrency.decimal)} {data.paymentCurrency.symbol}
              </Typography>
            </Stack>
            <Copyable text={props.id} style={{ marginLeft: 4 }} />
          </Stack>
          <Stack
            className="section-body"
            sx={{
              justifyContent: 'flex-start',
              flexWrap: 'wrap',

              'hr.MuiDivider-root:last-child': {
                display: 'none',
              },

              flexDirection: {
                xs: 'column',
                sm: 'column',
                md: 'row',
              },

              alignItems: 'flex-start',

              gap: {
                xs: 1,
                sm: 1,
                md: 3,
              },
            }}>
            <InfoMetric
              label={t('common.status')}
              value={
                <Stack direction="row" spacing={1} alignItems="center">
                  <Status label={data.status} color={getInvoiceStatusColor(data.status)} />
                  {data.status === 'uncollectible' && data.metadata?.slippage?.below_threshold && (
                    <Tooltip
                      title={t('payment.customer.invoice.slippageExceededDetail', {
                        currentRate: data.metadata.slippage.rate_at_invoice || '—',
                        minRate: data.metadata.slippage.min_acceptable_rate || '—',
                      })}
                      arrow
                      placement="top">
                      <span>
                        <Status label={t('payment.customer.invoice.slippageExceeded')} color="warning" />
                      </span>
                    </Tooltip>
                  )}
                </Stack>
              }
              divider
            />
            {data.subscription && (
              <InfoMetric
                label={t('admin.subscription.name')}
                value={
                  <Link to={`/admin/billing/${data.subscription.id}`}>
                    <Typography
                      variant="body1"
                      sx={{
                        color: 'text.link',
                      }}>
                      {data.subscription.description || data.subscription.id}
                    </Typography>
                  </Link>
                }
                divider
              />
            )}
            <InfoMetric label={t('common.createdAt')} value={formatTime(data.created_at)} divider />
            <InfoMetric
              label={t('admin.subscription.currentPeriod')}
              value={
                data.period_start && data.period_end
                  ? [formatTime(data.period_start * 1000), formatTime(data.period_end * 1000)].join(' ~ ')
                  : ''
              }
            />
          </Stack>
        </Box>
        <Divider />
      </Box>
      <Stack
        sx={{
          flexDirection: {
            xs: 'column',
            lg: 'row',
          },
          gap: {
            xs: 2.5,
            md: 4,
          },
          '.payment-link-column-1': {
            minWidth: {
              xs: '100%',
              lg: '600px',
            },
          },
          '.payment-link-column-2': {
            width: {
              xs: '100%',
              md: '100%',
              lg: '320px',
            },
            maxWidth: {
              xs: '100%',
              md: '33%',
            },
          },
        }}>
        <Box
          className="payment-link-column-1"
          sx={{
            flex: 1,
            gap: 2.5,
            display: 'flex',
            flexDirection: 'column',
          }}>
          <Box className="section" sx={{ containerType: 'inline-size' }}>
            <SectionHeader title={t('admin.details')} />
            <InfoRowGroup
              sx={{
                display: 'grid',
                gridTemplateColumns: {
                  xs: 'repeat(1, 1fr)',
                  xl: 'repeat(2, 1fr)',
                },
                '@container (min-width: 1000px)': {
                  gridTemplateColumns: 'repeat(2, 1fr)',
                },
                '.info-row-wrapper': {
                  gap: 1,
                  flexDirection: {
                    xs: 'column',
                    xl: 'row',
                  },
                  alignItems: {
                    xs: 'flex-start',
                    xl: 'center',
                  },
                  '@container (min-width: 1000px)': {
                    flexDirection: 'row',
                    alignItems: 'center',
                  },
                },
                '.currency-name': {
                  color: 'text.secondary',
                },
              }}>
              <InfoRow
                label={t('admin.invoice.billTo')}
                value={<CustomerLink customer={data.customer} size={isMobile ? 'default' : 'small'} />}
              />
              <InfoRow label={t('admin.invoice.from')} value={data.statement_descriptor || blocklet.appName} />
              <InfoRow label={t('admin.invoice.description')} value={getDescription(data.description || '')} />

              <InfoRow label={t('admin.invoice.billing')} value={data.collection_method} />
              {data.status_transitions?.finalized_at && (
                <InfoRow
                  label={t('admin.invoice.finalizedAt')}
                  value={formatTime(data.status_transitions.finalized_at * 1000)}
                />
              )}
              {data.status_transitions?.paid_at && (
                <InfoRow label={t('admin.invoice.paidAt')} value={formatTime(data.status_transitions.paid_at * 1000)} />
              )}
              <InfoRow
                label={t('admin.paymentMethod._name')}
                value={<Currency logo={data.paymentMethod?.logo} name={data.paymentMethod?.name} />}
              />
              <InfoRow
                label={t('admin.paymentCurrency.name')}
                value={
                  <Currency
                    logo={data.paymentCurrency.logo}
                    name={`${data.paymentCurrency.symbol} (${data.paymentMethod?.name})`}
                  />
                }
              />
              {(!!data.paymentIntent?.payment_details?.ethereum || !!data.paymentIntent?.payment_details?.base) && (
                <InfoRow
                  label={t('common.txGas')}
                  value={<TxGas details={data.paymentIntent.payment_details as any} method={data.paymentMethod} />}
                />
              )}
              {data.paymentIntent && data.paymentIntent.payment_details && (
                <InfoRow
                  label={t(`common.${data.paymentIntent.payment_details?.arcblock?.type || 'transfer'}TxHash`)}
                  value={
                    <TxLink details={data.paymentIntent.payment_details} method={data.paymentMethod} mode="customer" />
                  }
                />
              )}
              {['stake', 'stake_overdraft_protection'].includes(data.billing_reason) &&
                data?.metadata?.payment_details?.arcblock?.tx_hash && (
                  <InfoRow
                    label={t('common.stakeTxHash')}
                    value={
                      <TxLink
                        details={{
                          arcblock: { tx_hash: data.metadata?.payment_details?.arcblock?.tx_hash, payer: '' },
                        }}
                        method={data.paymentMethod}
                      />
                    }
                  />
                )}
            </InfoRowGroup>
          </Box>
          {data?.relatedCreditGrants && data.relatedCreditGrants.length > 0 && (
            <RelatedCreditGrants grants={data.relatedCreditGrants} mode="dashboard" />
          )}
          <Divider />
          <Box className="section">
            <SectionHeader title={t('admin.summary')} />
            <Typography
              variant="body2"
              sx={{
                color: 'text.secondary',
                mb: 2,
                fontSize: '0.875rem',
              }}>
              {t('admin.invoice.billingContextNote')}
            </Typography>
            <Box className="section-body">
              <InvoiceTable invoice={data} emptyNodeText={t('empty.summary')} mode="admin" />
            </Box>
          </Box>
          <Divider />
          {isDonation && !isEmpty(data.paymentIntent?.beneficiaries) && (
            <>
              <Box className="section">
                <Typography variant="h3" className="section-header">
                  {t('customer.invoice.donation')}
                </Typography>
              </Box>
              <Box sx={{ maxWidth: 800 }}>
                <PaymentBeneficiaries
                  data={data?.paymentIntent?.beneficiaries as any}
                  currency={data.paymentCurrency}
                  totalAmount={data?.amount_paid}
                />
              </Box>
              <Divider />
            </>
          )}
          <Box className="section">
            <SectionHeader title={t('admin.payments')} />
            <Box className="section-body">
              <PaymentList features={{ customer: false, toolbar: false }} invoice_id={data.id} />
            </Box>
          </Box>
          <Divider />
          <Box className="section">
            <SectionHeader title={t('admin.refunds')} />
            <Box className="section-body">
              <RefundList features={{ customer: false, toolbar: false }} invoice_id={data.id} />
            </Box>
          </Box>
          <Divider />
          <Box className="section">
            <SectionHeader title={t('admin.events.title')} />
            <Box className="section-body">
              <EventList
                features={{ toolbar: false }}
                object_id={[data.id, data.payment_intent_id].filter(Boolean).join(',')}
              />
            </Box>
          </Box>
        </Box>
        {isMobile && <Divider />}
        <Box className="payment-link-column-2" sx={{ gap: 2.5, display: 'flex', flexDirection: 'column' }}>
          <Box className="section">
            <SectionHeader title={t('admin.connections')} />
            <Stack>
              <InfoRow
                label={t('admin.subscription.name')}
                value={
                  data.subscription ? (
                    <Link to={`/admin/billing/${data.subscription.id}`}>{data.subscription.id}</Link>
                  ) : (
                    ''
                  )
                }
                direction={InfoDirection}
                alignItems={InfoAlignItems}
              />
              <InfoRow
                label={t('admin.paymentIntent.name')}
                value={
                  data.payment_intent_id ? (
                    <Link to={`/admin/payments/${data.payment_intent_id}`}>{data.payment_intent_id}</Link>
                  ) : (
                    ''
                  )
                }
                direction={InfoDirection}
                alignItems={InfoAlignItems}
              />
            </Stack>
          </Box>
          <Divider />
          <Box className="section">
            <SectionHeader title={t('common.metadata.label')}>
              <Button
                variant="text"
                color="inherit"
                size="small"
                sx={{ color: 'text.link' }}
                disabled={state.editing.metadata}
                onClick={handleEditMetadata}>
                {t('common.edit')}
              </Button>
            </SectionHeader>
            <Box className="section-body">
              <MetadataList data={data.metadata} handleEditMetadata={handleEditMetadata} />
              {state.editing.metadata && (
                <MetadataEditor
                  data={data}
                  loading={state.loading.metadata}
                  onSave={onUpdateMetadata}
                  onCancel={() => setState((prev) => ({ editing: { ...prev.editing, metadata: false } }))}
                />
              )}
            </Box>
          </Box>
        </Box>
      </Stack>
    </Root>
  );
}

const Root = styled(Stack)``;
