/* eslint-disable react/no-unstable-nested-components */
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import Toast from '@arcblock/ux/lib/Toast';
import {
  api,
  formatError,
  formatTime,
  CreditTransactionsList,
  CreditStatusChip,
  getCustomerAvatar,
  TxLink,
  formatCreditAmount,
  formatBNStr,
} from '@blocklet/payment-react';
import type { TCreditGrantExpanded } from '@blocklet/payment-types';
import { ArrowBackOutlined } from '@mui/icons-material';
import { Alert, Avatar, Box, Button, CircularProgress, Divider, Stack, Typography } from '@mui/material';
import { useRequest, useSetState } from 'ahooks';
import { styled } from '@mui/system';
import { useCallback } from 'react';
import { useNavigate } from 'react-router-dom';

import InfoMetric from '../../../../../components/info-metric';
import InfoRow from '../../../../../components/info-row';
import InfoRowGroup from '../../../../../components/info-row-group';
import Copyable from '../../../../../components/copyable';
import SectionHeader from '../../../../../components/section/header';
import MetadataList from '../../../../../components/metadata/list';
import MetadataEditor from '../../../../../components/metadata/editor';
import CreditGrantItemList from '../../../../../components/customer/credit-grant-item-list';
import { goBackOrFallback } from '../../../../../libs/util';
import EventList from '../../../../../components/event/list';

const fetchData = (id: string | undefined): Promise<TCreditGrantExpanded> => {
  return api.get(`/api/credit-grants/${id}`).then((res: any) => res.data);
};

export default function AdminCreditGrantDetail({ id }: { id: string }) {
  const { t } = useLocaleContext();
  const navigate = useNavigate();
  const [state, setState] = useSetState({
    editing: {
      metadata: false,
      creditGrant: false,
    },
    loading: {
      metadata: false,
      creditGrant: false,
    },
  });

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

  const handleBack = useCallback(() => {
    goBackOrFallback('/admin/customers');
  }, []);

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

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

  const isDepleted = data?.status === 'depleted';

  const getStatusText = (status: string) => {
    switch (status) {
      case 'granted':
        return t('admin.customer.creditGrants.status.granted');
      case 'pending':
        return t('admin.customer.creditGrants.status.pending');
      case 'depleted':
        return t('admin.customer.creditGrants.status.depleted');
      case 'expired':
        return t('admin.customer.creditGrants.status.expired');
      case 'voided':
        return t('admin.customer.creditGrants.status.voided');
      default:
        return status;
    }
  };

  const getUsagePercentage = () => {
    if (!data.amount || !data.remaining_amount) return 0;
    const total = parseFloat(data.amount);
    const remaining = parseFloat(data.remaining_amount);
    return ((total - remaining) / total) * 100;
  };

  const onUpdateMetadata = async (updates: any) => {
    try {
      setState((prev) => ({ loading: { ...prev.loading, metadata: true } }));
      await api.put(`/api/credit-grants/${id}`, updates);
      Toast.success(t('common.saved'));
      runAsync();
    } catch (err) {
      console.error(err);
      Toast.error(formatError(err));
    } finally {
      setState((prev) => ({ loading: { ...prev.loading, metadata: false } }));
    }
  };

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

  return (
    <Root direction="column" spacing={2.5} sx={{ mb: 4 }}>
      <Box>
        <Stack className="page-header" direction="row" justifyContent="space-between" alignItems="center">
          <Stack
            direction="row"
            alignItems="center"
            sx={{ fontWeight: 'normal', cursor: 'pointer' }}
            onClick={handleBack}>
            <ArrowBackOutlined fontSize="small" sx={{ mr: 0.5, color: 'text.secondary' }} />
            <Typography variant="h6" sx={{ color: 'text.secondary', fontWeight: 'normal' }}>
              {t('admin.customer.creditGrants.title')}
            </Typography>
          </Stack>
          {data.metadata!.invoice_id && (
            <Button
              variant="outlined"
              size="small"
              onClick={() => navigate(`/admin/billing/${data.metadata!.invoice_id}`)}>
              {t('admin.customer.creditGrants.viewInvoice')}
            </Button>
          )}
        </Stack>

        <Box
          mt={4}
          mb={3}
          sx={{
            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" justifyContent="space-between" alignItems="center">
            <Stack direction="column" spacing={0.5}>
              <Typography variant="h2" sx={{ fontWeight: 600 }}>
                {data.name || `${t('admin.customer.creditGrants.grant')} ${data.id.slice(-8)}`}
              </Typography>
              <Copyable text={data.id} />
            </Stack>
          </Stack>

          <Stack
            className="section-body"
            justifyContent="flex-start"
            flexWrap="wrap"
            sx={{
              '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={<CreditStatusChip status={data.status} label={getStatusText(data.status)} />}
              divider
            />
            <InfoMetric
              label={t('admin.customer.creditGrants.originalAmount')}
              value={
                <Stack direction="row" alignItems="center" spacing={0.5}>
                  <Avatar
                    src={data.paymentCurrency?.logo}
                    sx={{ width: 16, height: 16 }}
                    alt={data.paymentCurrency?.symbol}
                  />
                  <Typography variant="body2" sx={{ color: 'text.secondary' }}>
                    {formatCreditAmount(
                      formatBNStr(data.amount, data.paymentCurrency.decimal),
                      data.paymentCurrency.symbol
                    )}
                  </Typography>
                </Stack>
              }
              divider
            />
            <InfoMetric
              label={t('common.remainingCredit')}
              value={
                <Stack direction="row" alignItems="center" spacing={0.5}>
                  <Avatar
                    src={data.paymentCurrency?.logo}
                    sx={{ width: 16, height: 16 }}
                    alt={data.paymentCurrency?.symbol}
                  />
                  <Typography variant="body2" color={isDepleted ? 'error.main' : 'text.secondary'}>
                    {formatCreditAmount(
                      formatBNStr(data.remaining_amount, data.paymentCurrency.decimal),
                      data.paymentCurrency.symbol
                    )}
                  </Typography>
                </Stack>
              }
              divider
            />
            <InfoMetric
              label={t('admin.customer.creditGrants.usage')}
              value={
                <Typography variant="body2" color={isDepleted ? 'error.main' : 'text.secondary'}>
                  {getUsagePercentage().toFixed(1)}%
                </Typography>
              }
            />
          </Stack>
        </Box>
        <Divider />
      </Box>

      <Stack
        sx={{
          flexDirection: {
            xs: 'column',
            lg: 'row',
          },
          gap: {
            xs: 2.5,
            md: 4,
          },
          '.credit-grant-column-1': {
            minWidth: {
              xs: '100%',
              lg: '600px',
            },
          },
          '.credit-grant-column-2': {
            width: {
              xs: '100%',
              md: '100%',
              lg: '320px',
            },
            maxWidth: {
              xs: '100%',
              md: '33%',
            },
          },
        }}>
        <Box flex={1} className="credit-grant-column-1" sx={{ 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',
                  },
                },
              }}>
              <InfoRow
                label={t('common.customer')}
                value={
                  <Stack direction="row" alignItems="center" spacing={1}>
                    <Avatar
                      src={getCustomerAvatar(
                        data.customer?.did,
                        data.customer?.updated_at ? new Date(data.customer.updated_at).toISOString() : '',
                        24
                      )}
                      alt={data.customer?.name}
                      sx={{ width: 24, height: 24 }}
                    />
                    <Typography>{data.customer?.name}</Typography>
                  </Stack>
                }
              />
              <InfoRow
                label={t('common.scope')}
                value={
                  <Typography>
                    {data.applicability_config?.scope?.prices ? t('common.specific') : t('common.general')}
                  </Typography>
                }
              />
              <InfoRow
                label={t('admin.creditProduct.priority.label')}
                value={<Typography>{data.priority}</Typography>}
              />
              <InfoRow label={t('common.createdAt')} value={formatTime(data.created_at)} />
              <InfoRow
                label={t('common.effectiveDate')}
                value={formatTime(data.effective_at ? data.effective_at * 1000 : data.created_at)}
              />
              {data.expires_at && (
                <InfoRow label={t('common.expirationDate')} value={formatTime(data.expires_at * 1000)} />
              )}
              {data.chain_detail?.mint?.hash && data.paymentMethod?.type === 'arcblock' && (
                <InfoRow
                  label={t('common.mintTxHash')}
                  value={
                    <TxLink
                      details={{ arcblock: { tx_hash: data.chain_detail.mint.hash, payer: '' } }}
                      method={data.paymentMethod}
                      mode="dashboard"
                    />
                  }
                />
              )}
            </InfoRowGroup>
          </Box>

          <Divider />

          {/* 适用范围 - 使用新的CreditGrantItemList组件 */}
          {data.items && data.items.length > 0 && (
            <>
              <Box className="section">
                <SectionHeader title={t('admin.creditProduct.associatedPrices.label')} />
                <Box className="section-body">
                  <CreditGrantItemList data={data.items} currency={data.paymentCurrency} mode="dashboard" />
                </Box>
              </Box>
              <Divider />
            </>
          )}

          {/* 交易记录 */}
          <Box className="section">
            <SectionHeader title={t('admin.creditTransactions.title')} />
            <Box className="section-body">
              <CreditTransactionsList
                customer_id={data.customer_id}
                credit_grant_id={data.id}
                showAdminColumns
                showTimeFilter
                mode="dashboard"
              />
            </Box>
          </Box>

          <Divider />
          <Box className="section">
            <SectionHeader title={t('admin.events.title')} />
            <Box className="section-body">
              <EventList features={{ toolbar: false }} object_id={data.id} />
            </Box>
          </Box>
        </Box>

        <Box className="credit-grant-column-2" sx={{ gap: 2.5, display: 'flex', flexDirection: 'column' }}>
          {/* 元数据 */}
          <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)``;
