/* eslint-disable react/require-default-props */
import DID from '@arcblock/ux/lib/DID';
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import { api, formatBNStr, formatCreditAmount, formatToDate, usePaymentContext } from '@blocklet/payment-react';
import { BN } from '@ocap/util';
import type { GroupedBN, TPaymentCurrency, TPaymentMethod, TPaymentStat } from '@blocklet/payment-types';
import {
  Avatar,
  Box,
  Button,
  Card,
  Divider,
  Grid,
  IconButton,
  Popover,
  Skeleton,
  Stack,
  Tab,
  Tabs,
  Typography,
} from '@mui/material';
import { alpha, useTheme } from '@mui/material/styles';
import { useRequest, useSetState } from 'ahooks';
import omit from 'lodash/omit';
import { useMemo, useState } from 'react';
import type { SyntheticEvent } from 'react';
import { Link } from 'react-router-dom';

import {
  ArrowForward,
  BalanceOutlined,
  CalendarMonth,
  KeyboardArrowDown,
  KeyboardArrowUp,
  LocalMallOutlined,
  PaidOutlined,
  PaymentsOutlined,
  Refresh,
  SellOutlined,
  WarningAmber,
} from '@mui/icons-material';
import Chart, { TCurrencyMap, TCurrency } from '../../components/chart';
import CurrencySelect from '../../components/price/currency-select';
import dayjs from '../../libs/dayjs';
import { stringToColor } from '../../libs/util';
import DateRangePicker from '../../components/date-range-picker';

type TRevenueStat = {
  totalRevenue: string;
  refundAmount: string;
  promotionCost: string;
  creditGrantCost: string;
  vendorCost: string;
  taxedRevenue: string;
  netRevenue: string;
};

type ChartType = 'payments' | 'payouts' | 'refunds';

type FilterState = {
  anchorEl: HTMLElement | null;
  startDate: Date;
  endDate: Date;
  currency: string;
  chartType: ChartType;
};

type TSummary = {
  balances: GroupedBN;
  addresses: GroupedBN;
  links: GroupedBN;
  summary: { [key: string]: { status: string; count: number }[] };
  revenueByCurrency?: Record<string, TRevenueStat>;
};

type MetricItem = { type: string; count: number; countStatus?: string; total?: number; link: string };

const FILTER_ALL = 'all';
const DEFAULT_CURRENCY_DISPLAY_COUNT = 3;
const INDICATOR_SKELETON_KEYS = ['slot-a', 'slot-b', 'slot-c'];
const ADDRESS_SKELETON_KEYS = ['slot-a', 'slot-b'];
const BALANCE_SKELETON_KEYS = ['slot-a', 'slot-b', 'slot-c'];
const METRIC_SKELETON_KEYS = ['slot-a', 'slot-b', 'slot-c', 'slot-d'];

export const getDefaultRanges = (date: string) => [
  {
    label: 'This Week',
    startDate: dayjs(date).startOf('week').toDate(),
    endDate: dayjs(date).endOf('week').toDate(),
  },
  {
    label: 'Last Week',
    startDate: dayjs(date).subtract(1, 'week').startOf('week').toDate(),
    endDate: dayjs(date).subtract(1, 'week').endOf('week').toDate(),
  },
  {
    label: 'Last 7 Days',
    startDate: dayjs(date).subtract(7, 'day').startOf('day').toDate(),
    endDate: dayjs(date).toDate(),
  },
  {
    label: 'This Month',
    startDate: dayjs(date).startOf('month').toDate(),
    endDate: dayjs(date).endOf('month').toDate(),
  },
  {
    label: 'Last Month',
    startDate: dayjs(date).subtract(1, 'month').startOf('month').toDate(),
    endDate: dayjs(date).subtract(1, 'month').endOf('month').toDate(),
  },
  {
    label: 'This Year',
    startDate: dayjs(date).startOf('year').toDate(),
    endDate: dayjs(date).endOf('year').toDate(),
  },
  {
    label: 'Last Year',
    startDate: dayjs(date).subtract(1, 'year').startOf('year').toDate(),
    endDate: dayjs(date).subtract(1, 'year').endOf('year').toDate(),
  },
];

export const groupData = (data: TPaymentStat[], currencies: { [key: string]: any }, key: string, locale: string) => {
  const grouped: { [key: string]: object } = {};
  data.forEach((x) => {
    if (!grouped[x.timestamp]) {
      grouped[x.timestamp] = { timestamp: formatToDate(x.timestamp * 1000, locale, 'YYYY-MM-DD') };
    }

    if (currencies[x.currency_id]) {
      const { symbol } = currencies[x.currency_id];
      // @ts-ignore
      grouped[x.timestamp][symbol] = +x[key];
    }
  });

  return Object.values(grouped);
};

export const isZeroValue = (value: string): boolean => {
  try {
    return new BN(value || '0').isZero();
  } catch (err) {
    return Number(value) === 0;
  }
};

export const sortByMethodAndSymbol = (
  a: { method?: string; symbol: string },
  b: { method?: string; symbol: string }
): number => {
  const methodA = a.method || '';
  const methodB = b.method || '';

  const methodCompare = methodA.localeCompare(methodB);
  if (methodCompare !== 0) {
    return methodCompare;
  }

  return a.symbol.localeCompare(b.symbol);
};

export const getCurrencyLabel = (currency: TCurrency): string =>
  currency.symbol || ((currency as any).display_name as string | undefined) || currency.name;

export default function Overview() {
  const { t, locale } = useLocaleContext();
  const { settings, livemode } = usePaymentContext();
  const theme = useTheme();
  const maxDate = dayjs().endOf('day').toDate();
  const [state, setState] = useSetState<FilterState>({
    anchorEl: null,
    startDate: dayjs().subtract(30, 'day').startOf('day').toDate(),
    endDate: maxDate,
    currency: FILTER_ALL,
    chartType: 'payments',
  });

  const currencies: TCurrencyMap = useMemo(() => {
    const map: TCurrencyMap = {};
    (settings.paymentMethods || []).forEach((method: { payment_currencies: TPaymentCurrency[] }) => {
      (method.payment_currencies || []).forEach((currency: TPaymentCurrency) => {
        if (!map[currency.id]) {
          map[currency.id] = {
            ...currency,
            method: omit(method, ['payment_currencies']) as TPaymentMethod,
            color: stringToColor(currency.id),
          };
        }
      });
    });
    return map;
  }, [settings.paymentMethods]);

  const currencyList = useMemo(() => {
    return Object.values(currencies).sort((a, b) => {
      return (a.symbol || '').localeCompare(b.symbol || '');
    });
  }, [currencies]);

  const selectedCurrencyIds = useMemo(() => {
    if (state.currency === FILTER_ALL) {
      return currencyList.map((item) => item.id);
    }
    if (state.currency && currencies[state.currency]) {
      return [state.currency];
    }
    return [];
  }, [currencyList, currencies, state.currency]);

  const filteredCurrencies = useMemo(() => {
    const map: TCurrencyMap = {};
    selectedCurrencyIds.forEach((id) => {
      if (currencies[id]) {
        map[id] = currencies[id];
      }
    });
    return map;
  }, [selectedCurrencyIds, currencies]);

  const currencyAllOption = useMemo(
    () => ({
      value: FILTER_ALL,
      label: t('admin.overviewPage.filters.allCurrencies'),
    }),
    [t]
  );

  const currencySelectedTypographySx = {
    justifyContent: 'space-between',
    textAlign: 'left',
    minWidth: 'unset',
    width: '100%',
    fontWeight: 500,
    color: 'text.primary',
    fontSize: '0.875rem',
  } as const;

  const currencySelectSx = {
    width: '100%',
    height: 32,
    border: 'none',
    '& .MuiOutlinedInput-root': {
      height: 32,
    },
    '& .MuiOutlinedInput-notchedOutline': {
      border: 'none',
    },
    '& .MuiSelect-select': {
      py: 0,
      px: 2,
      height: 32,
      display: 'flex',
      alignItems: 'center',
      fontSize: '12px',
      fontWeight: 400,
    },
  } as const;

  const indicatorGridSx = {
    display: 'grid',
    gap: 2,
    gridTemplateColumns: {
      xs: 'repeat(1, minmax(0, 1fr))',
      sm: 'repeat(2, minmax(0, 1fr))',
      lg: 'repeat(3, minmax(0, 1fr))',
    },
  } as const;

  const trend = useRequest<TPaymentStat[], any>(
    async () => {
      const params: { start: number; end: number; currency_id?: string } = {
        start: dayjs(state.startDate).unix(),
        end: dayjs(state.endDate).unix(),
      };
      if (state.currency !== FILTER_ALL) {
        params.currency_id = state.currency;
      }
      const result = await api.get('/api/payment-stats', {
        params,
      });
      return result.data.list;
    },
    {
      refreshDeps: [state.startDate, state.endDate, state.currency],
    }
  );

  const summary = useRequest<TSummary, any>(
    async () => {
      const params: { start: number; end: number; currency_id?: string } = {
        start: dayjs(state.startDate).unix(),
        end: dayjs(state.endDate).unix(),
      };
      if (state.currency !== FILTER_ALL) {
        params.currency_id = state.currency;
      }
      const result = await api.get('/api/payment-stats/summary', {
        params,
      });
      return result.data;
    },
    {
      refreshDeps: [state.startDate, state.endDate, state.currency],
    }
  );

  const overdueSummary = useRequest<
    {
      list: Array<{
        currency: TPaymentCurrency;
        total_pending: string;
        customer_count: number;
        event_count: number;
      }>;
    },
    any
  >(
    async () => {
      const result = await api.get('/api/meter-events/overdue-summary');
      return result.data;
    },
    {
      refreshDeps: [],
    }
  );

  const summaryLoading = summary.loading;
  const trendLoading = trend.loading;
  const overdueLoading = overdueSummary.loading;
  const overdueList = overdueSummary.data?.list || [];
  const hasOverdue = overdueList.length > 0;
  const summaryData = summary.data;
  const summarySummary = summaryData?.summary;
  const addresses = summaryData?.addresses;
  const balances = summaryData?.balances;
  const links = summaryData?.links || {};
  const hasAddresses = Boolean(addresses && Object.keys(addresses).length > 0);
  const hasBalances = Boolean(balances && Object.keys(balances).length > 0);

  const { metrics, attentions } = useMemo(() => {
    const metricItems: MetricItem[] = [];
    const attentionItems: MetricItem[] = [];
    if (!summarySummary) {
      return { metrics: metricItems, attentions: attentionItems };
    }
    const { subscription, invoice, refund, payment, payout } = summarySummary;

    metricItems.push(
      {
        type: 'subscription',
        count: subscription?.find((x) => x.status === 'active')?.count || 0,
        countStatus: 'active',
        total: subscription?.reduce((sum, item) => sum + Number(item.count), 0) || 0,
        link: '/admin/billing/subscriptions',
      },
      {
        type: 'invoice',
        count: invoice?.find((x) => x.status === 'paid')?.count || 0,
        countStatus: 'paid',
        total: invoice?.reduce((sum, item) => sum + Number(item.count), 0) || 0,
        link: '/admin/billing/invoices',
      },
      {
        type: 'refund',
        count: refund?.find((x) => x.status === 'succeeded')?.count || 0,
        countStatus: 'succeeded',
        total: refund?.reduce((sum, item) => sum + Number(item.count), 0) || 0,
        link: '/admin/payments/refunds',
      },
      {
        type: 'paymentIntent',
        count: payment?.find((x) => x.status === 'succeeded')?.count || 0,
        countStatus: 'succeeded',
        total: payment?.reduce((sum, item) => sum + Number(item.count), 0) || 0,
        link: '/admin/payments/intents',
      },
      {
        type: 'payout',
        count: payout?.find((x) => x.status === 'paid')?.count || 0,
        countStatus: 'paid',
        total: payout?.reduce((sum, item) => sum + Number(item.count), 0) || 0,
        link: '/admin/payments/payouts',
      }
    );

    attentionItems.push(
      {
        type: 'subscription',
        count: subscription?.find((x) => x.status === 'past_due')?.count || 0,
        link: '/admin/billing/subscriptions?status=past_due',
      },
      {
        type: 'invoice',
        count: invoice?.find((x) => x.status === 'uncollectible')?.count || 0,
        link: '/admin/billing/invoices?status=uncollectible',
      },
      {
        type: 'refund',
        count: refund?.find((x) => x.status === 'failed')?.count || 0,
        link: '/admin/payments/refunds?status=failed',
      },
      {
        type: 'paymentIntent',
        count: payment?.find((x) => x.status === 'requires_action')?.count || 0,
        link: '/admin/payments/intents?status=requires_action',
      },
      {
        type: 'payout',
        count: payout?.find((x) => x.status === 'failed')?.count || 0,
        link: '/admin/payments/payouts?status=failed',
      }
    );

    return { metrics: metricItems, attentions: attentionItems };
  }, [summarySummary]);

  const warnItems = useMemo(() => attentions.filter((x) => x.count > 0), [attentions]);
  const showAddressesCard = summaryLoading || hasAddresses;
  const showBalancesCard = summaryLoading || hasBalances;
  const showMetricsCard = summaryLoading || metrics.length > 0;

  const payments = useMemo(
    () => groupData(trend.data || [], filteredCurrencies, 'amount_paid', locale),
    [trend.data, filteredCurrencies, locale]
  );
  const payouts = useMemo(
    () => groupData(trend.data || [], filteredCurrencies, 'amount_payout', locale),
    [trend.data, filteredCurrencies, locale]
  );
  const refunds = useMemo(
    () => groupData(trend.data || [], filteredCurrencies, 'amount_refund', locale),
    [trend.data, filteredCurrencies, locale]
  );

  const chartData = useMemo(() => {
    if (state.chartType === 'payments') {
      return payments;
    }
    if (state.chartType === 'payouts') {
      return payouts;
    }
    return refunds;
  }, [state.chartType, payments, payouts, refunds]);

  const [expandedIndicators, setExpandedIndicators] = useState<Record<string, boolean>>({});

  const revenueByCurrency = useMemo(() => summaryData?.revenueByCurrency || {}, [summaryData?.revenueByCurrency]);
  const displayedCurrencies = useMemo(
    () =>
      selectedCurrencyIds.map((id) => currencies[id]).filter((currency): currency is TCurrency => Boolean(currency)),
    [selectedCurrencyIds, currencies]
  );

  const sortedBalanceCurrencyIds = useMemo(() => {
    return Object.keys(balances || {}).sort((a, b) => {
      const currencyA = currencies[a];
      const currencyB = currencies[b];
      if (!currencyA || !currencyB) return 0;
      return sortByMethodAndSymbol(
        { method: currencyA.method?.name, symbol: currencyA.symbol || '' },
        { method: currencyB.method?.name, symbol: currencyB.symbol || '' }
      );
    });
  }, [balances, currencies]);

  const indicatorConfigs = useMemo(
    () => [
      {
        key: 'totalRevenue' as const,
        title: t('admin.overviewPage.financialIndicators.totalIncome.title'),
        subtitle: t('admin.overviewPage.financialIndicators.totalIncome.subtitle'),
        palette: theme.palette.success,
        icon: <PaymentsOutlined />,
      },
      {
        key: 'vendorCost' as const,
        title: t('admin.overviewPage.financialIndicators.costOfGoods.title'),
        subtitle: t('admin.overviewPage.financialIndicators.costOfGoods.subtitle'),
        palette: theme.palette.error,
        icon: <LocalMallOutlined />,
      },
      {
        key: 'netRevenue' as const,
        title: t('admin.overviewPage.financialIndicators.netRevenue.title'),
        subtitle: t('admin.overviewPage.financialIndicators.netRevenue.subtitle'),
        palette: theme.palette.info,
        icon: <PaidOutlined />,
      },
      {
        key: 'promotionCost' as const,
        title: t('admin.overviewPage.financialIndicators.promotionCost.title'),
        subtitle: t('admin.overviewPage.financialIndicators.promotionCost.subtitle'),
        palette: theme.palette.secondary,
        icon: <SellOutlined />,
      },
      {
        key: 'taxedRevenue' as const,
        title: t('admin.overviewPage.financialIndicators.taxedRevenue.title'),
        subtitle: t('admin.overviewPage.financialIndicators.taxedRevenue.subtitle'),
        palette: theme.palette.primary,
        icon: <BalanceOutlined />,
      },
    ],
    [t, theme]
  );

  // 辅助函数：构建指标行数据
  const buildIndicatorRow = (currency: TCurrency, config: (typeof indicatorConfigs)[0]) => {
    const value = revenueByCurrency[currency.id]?.[config.key] || '0';
    const info = currencies[currency.id];
    const formattedNumber = info ? formatBNStr(value || '0', info.decimal || 0) : value || '0';
    const symbolLabel = getCurrencyLabel(currency);
    const suffix = info?.symbol || '';
    return {
      id: currency.id,
      symbol: symbolLabel,
      logo: currency.logo,
      value: suffix ? `${formattedNumber} ${suffix}` : formattedNumber,
      number: formattedNumber,
      suffix,
      rawValue: value,
      method: currency.method?.name,
    };
  };

  // 辅助函数：处理始终显示的指标（totalRevenue 和 netRevenue）
  const processAlwaysVisibleIndicator = (rows: ReturnType<typeof buildIndicatorRow>[]) => {
    const baseCurrencyId =
      typeof settings.baseCurrency === 'string' ? settings.baseCurrency : (settings.baseCurrency as any)?.id;

    const baseCurrencyRow = rows.find((row) => row.id === baseCurrencyId);
    const otherNonZeroRows = rows.filter((row) => row.id !== baseCurrencyId && !isZeroValue(row.rawValue));

    return baseCurrencyRow
      ? [baseCurrencyRow, ...otherNonZeroRows].sort(sortByMethodAndSymbol)
      : otherNonZeroRows.sort(sortByMethodAndSymbol);
  };

  const financialIndicators = useMemo(
    () =>
      indicatorConfigs
        .map((config) => {
          const rows = displayedCurrencies.map((currency) => buildIndicatorRow(currency, config));
          const isAlwaysVisible = config.key === 'totalRevenue' || config.key === 'netRevenue';

          let finalRows;
          if (isAlwaysVisible) {
            finalRows = processAlwaysVisibleIndicator(rows);
          } else {
            const meaningfulRows = rows.filter((row) => !isZeroValue(row.rawValue));
            if (meaningfulRows.length === 0) return null;
            finalRows = meaningfulRows.sort(sortByMethodAndSymbol);
          }

          return {
            ...config,
            rows: finalRows,
            gradient: `linear-gradient(135deg, ${alpha(config.palette.main, 0.08)} 0%, ${alpha(
              config.palette.main,
              0.02
            )} 100%)`,
            borderColor: alpha(config.palette.main, 0.24),
          };
        })
        .filter((item): item is NonNullable<typeof item> => Boolean(item)),
    [indicatorConfigs, displayedCurrencies, revenueByCurrency, currencies, settings.baseCurrency]
  );

  const handleToggleIndicator = (key: string) => {
    setExpandedIndicators((prev) => ({
      ...prev,
      [key]: !prev[key],
    }));
  };

  const renderFilterBar = () => (
    <Stack
      direction={{ xs: 'column', md: 'row' }}
      spacing={2}
      sx={{
        alignItems: { md: 'center' },
        justifyContent: 'space-between',
        flexWrap: 'wrap',
        mb: 2,
      }}>
      <Stack
        direction={{ xs: 'column', sm: 'row' }}
        spacing={2}
        sx={{
          flex: 1,
          alignItems: { sm: 'center' },
        }}>
        <Button
          onClick={onTogglePicker}
          variant="outlined"
          size="small"
          startIcon={<CalendarMonth fontSize="small" />}
          sx={{
            borderRadius: 1.5,
            textTransform: 'none',
            fontWeight: 400,
            px: 2,
            color: 'text.primary',
            borderColor: 'divider',
            '&:hover': {
              borderColor: 'primary.main',
              backgroundColor: 'transparent',
            },
          }}>
          {dateRangeLabel}
        </Button>
        <Box
          sx={{
            width: { xs: '100%', sm: 'auto' },
            minWidth: 140,
            border: '1px solid',
            borderColor: 'divider',
            borderRadius: 1.5,
            height: 32,
            display: 'flex',
            alignItems: 'center',
            px: 2,
            transition: 'border-color 0.2s',
            '&:hover': {
              borderColor: 'primary.main',
            },
            '&:has(.MuiSelect-root)': {
              px: 0,
            },
          }}>
          <CurrencySelect
            mode="selected"
            value={state.currency}
            hasSelected={() => false}
            onSelect={handleCurrencySelect}
            includeAllOption
            allOption={currencyAllOption}
            selectedSx={currencySelectedTypographySx}
            selectSX={currencySelectSx}
          />
        </Box>
        <IconButton
          onClick={handleRefresh}
          size="small"
          sx={{
            border: '1px solid',
            borderColor: 'divider',
            borderRadius: 1.5,
            width: {
              xs: 'fit-content',
              md: 'auto',
            },
            alignSelf: {
              xs: 'flex-end',
              md: 'flex-start',
            },
            '&:hover': {
              borderColor: 'primary.main',
            },
          }}>
          <Refresh fontSize="small" />
        </IconButton>
      </Stack>
    </Stack>
  );

  const renderAttentionBanner = () => {
    if (warnItems.length === 0) {
      return null;
    }

    return (
      <Box
        sx={{
          mb: 2,
          p: 1,
          borderRadius: 1,
          backgroundColor: alpha(theme.palette.warning.main, 0.05),
        }}>
        <Stack
          direction="row"
          spacing={1}
          useFlexGap
          sx={{
            alignItems: 'center',
            flexWrap: 'wrap',
          }}>
          <Typography
            variant="body2"
            sx={{
              color: 'text.secondary',
              fontWeight: 500,
              width: {
                xs: '100%',
                sm: 'auto',
              },
            }}>
            {t('admin.overviewPage.metrics.essential')}:
          </Typography>
          {warnItems.map((metric) => (
            <Button
              key={metric.type}
              component={Link}
              to={metric.link}
              variant="text"
              size="small"
              sx={{
                minWidth: 'auto',
                px: 1.5,
                py: 0.5,
                borderRadius: 0.75,
                textTransform: 'none',
                color: 'warning.main',
                backgroundColor: alpha(theme.palette.warning.main, 0.12),
                fontWeight: 500,
                fontSize: '0.875rem',
                '&:hover': {
                  backgroundColor: alpha(theme.palette.warning.main, 0.2),
                },
              }}>
              {t(`admin.${metric.type}.attention`)}: {metric.count}
            </Button>
          ))}
        </Stack>
      </Box>
    );
  };

  const renderFinancialIndicatorCards = () => {
    if (summaryLoading) {
      return (
        <Box sx={indicatorGridSx}>
          {indicatorConfigs.map((indicator) => (
            <Card
              key={`${indicator.key}-loading`}
              sx={{
                p: 2,
                borderRadius: 1,
                border: '1px solid',
                borderColor: alpha(indicator.palette.main, 0.12),
                backgroundColor: alpha(indicator.palette.main, 0.02),
              }}>
              <Stack spacing={2}>
                <Stack
                  direction="row"
                  spacing={1.5}
                  sx={{
                    alignItems: 'center',
                  }}>
                  <Skeleton variant="rectangular" width={48} height={48} sx={{ borderRadius: 1 }} />
                  <Box sx={{ flex: 1 }}>
                    <Skeleton variant="text" width="70%" height={20} />
                    <Skeleton variant="text" width="45%" height={16} />
                  </Box>
                </Stack>
                <Skeleton variant="rectangular" height={1} />
                <Stack spacing={1.5}>
                  {INDICATOR_SKELETON_KEYS.map((placeholder) => (
                    <Stack
                      key={`indicator-skeleton-${indicator.key}-${placeholder}`}
                      direction="row"
                      spacing={1}
                      sx={{
                        alignItems: 'center',
                      }}>
                      <Skeleton variant="circular" width={24} height={24} />
                      <Skeleton variant="text" width="45%" height={18} />
                      <Skeleton variant="text" width="30%" height={18} sx={{ marginLeft: 'auto' }} />
                    </Stack>
                  ))}
                </Stack>
              </Stack>
            </Card>
          ))}
        </Box>
      );
    }

    if (financialIndicators.length > 0) {
      return (
        <Box sx={indicatorGridSx}>
          {financialIndicators.map((indicator) => {
            const isExpanded = !!expandedIndicators[indicator.key];
            const hasMore = indicator.rows.length > DEFAULT_CURRENCY_DISPLAY_COUNT;
            const rowsToShow = isExpanded ? indicator.rows : indicator.rows.slice(0, DEFAULT_CURRENCY_DISPLAY_COUNT);

            return (
              <Card
                key={indicator.key}
                sx={{
                  p: 2,
                  borderRadius: 1,
                  backgroundImage: indicator.gradient,
                  border: '1px solid',
                  borderColor: indicator.borderColor,
                  boxShadow: 'none',
                  position: 'relative',
                }}>
                <Stack spacing={1.5}>
                  <Stack
                    direction="row"
                    spacing={1}
                    sx={{
                      alignItems: 'center',
                    }}>
                    <Box
                      sx={{
                        width: 48,
                        height: 48,
                        borderRadius: 1,
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        backgroundColor: alpha(indicator.palette.main, 0.15),
                      }}>
                      <Box
                        sx={{
                          color: indicator.palette.main,
                          display: 'flex',
                          alignItems: 'center',
                          justifyContent: 'center',
                        }}>
                        {indicator.icon}
                      </Box>
                    </Box>
                    <Box>
                      <Typography variant="body1" sx={{ fontWeight: 600 }}>
                        {indicator.title}
                      </Typography>
                      <Typography
                        variant="caption"
                        sx={{
                          color: 'text.secondary',
                        }}>
                        {indicator.subtitle}
                      </Typography>
                    </Box>
                  </Stack>

                  <Divider />

                  <Stack spacing={2} sx={{ mb: hasMore ? '30px !important' : 0 }}>
                    {rowsToShow.map((row) => (
                      <Stack
                        key={row.id}
                        direction="row"
                        spacing={1}
                        sx={{
                          alignItems: 'center',
                        }}>
                        <Avatar src={row.logo} alt={row.symbol} sx={{ width: 24, height: 24 }} />
                        <Box sx={{ flex: 1, minWidth: 0 }}>
                          <Typography variant="body2" sx={{ fontWeight: 600 }}>
                            {row.method}
                          </Typography>
                        </Box>
                        <Typography
                          variant="body2"
                          sx={{
                            fontWeight: 600,
                            textAlign: 'right',
                            color: indicator.palette.main,
                          }}>
                          {row.value}
                        </Typography>
                      </Stack>
                    ))}
                  </Stack>

                  {hasMore && (
                    <Box
                      sx={{
                        display: 'flex',
                        justifyContent: 'center',
                        pt: 0.5,
                        position: 'absolute',
                        bottom: '10px',
                        left: '50%',
                        transform: 'translateX(-50%)',
                      }}>
                      <IconButton
                        size="small"
                        onClick={() => handleToggleIndicator(indicator.key)}
                        sx={{
                          color: indicator.palette.main,
                          '&:hover': {
                            backgroundColor: alpha(indicator.palette.main, 0.1),
                          },
                        }}>
                        {isExpanded ? <KeyboardArrowUp fontSize="small" /> : <KeyboardArrowDown fontSize="small" />}
                      </IconButton>
                    </Box>
                  )}
                </Stack>
              </Card>
            );
          })}
        </Box>
      );
    }

    return (
      <Typography
        variant="body2"
        sx={{
          color: 'text.secondary',
        }}>
        {t('common.noData')}
      </Typography>
    );
  };

  const renderTrendCard = () => (
    <Card
      variant="outlined"
      sx={{
        p: { xs: 2, md: 3 },
        borderRadius: 1,
      }}>
      <Stack spacing={2}>
        <Stack
          direction={{ xs: 'column', sm: 'row' }}
          spacing={2}
          sx={{
            alignItems: { sm: 'center' },
            justifyContent: 'space-between',
          }}>
          <Box>
            <Typography variant="h5" sx={{ fontWeight: 600 }}>
              {t('admin.overviewPage.charts.title')}
            </Typography>
          </Box>
          <Tabs
            value={state.chartType}
            onChange={handleChartTypeChange}
            sx={{
              minHeight: 36,
              border: '1px solid',
              borderColor: 'divider',
              borderRadius: 1,
              p: 0.5,
              '& .MuiTabs-flexContainer': {
                gap: 0.5,
              },
              '& .MuiTab-root': {
                fontSize: '0.875rem',
                px: '8px !important',
                mr: '8px !important',
                textTransform: 'none',
                color: 'text.secondary',
                borderRadius: 1,
                '&.Mui-selected': {
                  color: 'primary.main',
                  fontSize: '0.875rem !important',
                  backgroundColor: alpha(theme.palette.primary.main, 0.08),
                },
              },
              '& .MuiTabs-indicator': {
                display: 'none',
              },
            }}>
            <Tab value="payments" label={t('admin.overviewPage.charts.payments')} />
            <Tab value="payouts" label={t('admin.overviewPage.charts.payouts')} />
            <Tab value="refunds" label={t('admin.overviewPage.charts.refunds')} />
          </Tabs>
        </Stack>
        <Chart loading={trendLoading} height={360} data={chartData} currencies={filteredCurrencies} />
      </Stack>
    </Card>
  );

  const renderFinancialSection = () => (
    <Stack spacing={3}>
      <Typography variant="h5" sx={{ fontWeight: 600 }}>
        {t('admin.overviewPage.financialIndicatorsTitle')}
      </Typography>
      {renderFinancialIndicatorCards()}
      {renderTrendCard()}
    </Stack>
  );

  const showOverdueCard = overdueLoading || hasOverdue;

  const renderBusinessMonitoringSection = () => (
    <Stack direction="column" spacing={3}>
      <Typography variant="h5" sx={{ fontWeight: 600 }}>
        {t('admin.overviewPage.businessMonitoringTitle')}
      </Typography>
      {showAddressesCard && (
        <Card
          variant="outlined"
          sx={{
            p: 2,
            borderRadius: 1,
          }}>
          <Stack
            direction="row"
            sx={{
              alignItems: 'center',
              justifyContent: 'space-between',
            }}>
            <Typography variant="h5">{t('admin.addresses')}</Typography>
          </Stack>
          <Stack direction="column" spacing={1.5} sx={{ mt: 2 }}>
            {summaryLoading
              ? ADDRESS_SKELETON_KEYS.map((placeholder) => (
                  <Skeleton key={`address-skeleton-${placeholder}`} variant="rounded" height={40} />
                ))
              : Object.keys(addresses || {}).map((chain) => (
                  <Box
                    key={chain}
                    sx={{
                      backgroundColor: theme.mode === 'dark' ? 'grey.100' : 'grey.50',
                      p: 1,
                      borderRadius: 1.5,
                    }}>
                    <DID did={addresses?.[chain] as string} chainId={getChainId(chain)} copyable showQrcode />
                  </Box>
                ))}
          </Stack>
        </Card>
      )}
      {showBalancesCard && (
        <Card
          variant="outlined"
          sx={{
            p: 2,
            borderRadius: 1,
          }}>
          <Typography component="h3" variant="h5" sx={{ mb: 2 }}>
            {t('admin.balances')}
          </Typography>
          <Stack spacing={1}>
            {summaryLoading
              ? BALANCE_SKELETON_KEYS.map((placeholder) => (
                  <Skeleton key={`balance-skeleton-${placeholder}`} variant="rounded" height={56} />
                ))
              : sortedBalanceCurrencyIds.map((currencyId) => (
                  <Stack
                    key={currencyId}
                    component="a"
                    href={links[currencyId] as string}
                    target="_blank"
                    direction="row"
                    spacing={1}
                    sx={{
                      alignItems: 'center',
                      textDecoration: 'none',
                      backgroundColor: theme.mode === 'dark' ? 'grey.100' : 'grey.50',
                      color: 'inherit',
                      p: 1,
                      borderRadius: 1.5,
                      transition: 'background-color 0.2s ease-in-out',
                      '&:hover': {
                        backgroundColor: 'action.hover',
                        '& .arrow-icon': {
                          opacity: 1,
                          transform: 'translateX(0)',
                        },
                      },
                    }}>
                    <Avatar
                      src={currencies[currencyId]?.logo}
                      alt={currencies[currencyId]?.symbol}
                      sx={{ width: 24, height: 24 }}
                    />
                    <Box sx={{ flex: 1, minWidth: 0 }}>
                      <Typography variant="body2" sx={{ fontWeight: 500 }}>
                        {currencies[currencyId]?.symbol}
                      </Typography>
                      <Typography
                        variant="caption"
                        sx={{
                          color: 'text.secondary',
                        }}>
                        {currencies[currencyId]?.method.name}
                      </Typography>
                    </Box>
                    <Typography
                      variant="body2"
                      sx={{
                        fontWeight: 600,
                        textAlign: 'right',
                      }}>
                      {formatBNStr((balances?.[currencyId] as string) || '0', currencies[currencyId]?.decimal ?? 0)}
                    </Typography>
                    <ArrowForward
                      className="arrow-icon"
                      fontSize="small"
                      sx={{
                        opacity: 0,
                        transform: 'translateX(-10px)',
                        transition: 'all 0.2s ease-in-out',
                        color: 'text.secondary',
                      }}
                    />
                  </Stack>
                ))}
          </Stack>
        </Card>
      )}
      {showOverdueCard && (
        <Card
          variant="outlined"
          sx={{
            p: 2,
            borderRadius: 1,
          }}>
          <Stack
            direction="row"
            sx={{
              alignItems: 'center',
              mb: 2,
            }}>
            <Box
              sx={{
                width: 40,
                height: 40,
                borderRadius: 1,
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                backgroundColor: alpha(theme.palette.warning.main, 0.12),
                mr: 1.5,
              }}>
              <WarningAmber sx={{ color: 'warning.main', fontSize: 24 }} />
            </Box>
            <Box>
              <Typography component="h3" variant="h5">
                {t('admin.overviewPage.overdue.title')}
              </Typography>
              <Typography variant="caption" sx={{ color: 'text.secondary' }}>
                {t('admin.overviewPage.overdue.subtitle')}
              </Typography>
            </Box>
          </Stack>
          <Stack spacing={1}>
            {overdueLoading
              ? BALANCE_SKELETON_KEYS.slice(0, 2).map((placeholder) => (
                  <Skeleton key={`overdue-skeleton-${placeholder}`} variant="rounded" height={56} />
                ))
              : overdueList.map((item) => (
                  <Stack
                    key={item.currency.id}
                    component={Link}
                    to={`/admin/billing/overdue?currency_id=${item.currency.id}`}
                    direction="row"
                    spacing={1}
                    sx={{
                      alignItems: 'center',
                      textDecoration: 'none',
                      backgroundColor: theme.mode === 'dark' ? 'grey.100' : 'grey.50',
                      color: 'inherit',
                      p: 1.5,
                      borderRadius: 1.5,
                      transition: 'background-color 0.2s ease-in-out',
                      '&:hover': {
                        backgroundColor: 'action.hover',
                        '& .arrow-icon': {
                          opacity: 1,
                          transform: 'translateX(0)',
                        },
                      },
                    }}>
                    <Avatar src={item.currency.logo} alt={item.currency.symbol} sx={{ width: 28, height: 28 }} />
                    <Box sx={{ flex: 1, minWidth: 0 }}>
                      <Typography variant="body2" sx={{ fontWeight: 600 }}>
                        {item.currency.name}
                      </Typography>
                      <Typography variant="caption" sx={{ color: 'text.secondary' }}>
                        {t('admin.overviewPage.overdue.customers', { count: item.customer_count })}
                        {' · '}
                        {t('admin.overviewPage.overdue.events', { count: item.event_count })}
                      </Typography>
                    </Box>
                    <Typography
                      variant="body2"
                      sx={{
                        fontWeight: 600,
                        textAlign: 'right',
                        color: 'warning.main',
                      }}>
                      -
                      {formatCreditAmount(
                        formatBNStr(item.total_pending, item.currency.decimal ?? 0),
                        item.currency.symbol
                      )}
                    </Typography>
                    <ArrowForward
                      className="arrow-icon"
                      fontSize="small"
                      sx={{
                        opacity: 0,
                        transform: 'translateX(-10px)',
                        transition: 'all 0.2s ease-in-out',
                        color: 'text.secondary',
                      }}
                    />
                  </Stack>
                ))}
          </Stack>
        </Card>
      )}
      {showMetricsCard && (
        <Card
          variant="outlined"
          sx={{
            p: 2,
            borderRadius: 1,
          }}>
          <Typography component="h3" variant="h5">
            {t('admin.overviewPage.metrics.transaction')}
          </Typography>
          <Stack
            direction="row"
            sx={{
              flexWrap: 'wrap',
              gap: 1,
              mt: 2,
            }}>
            {summaryLoading
              ? METRIC_SKELETON_KEYS.map((placeholder) => (
                  <Skeleton
                    key={`metric-skeleton-${placeholder}`}
                    variant="rounded"
                    height={80}
                    sx={{ flex: '1 1 calc(50% - 8px)' }}
                  />
                ))
              : metrics.map((metric) => (
                  <Card
                    key={metric.type}
                    variant="outlined"
                    sx={{
                      p: 1.5,
                      flex: '1 1 calc(50% - 8px)',
                      minWidth: 0,
                      borderRadius: 1,
                      backgroundColor: theme.mode === 'dark' ? 'grey.100' : 'grey.50',
                      border: 'none',
                      boxShadow: 'none',
                      containerType: 'inline-size',
                    }}>
                    <Box>
                      <Typography
                        sx={{
                          color: 'text.primary',
                          fontSize: '0.875rem',
                          mb: 1,
                          fontWeight: 600,
                        }}>
                        {t(`admin.${metric.type}.name`)}
                      </Typography>
                      <Stack
                        sx={{
                          gap: 1.5,
                          flexWrap: 'wrap',
                          flexDirection: 'row',
                          alignItems: 'baseline',
                          '@container (max-width: 220px)': {
                            flexDirection: 'column',
                            alignItems: 'flex-start',
                          },
                        }}>
                        <Typography
                          component={Link}
                          to={`${metric.link}?status=`}
                          sx={{
                            fontSize: '1.5rem',
                            fontWeight: 600,
                            color: 'text.primary',
                            textDecoration: 'none',
                            cursor: 'pointer',
                            transition: 'color 0.15s ease-in-out',
                            '&:hover': {
                              color: 'primary.main',
                            },
                          }}>
                          {metric.total}
                        </Typography>
                        <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
                          <Typography
                            component="span"
                            sx={{
                              fontSize: '1rem',
                              color: 'text.secondary',
                            }}>
                            {t(`admin.${metric.type}.status.${metric.countStatus}`)}
                          </Typography>
                          <Typography
                            component={Link}
                            to={`${metric.link}?status=${metric.countStatus}`}
                            sx={{
                              fontSize: '1rem',
                              fontWeight: 600,
                              color: 'text.secondary',
                              textDecoration: 'none',
                              cursor: 'pointer',
                              transition: 'color 0.15s ease-in-out',
                              '&:hover': {
                                color: 'success.main',
                              },
                            }}>
                            {metric.count}
                          </Typography>
                        </Box>
                      </Stack>
                    </Box>
                  </Card>
                ))}
          </Stack>
        </Card>
      )}
    </Stack>
  );

  const onTogglePicker = (e: any) => {
    if (state.anchorEl) {
      setState({ anchorEl: null });
    } else {
      setState({ anchorEl: e.currentTarget });
    }
  };

  const onRangeChange = (range: any) => {
    setState({
      startDate: range.startDate,
      endDate: dayjs(range.endDate).endOf('day').toDate(),
      anchorEl: null,
    });
  };

  const handleChartTypeChange = (_: SyntheticEvent, value: ChartType) => {
    if (value) {
      setState({ chartType: value });
    }
  };

  const handleCurrencySelect = (currencyId: string) => {
    setState({ currency: currencyId });
  };

  const handleRefresh = () => {
    trend.run();
    summary.run();
  };

  const open = Boolean(state.anchorEl);
  const id = open ? 'date-range-picker-popover' : undefined;

  const dateRangeLabel = `${formatToDate(state.startDate, locale, 'YYYY-MM-DD')} - ${formatToDate(
    state.endDate,
    locale,
    'YYYY-MM-DD'
  )}`;

  const getChainId = (type: string) => {
    if (type === 'arcblock') {
      return livemode ? 'main' : 'beta';
    }
    return '';
  };

  return (
    <>
      {renderFilterBar()}
      {renderAttentionBanner()}

      <Grid
        container
        spacing={{ xs: 3, lg: 6 }}
        sx={{
          mb: 4,
        }}>
        <Grid
          size={{
            xs: 12,
            lg: 8,
          }}>
          {renderFinancialSection()}
        </Grid>

        <Grid
          size={{
            xs: 12,
            lg: 4,
          }}>
          {renderBusinessMonitoringSection()}
        </Grid>
      </Grid>

      <Popover
        id={id}
        open={open}
        anchorEl={state.anchorEl}
        onClose={() => setState({ anchorEl: null })}
        anchorOrigin={{ vertical: 'bottom', horizontal: 'left' }}>
        <DateRangePicker
          open
          toggle={onTogglePicker as any}
          maxDate={maxDate}
          definedRanges={getDefaultRanges(maxDate.toISOString())}
          onChange={onRangeChange}
        />
      </Popover>
    </>
  );
}
