import {
  formatCreditAmount,
  CreditGrantsList,
  CreditTransactionsList,
  api,
  AutoTopupModal,
  formatBNStr,
} from '@blocklet/payment-react';
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import { Box, Card, CardContent, Stack, Typography, Tabs, Tab, Button } from '@mui/material';
import { useMemo, useState, useEffect } from 'react';
import { useSearchParams } from 'react-router-dom';
import type { TPaymentCurrency } from '@blocklet/payment-types';
import { useRequest } from 'ahooks';
import { AddOutlined, AutoModeOutlined } from '@mui/icons-material';
import { BN } from '@ocap/util';
import Toast from '@arcblock/ux/lib/Toast';
import { formatError } from '@blocklet/error';
import SplitButton from '@arcblock/ux/lib/SplitButton';
import { useConditionalSection } from '../conditional-section';

enum CreditTab {
  OVERVIEW = 'overview',
  GRANTS = 'grants',
  TRANSACTIONS = 'transactions',
}

interface CreditOverviewProps {
  customerId: string;
  settings: any;
  mode?: 'portal' | 'dashboard';
}

const fetchCreditSummary = async (customerId: string) => {
  try {
    const [grantsResponse, pendingAmountResponse] = await Promise.all([
      api.get(`/api/credit-grants/summary?customer_id=${customerId}`),
      api.get(`/api/meter-events/pending-amount?customer_id=${customerId}`),
      // api.get(`/api/credit-transactions/summary?customer_id=${customerId}`),
    ]);

    return {
      grants: grantsResponse.data,
      // transactions: transactionsResponse.data,
      pendingAmount: pendingAmountResponse.data,
    };
  } catch (error) {
    console.error('Failed to fetch credit summary:', error);
    return {
      grants: null,
      transactions: null,
      pendingAmount: null,
    };
  }
};

export default function CreditOverview({ customerId, settings, mode = 'portal' }: CreditOverviewProps) {
  const { t } = useLocaleContext();
  const [searchParams, setSearchParams] = useSearchParams();

  const getInitialTab = (): CreditTab => {
    const tabParam = searchParams.get('creditTab');
    if (tabParam && Object.values(CreditTab).includes(tabParam as CreditTab)) {
      return tabParam as CreditTab;
    }
    return CreditTab.OVERVIEW;
  };

  const [creditTab, setCreditTab] = useState<CreditTab>(getInitialTab);
  const conditionalSection = useConditionalSection();
  const [autoRecharge, setAutoRecharge] = useState({
    currencyId: '',
    open: false,
  });

  useEffect(() => {
    const tabParam = searchParams.get('creditTab');
    if (tabParam && Object.values(CreditTab).includes(tabParam as CreditTab)) {
      setCreditTab(tabParam as CreditTab);
    }
  }, [searchParams]);

  // Handle auto-recharge action from notification deep link
  useEffect(() => {
    const action = searchParams.get('action');
    const currencyId = searchParams.get('currencyId');
    if (action === 'auto-recharge' && currencyId) {
      setAutoRecharge({ currencyId, open: true });
      // Clean up query params after opening modal
      const newParams = new URLSearchParams(searchParams);
      newParams.delete('action');
      newParams.delete('currencyId');
      setSearchParams(newParams, { replace: true });
    }
  }, [searchParams, setSearchParams]);

  const creditCurrencies = useMemo(() => {
    return (
      settings?.paymentMethods
        ?.filter((method: any) => method.type === 'arcblock')
        ?.flatMap((method: any) => method.payment_currencies)
        ?.filter((currency: TPaymentCurrency) => {
          return currency.type === 'credit';
        }) || []
    );
  }, [settings]);

  const { data: creditSummary } = useRequest(fetchCreditSummary, {
    defaultParams: [customerId],
    refreshDeps: [creditTab === CreditTab.OVERVIEW],
    onSuccess: (data) => {
      const filteredCurrencies = creditCurrencies.filter((currency: TPaymentCurrency) => {
        return data.grants?.[currency.id];
      });
      conditionalSection?.hideRender(filteredCurrencies.length === 0);
    },
  });

  const handleRecharge = async (currency: TPaymentCurrency) => {
    try {
      const response = await api
        .get(`/api/payment-currencies/${currency.id}/recharge-config`)
        .then((res: any) => res.data);
      if (response.recharge_config && response.recharge_config.payment_url) {
        const url = new URL(response.recharge_config.payment_url);
        url.searchParams.set('redirect', window.location.href);
        window.open(url.toString(), '_self');
      } else {
        Toast.error(t('customer.recharge.unsupported'));
      }
    } catch (error) {
      console.error('Failed to fetch recharge config:', error);
      Toast.error(formatError(error));
    }
  };

  const handleAutoRecharge = (currency: TPaymentCurrency) => {
    setAutoRecharge({ currencyId: currency.id, open: true });
  };

  const handleTabChange = (newValue: CreditTab) => {
    setCreditTab(newValue);
    const newParams = new URLSearchParams(searchParams);
    if (newValue === CreditTab.OVERVIEW) {
      newParams.delete('creditTab');
    } else {
      newParams.set('creditTab', newValue);
    }
    setSearchParams(newParams);
  };

  // 渲染信用概览卡片
  const renderCreditOverviewCard = (currency: any) => {
    const method = settings?.paymentMethods?.find((m: any) => m.id === currency.payment_method_id);
    if (method?.type !== 'arcblock') {
      return null;
    }

    const currencyId = currency.id as string;
    const grantData = creditSummary?.grants?.[currencyId];
    const pendingAmount = creditSummary?.pendingAmount?.[currencyId] || '0';

    if (!grantData || grantData.meter?.status === 'inactive') {
      return null;
    }

    const showRecharge = grantData.paymentCurrency.recharge_config?.base_price_id && mode === 'portal';

    const totalAmount = grantData.totalAmount || '0';
    const remainingAmount = grantData.remainingAmount || '0';

    const cardTitle = grantData.meter?.name || currency.name;

    return (
      <Card
        key={currency.id}
        sx={{
          height: '100%',
          display: 'flex',
          flexDirection: 'column',
          border: '1px solid',
          borderColor: 'divider',
          boxShadow: 1,
          borderRadius: 1,
          backgroundColor: 'background.default',
        }}>
        <CardContent sx={{ flexGrow: 1 }}>
          <Stack spacing={2}>
            {/* 货币信息 */}

            <Stack
              direction="row"
              spacing={0.5}
              sx={{
                alignItems: 'center',
                justifyContent: 'space-between',
                borderBottom: '1px solid',
                borderColor: 'divider',
                pb: 2,
              }}>
              <Typography variant="h6" component="div">
                {cardTitle}
              </Typography>
              {showRecharge && (
                <SplitButton
                  variant="outlined"
                  size="small"
                  color="primary"
                  menu={[
                    <SplitButton.Item
                      key="autoRecharge"
                      onClick={() => handleAutoRecharge(currency)}
                      sx={{
                        color: 'primary.main',
                      }}>
                      <AutoModeOutlined fontSize="small" sx={{ mr: 0.5 }} />
                      <Typography variant="body2" className="recharge-title">
                        {t('customer.credit.autoRecharge')}
                      </Typography>
                    </SplitButton.Item>,
                  ]}>
                  <Button variant="text" color="primary" size="small" onClick={() => handleRecharge(currency)}>
                    <AddOutlined fontSize="small" />
                    <Typography variant="body2" className="recharge-title">
                      {t('customer.credit.recharge')}
                    </Typography>
                  </Button>
                </SplitButton>
              )}
            </Stack>

            {/* 可用额度（净余额 = 剩余 - 欠费） */}
            {(() => {
              const remaining = new BN(remainingAmount || '0');
              const pending = new BN(pendingAmount || '0');
              const netBalance = remaining.sub(pending);
              const isNegative = netBalance.isNeg();
              const absBalance = isNegative ? netBalance.abs().toString() : netBalance.toString();
              const formattedBalance =
                totalAmount === '0' && remainingAmount === '0' && pendingAmount === '0'
                  ? '0'
                  : formatCreditAmount(formatBNStr(absBalance, currency.decimal), currency.symbol, false);

              return (
                <Box sx={{ display: 'flex', justifyContent: 'space-between' }}>
                  <Typography
                    variant="body2"
                    gutterBottom
                    sx={{
                      color: 'text.secondary',
                    }}>
                    {t('admin.customer.creditGrants.creditBalance')}
                  </Typography>
                  <Typography
                    variant="h5"
                    component="div"
                    sx={{ fontWeight: 'normal', color: isNegative ? 'error.main' : 'text.primary' }}>
                    {isNegative ? `-${formattedBalance}` : formattedBalance}
                  </Typography>
                </Box>
              );
            })()}
          </Stack>
        </CardContent>
      </Card>
    );
  };

  const filteredCreditCurrencies = useMemo(() => {
    return creditCurrencies.filter((currency: TPaymentCurrency) => {
      const grantData = creditSummary?.grants?.[currency.id];
      if (!grantData) return false;
      return true;
    });
  }, [creditCurrencies, creditSummary?.grants]);

  return (
    <Stack sx={{ width: '100%' }}>
      <Tabs
        value={creditTab}
        onChange={(_, newValue) => handleTabChange(newValue as CreditTab)}
        sx={{
          flex: '1 0 auto',
          maxWidth: '100%',
          fontSize: 14,
          borderBottom: 1,
          borderColor: 'divider',
          '.Mui-selected': {
            fontSize: '14px !important',
            color: 'primary.main',
          },
        }}>
        <Tab label={t('admin.creditGrants.overview')} value={CreditTab.OVERVIEW} />
        <Tab label={t('admin.creditGrants.tab')} value={CreditTab.GRANTS} />
        <Tab label={t('admin.creditTransactions.tab')} value={CreditTab.TRANSACTIONS} />
      </Tabs>
      <Box className="section-body">
        {/* 概览标签页 */}
        {creditTab === CreditTab.OVERVIEW && (
          <Box sx={{ width: '100%', mt: 1 }} key={creditTab}>
            <Box
              sx={{
                display: 'grid',
                gridTemplateColumns: {
                  xs: 'repeat(1, 1fr)',
                  md: 'repeat(2, 1fr)',
                },
                gap: 2,
                '@container (max-width: 600px)': {
                  gridTemplateColumns: 'repeat(1, 1fr)',
                },
              }}>
              {filteredCreditCurrencies.map(renderCreditOverviewCard)}
            </Box>

            {filteredCreditCurrencies.length === 0 && (
              <Box
                sx={{
                  display: 'flex',
                  flexDirection: 'column',
                  alignItems: 'center',
                  justifyContent: 'center',
                  py: 8,
                  textAlign: 'center',
                }}>
                <Typography
                  variant="h6"
                  gutterBottom
                  sx={{
                    color: 'text.secondary',
                  }}>
                  {t('admin.customer.creditGrants.noGrants')}
                </Typography>
                <Typography
                  variant="body2"
                  sx={{
                    color: 'text.secondary',
                  }}>
                  {t('admin.customer.creditGrants.noGrantsDescription')}
                </Typography>
              </Box>
            )}
          </Box>
        )}
        {creditTab === CreditTab.GRANTS && <CreditGrantsList customer_id={customerId} mode={mode} key={creditTab} />}
        {creditTab === CreditTab.TRANSACTIONS && (
          <CreditTransactionsList customer_id={customerId} mode={mode} key={creditTab} includeGrants />
        )}
      </Box>
      {autoRecharge.open && (
        <AutoTopupModal
          open
          onClose={() => setAutoRecharge({ currencyId: '', open: false })}
          currencyId={autoRecharge.currencyId}
        />
      )}
    </Stack>
  );
}
