/* eslint-disable react/no-unstable-nested-components */
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import {
  Amount,
  Status,
  TxLink,
  api,
  formatBNStr,
  formatTime,
  getPayoutStatusColor,
  getUserProfileLink,
  useMobile,
} from '@blocklet/payment-react';
import type { TCustomer, TPaymentLink, TPayoutExpanded } from '@blocklet/payment-types';
import { ArrowBackOutlined } from '@mui/icons-material';
import { Alert, Avatar, Box, Button, CircularProgress, Divider, Stack, Typography } from '@mui/material';
import { styled } from '@mui/system';
import { useRequest } from 'ahooks';

import { useParams } from 'react-router-dom';
import InfoMetric from '../../../components/info-metric';
import InfoRow from '../../../components/info-row';
import SectionHeader from '../../../components/section/header';
import { goBackOrFallback } from '../../../libs/util';
import CustomerLink from '../../../components/customer/link';
import InfoRowGroup from '../../../components/info-row-group';
import { useArcsphere } from '../../../hooks/browser';

const fetchData = (
  id: string
): Promise<
  TPayoutExpanded & {
    paymentIntent?: { customer: TCustomer };
    paymentLink: TPaymentLink;
  }
> => {
  return api.get(`/api/payouts/${id}`).then((res: any) => res.data);
};

export default function PayoutDetail() {
  const { t, locale } = useLocaleContext();
  const { isMobile } = useMobile();
  const inArcsphere = useArcsphere();
  const params = useParams<{ id: string }>();
  const { loading, error, data } = useRequest(() => fetchData(params.id!), {
    ready: !!params.id,
  });

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

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

  const currency = data.paymentCurrency;
  const total = [formatBNStr(data?.amount, currency.decimal), currency.symbol].join(' ');
  const { paymentIntent, paymentLink } = data || {};

  const isAnonymousPayer = paymentIntent?.customer?.metadata?.anonymous;
  return (
    <Root direction="column" spacing={2.5} mb={4}>
      <Box>
        <Stack
          className="page-header"
          direction="row"
          sx={{
            justifyContent: 'space-between',
            alignItems: 'center',
          }}>
          {!inArcsphere ? (
            <Stack
              direction="row"
              onClick={() => goBackOrFallback('/customer/payouts')}
              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 />
          )}
          {paymentLink?.donation_settings?.reference && (
            <Button
              variant="outlined"
              onClick={() => {
                window.open(paymentLink?.donation_settings?.reference, '_blank');
              }}>
              {t('customer.payout.viewReference')}
            </Button>
          )}
        </Stack>
        <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="row"
            sx={{
              justifyContent: 'space-between',
              alignItems: 'center',
            }}>
            <Stack
              direction="row"
              sx={{
                alignItems: 'center',
              }}>
              <Stack
                direction="row"
                spacing={1}
                sx={{
                  alignItems: 'center',
                }}>
                <Avatar
                  src={data.paymentCurrency.logo}
                  alt={data.paymentCurrency.symbol}
                  variant="square"
                  sx={{ width: '52px', height: '52px', borderRadius: 0.5 }}
                />
                <Stack
                  direction="column"
                  sx={{
                    alignItems: 'flex-start',
                    justifyContent: 'space-around',
                  }}>
                  <Amount amount={total} sx={{ my: 0, fontSize: '1.75rem', lineHeight: '32px' }} />
                </Stack>
              </Stack>
            </Stack>
          </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={<Status label={data.status} color={getPayoutStatusColor(data.status)} />}
              divider
            />
            <InfoMetric
              label={t('customer.payout.payer')}
              value={
                <CustomerLink
                  customer={paymentIntent.customer}
                  cardProps={{
                    onAvatarClick: () => {
                      if (isAnonymousPayer) {
                        return;
                      }
                      window.open(getUserProfileLink(paymentIntent?.customer?.did, locale), '_blank');
                    },
                    renderName: (user) => {
                      return (
                        <Typography
                          variant="subtitle1"
                          sx={{
                            ...(isAnonymousPayer
                              ? {}
                              : {
                                  cursor: 'pointer',
                                  '&:hover': {
                                    color: 'text.link',
                                  },
                                }),
                          }}
                          onClick={() => {
                            if (isAnonymousPayer) {
                              return;
                            }
                            const url = getUserProfileLink(user?.did, locale);
                            window.open(url, '_blank');
                          }}>
                          {user.fullName}
                        </Typography>
                      );
                    },
                  }}
                  linked={false}
                />
              }
              divider
            />
          </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">
            <SectionHeader title={t('common.detail')} />
            <InfoRowGroup
              sx={{
                display: 'grid',
                gridTemplateColumns: {
                  xs: 'repeat(1, 1fr)',
                  lg: 'repeat(2, 1fr)',
                },
                '.info-row-wrapper': {
                  gap: 1,
                  flexDirection: {
                    xs: 'column',
                    lg: 'row',
                  },
                  alignItems: {
                    xs: 'flex-start',
                    lg: 'center',
                  },
                },
              }}>
              <InfoRow label={t('common.createdAt')} value={formatTime(data.created_at)} />
              {paymentIntent && paymentIntent.payment_details && (
                <InfoRow
                  label={t('customer.payout.payTxHash')}
                  value={<TxLink details={paymentIntent.payment_details} method={data.paymentMethod} mode="customer" />}
                />
              )}
              <InfoRow
                label={t('customer.payout.receiver')}
                value={<CustomerLink customer={data.customer} linked={false} size={isMobile ? 'default' : 'small'} />}
              />
            </InfoRowGroup>
          </Box>
        </Box>
      </Stack>
    </Root>
  );
}

const Root = styled(Stack)``;
