import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import {
  api,
  formatBNStr,
  formatError,
  formatTime,
  getCustomerAvatar,
  TxLink,
  SourceDataViewer,
  formatCreditAmount,
} from '@blocklet/payment-react';
import type { TCreditTransactionExpanded } from '@blocklet/payment-types';
import { ArrowBackOutlined } from '@mui/icons-material';
import { Alert, Avatar, Box, Button, Chip, CircularProgress, Divider, Stack, Typography } from '@mui/material';
import { useRequest } 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 { goBackOrFallback } from '../../../../../libs/util';
import EventList from '../../../../../components/event/list';

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

export default function AdminCreditTransactionDetail({ id }: { id: string }) {
  const { t } = useLocaleContext();
  const navigate = useNavigate();

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

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

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

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

  const getTransferStatusChip = (status: string | null | undefined) => {
    if (!status) return null;

    const statusConfig = {
      pending: { label: t('common.pending'), color: 'warning' as const },
      completed: { label: t('common.completed'), color: 'success' as const },
      failed: { label: t('common.failed'), color: 'error' as const },
    };

    const config = statusConfig[status as keyof typeof statusConfig] || {
      label: status,
      color: 'default' as const,
    };

    return <Chip label={config.label} size="small" color={config.color} />;
  };

  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.creditTransactions.title')}
            </Typography>
          </Stack>
          <Stack direction="row" spacing={1}>
            {data.creditGrant && (
              <Button
                variant="outlined"
                size="small"
                onClick={() => navigate(`/admin/customers/${data.credit_grant_id}`)}>
                {t('common.viewGrant')}
              </Button>
            )}
            {data.subscription && (
              <Button
                variant="outlined"
                size="small"
                onClick={() => navigate(`/admin/billing/${data.subscription_id}`)}>
                {t('common.viewSubscription')}
              </Button>
            )}
          </Stack>
        </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.description || t('common.creditTransaction')}
              </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.creditAmount')}
              value={
                <Stack direction="row" alignItems="center" spacing={0.5}>
                  <Typography variant="body2" sx={{ color: 'error.main' }}>
                    -
                    {formatCreditAmount(
                      formatBNStr(data.credit_amount, data.creditGrant?.paymentCurrency?.decimal || 0),
                      data.creditGrant?.paymentCurrency?.symbol || ''
                    )}
                  </Typography>
                </Stack>
              }
              divider={!!data.transfer_status}
            />
            {data.transfer_status && (
              <InfoMetric label={t('common.transferStatus')} value={getTransferStatusChip(data.transfer_status)} />
            )}
          </Stack>
        </Box>
        <Divider />
      </Box>

      <Stack
        sx={{
          flexDirection: {
            xs: 'column',
            lg: 'row',
          },
          gap: {
            xs: 2.5,
            md: 4,
          },
          '.transaction-column-1': {
            minWidth: {
              xs: '100%',
              lg: '600px',
            },
          },
          '.transaction-column-2': {
            width: {
              xs: '100%',
              md: '100%',
              lg: '320px',
            },
            maxWidth: {
              xs: '100%',
              md: '33%',
            },
          },
        }}>
        <Box flex={1} className="transaction-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.creditGrant')}
                value={
                  <Typography
                    component="span"
                    onClick={() => navigate(`/admin/customers/${data.credit_grant_id}`)}
                    sx={{ color: 'text.link', cursor: 'pointer' }}>
                    {data.creditGrant?.name || data.credit_grant_id}
                  </Typography>
                }
              />
              {data.meter && (
                <InfoRow
                  label={t('common.meterEvent')}
                  value={
                    <Typography
                      component="span"
                      onClick={() => navigate(`/admin/billing/${data.meter_id}`)}
                      sx={{ color: 'text.link', cursor: 'pointer' }}>
                      {data.meter.name || data.meter.event_name}
                    </Typography>
                  }
                />
              )}
              {data.subscription && (
                <InfoRow
                  label={t('admin.subscription.name')}
                  value={
                    <Typography
                      component="span"
                      onClick={() => navigate(`/admin/billing/${data.subscription_id}`)}
                      sx={{ color: 'text.link', cursor: 'pointer' }}>
                      {data.subscription.description || data.subscription_id}
                    </Typography>
                  }
                />
              )}
              {data.transfer_hash && data.paymentMethod && (
                <InfoRow
                  label={t('common.transferTxHash')}
                  value={
                    <TxLink
                      details={{ arcblock: { tx_hash: data.transfer_hash, payer: '' } }}
                      method={data.paymentMethod}
                      mode="dashboard"
                    />
                  }
                />
              )}
              <InfoRow
                label={t('admin.meterEvent.reportedAt')}
                value={formatTime(
                  data.meterEvent?.timestamp
                    ? data.meterEvent.timestamp * 1000
                    : data.meterEvent?.created_at || data.created_at
                )}
              />
              <InfoRow
                label={t('admin.meterEvent.processedAt')}
                value={formatTime(
                  data.meterEvent?.processed_at ? data.meterEvent.processed_at * 1000 : data.created_at
                )}
              />
            </InfoRowGroup>
          </Box>

          {data.meterEvent?.source_data && (
            <>
              <Divider />
              <Box className="section">
                <SectionHeader title={t('common.sourceData')} />
                <Box className="section-body">
                  <SourceDataViewer data={data.meterEvent.source_data} />
                </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="transaction-column-2" sx={{ gap: 2.5, display: 'flex', flexDirection: 'column' }}>
          <Box className="section">
            <SectionHeader title={t('common.metadata.label')} />
            <Box className="section-body">
              <MetadataList data={data.metadata} />
            </Box>
          </Box>
        </Box>
      </Stack>
    </Root>
  );
}

const Root = styled(Stack)``;
