/* eslint-disable react/no-unstable-nested-components */
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import { api, formatTime, useMobile, CreditTransactionsList, formatBNStr } from '@blocklet/payment-react';
import type { TMeterEventExpanded } from '@blocklet/payment-types';
import { ArrowBackOutlined, InfoOutlined } from '@mui/icons-material';
import { Alert, Box, CircularProgress, Divider, Stack, Typography, Chip, Tooltip } from '@mui/material';
import { styled } from '@mui/system';
import { useRequest } from 'ahooks';

import { Link } from 'react-router-dom';
import Copyable from '../../../../components/copyable';
import CustomerLink from '../../../../components/customer/link';
import EventList from '../../../../components/event/list';
import InfoRow from '../../../../components/info-row';
import InfoMetric from '../../../../components/info-metric';
import SectionHeader from '../../../../components/section/header';
import { goBackOrFallback } from '../../../../libs/util';
import InfoRowGroup from '../../../../components/info-row-group';
import MetadataList from '../../../../components/metadata/list';

const fetchData = (id: string): Promise<TMeterEventExpanded> => {
  return api.get(`/api/meter-events/${id}`).then((res: any) => res.data);
};

export default function MeterEventDetail(props: { id: string }) {
  const { t } = useLocaleContext();
  const { isMobile } = useMobile();

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

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

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

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'pending':
        return 'info';
      case 'requires_action':
        return 'warning';
      case 'requires_capture':
        return 'warning';
      case 'completed':
        return 'success';
      case 'processing':
        return 'info';
      default:
        return 'default';
    }
  };

  return (
    <Root direction="column" spacing={2.5} sx={{ mb: 4 }}>
      <Box>
        <Stack
          className="page-header"
          direction="row"
          sx={{
            justifyContent: 'space-between',
            alignItems: 'center',
          }}>
          <Stack
            direction="row"
            onClick={() => goBackOrFallback('/admin/billing/meters')}
            sx={{
              alignItems: 'center',
              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.meterEvents.title')}
            </Typography>
          </Stack>
        </Stack>
        <Box
          sx={{
            mt: 4,
            mb: 3,
            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="column"
            sx={{
              gap: 1,
            }}>
            <Copyable text={props.id} />
          </Stack>

          <Stack
            className="section-body"
            sx={{
              justifyContent: 'flex-start',
              flexWrap: 'wrap',

              '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={<Chip label={data.status} color={getStatusColor(data.status)} size="small" />}
              divider
            />
            <InfoMetric
              label={t('common.meterEvent')}
              value={
                <Link to={`/admin/billing/meters/${data.meter.id}`} style={{ color: 'inherit' }}>
                  <Typography sx={{ color: 'text.link' }}>{data.meter.event_name}</Typography>
                </Link>
              }
              divider
            />
            {data.subscription && (
              <InfoMetric
                label={t('common.subscription')}
                value={
                  <Link to={`/admin/billing/${data.subscription.id}`} style={{ color: 'inherit' }}>
                    <Typography sx={{ color: 'text.link' }}>
                      {data.subscription.description || data.subscription.id}
                    </Typography>
                  </Link>
                }
                divider
              />
            )}
            <InfoMetric
              label={t('admin.meterEvent.creditConsumed')}
              value={`${formatBNStr(data.credit_consumed, data.paymentCurrency?.decimal)} ${data.paymentCurrency?.symbol}`}
              divider
            />
            {data.credit_pending !== '0' && (
              <InfoMetric
                label={t('admin.customer.creditGrants.pendingAmount')}
                value={
                  <Typography sx={{ color: 'error.main' }}>
                    {`${formatBNStr(data.credit_pending, data.paymentCurrency?.decimal)} ${data.paymentCurrency?.symbol}`}
                  </Typography>
                }
                divider
              />
            )}
          </Stack>
        </Box>
        <Divider />
      </Box>
      <Stack
        sx={{
          flexDirection: {
            xs: 'column',
            lg: 'row',
          },
          gap: {
            xs: 2.5,
            md: 4,
          },
          '.meter-event-column-1': {
            minWidth: {
              xs: '100%',
              lg: '600px',
            },
          },
          '.meter-event-column-2': {
            width: {
              xs: '100%',
              md: '100%',
              lg: '320px',
            },
            maxWidth: {
              xs: '100%',
              md: '33%',
            },
          },
        }}>
        <Box
          className="meter-event-column-1"
          sx={{
            flex: 1,
            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',
                  },
                },
                '.currency-name': {
                  color: 'text.secondary',
                },
              }}>
              <InfoRow
                label={t('admin.meterEvent.usageValue')}
                value={`${formatBNStr(data.payload.value, data.paymentCurrency?.decimal)} ${data.paymentCurrency?.symbol}`}
              />
              <InfoRow label={t('admin.meterEvent.reportedAt')} value={formatTime(data.timestamp * 1000)} />
              <InfoRow
                label={t('common.customer')}
                value={<CustomerLink customer={data.customer} size={isMobile ? 'default' : 'small'} />}
              />
              <InfoRow label={t('common.createdAt')} value={formatTime(data.created_at)} />
              <InfoRow
                label={t('common.status')}
                value={
                  <Stack
                    direction="row"
                    spacing={1}
                    sx={{
                      alignItems: 'center',
                    }}>
                    <Chip
                      label={data.status}
                      color={getStatusColor(data.status)}
                      size="small"
                      sx={{ textTransform: 'capitalize' }}
                    />
                    {data.metadata?.last_error && (
                      <Tooltip
                        title={
                          <pre style={{ whiteSpace: 'break-spaces' }}>
                            {JSON.stringify(
                              {
                                error: data.metadata.last_error,
                                failed_at: data.metadata.failed_at
                                  ? formatTime(data.metadata.failed_at * 1000)
                                  : undefined,
                                attempt_count: data.attempt_count,
                                next_attempt: data.next_attempt ? formatTime(data.next_attempt * 1000) : undefined,
                              },
                              null,
                              2
                            )}
                          </pre>
                        }>
                        <InfoOutlined fontSize="small" color="error" />
                      </Tooltip>
                    )}
                  </Stack>
                }
              />
            </InfoRowGroup>
          </Box>

          <Divider />

          <Box className="section">
            <Typography variant="h3" className="section-header">
              {t('admin.creditTransactions.title')}
            </Typography>
            <Box className="section-body">
              <CreditTransactionsList
                customer_id={data.payload.customer_id}
                source={data.id}
                showAdminColumns
                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>

        {isMobile && <Divider />}

        <Box className="meter-event-column-2" sx={{ gap: 2.5, display: 'flex', flexDirection: 'column' }}>
          {data.metadata && Object.keys(data.metadata).length > 0 && (
            <Box className="section">
              <SectionHeader title={t('common.metadata.label')} />
              <Box className="section-body">
                <MetadataList data={data.metadata} handleEditMetadata={() => {}} />
              </Box>
            </Box>
          )}
        </Box>
      </Stack>
    </Root>
  );
}

const Root = styled(Stack)``;
