import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import {
  api,
  formatTime,
  getCustomerAvatar,
  TxLink,
  SourceDataViewer,
  formatCreditAmount,
  formatBNStr,
} 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 { useNavigate, useParams } from 'react-router-dom';
import { styled } from '@mui/system';
import { useCallback } from 'react';
import InfoMetric from '../../../components/info-metric';
import { useSessionContext } from '../../../contexts/session';
import SectionHeader from '../../../components/section/header';
import InfoRow from '../../../components/info-row';
import InfoRowGroup from '../../../components/info-row-group';
import { useArcsphere } from '../../../hooks/browser';

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

export default function CustomerCreditTransactionDetail() {
  const { id } = useParams() as { id: string };
  const navigate = useNavigate();
  const { t } = useLocaleContext();
  const { session } = useSessionContext();
  const inArcsphere = useArcsphere();
  const { loading, error, data } = useRequest(() => fetchData(id));

  const handleBack = useCallback(() => {
    navigate('/customer', { replace: true });
  }, [navigate]);

  if (data?.customer?.did && session?.user?.did && data.customer.did !== session.user.did) {
    return <Alert severity="error">{t('common.accessDenied')}</Alert>;
  }

  if (error) {
    return <Alert severity="error">{error.message}</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>
      <Box>
        <Stack
          className="page-header"
          direction="row"
          justifyContent="space-between"
          alignItems="center"
          sx={{ position: 'relative' }}>
          {!inArcsphere ? (
            <Stack
              direction="row"
              onClick={handleBack}
              alignItems="center"
              sx={{ fontWeight: 'normal', cursor: 'pointer' }}>
              <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>
          ) : (
            <Box />
          )}
          <Stack direction="row" spacing={1}>
            {data.creditGrant && (
              <Button
                variant="outlined"
                size="small"
                onClick={() => navigate(`/customer/credit-grant/${data.credit_grant_id}`)}>
                {t('common.viewGrant')}
              </Button>
            )}
            {data.subscription && (
              <Button
                variant="outlined"
                size="small"
                onClick={() => navigate(`/customer/subscription/${data.subscription_id}`)}>
                {t('common.viewSubscription')}
              </Button>
            )}
          </Stack>
        </Stack>

        <Box
          mt={4}
          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" alignItems="flex-start" justifyContent="space-around">
              <Typography variant="h2" color="text.primary">
                {data.description || t('common.creditTransaction')}
              </Typography>
              <Typography variant="body2" color="text.secondary" sx={{ mt: 0.5 }}>
                {data.id}
              </Typography>
            </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 && (
              <InfoMetric
                label={t('common.transferStatus')}
                value={getTransferStatusChip(data.transfer_status)}
                divider
              />
            )}
            <InfoMetric label={t('common.createdAt')} value={formatTime(data.created_at)} />
          </Stack>
        </Box>
      </Box>

      <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(`/customer/credit-grant/${data.credit_grant_id}`)}
                sx={{ color: 'text.link', cursor: 'pointer' }}>
                {data.creditGrant?.name || data.credit_grant_id}
              </Typography>
            }
          />
          {data.subscription && (
            <InfoRow
              label={t('admin.subscription.name')}
              value={
                <Typography
                  component="span"
                  onClick={() => navigate(`/customer/subscription/${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="customer"
                />
              }
            />
          )}
          <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>
        </>
      )}
    </Root>
  );
}

const Root = styled(Stack)`
  margin-bottom: 24px;
  gap: 24px;
  flex-direction: column;
  @media (max-width: ${({ theme }) => theme.breakpoints.values.md}px) {
    .section-header {
      font-size: 18px;
    }
  }
`;
