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

import Copyable from '../../../../components/copyable';
import InfoMetric from '../../../../components/info-metric';
import SectionHeader from '../../../../components/section/header';
import WebhookAttempts from '../../../../components/webhook/attempts';
import { getWebhookStatusColor, goBackOrFallback } from '../../../../libs/util';

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

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

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

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

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

  return (
    <Root direction="column" spacing={4} sx={{ mb: 4 }}>
      <Box>
        <Stack
          className="page-header"
          direction="row"
          sx={{
            justifyContent: 'space-between',
            alignItems: 'center',
          }}>
          <Stack
            direction="row"
            onClick={() => goBackOrFallback('/admin/developers/webhooks')}
            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.webhooks')}
            </Typography>
          </Stack>
          <Copyable text={props.id} style={{ marginLeft: 4 }} />
        </Stack>
        <Box
          sx={{
            mt: 2,
          }}>
          <Stack
            direction="row"
            sx={{
              justifyContent: 'space-between',
              alignItems: 'center',
            }}>
            <Stack
              direction="column"
              sx={{
                alignItems: 'flex-start',
              }}>
              <Typography variant="h5">{data.url}</Typography>
              <Typography
                variant="body1"
                sx={{
                  color: 'text.secondary',
                }}>
                {data.description}
              </Typography>
            </Stack>
          </Stack>
          <Stack
            className="section-body"
            direction="row"
            spacing={3}
            sx={{
              justifyContent: 'flex-start',
              flexWrap: 'wrap',
              pt: 2,
              mt: 2,
              borderTop: '1px solid',
              borderColor: 'divider',
            }}>
            <InfoMetric
              label={t('common.status')}
              value={<Status label={data.status} color={getWebhookStatusColor(data.status)} />}
              divider
            />
            <InfoMetric
              label={t('admin.webhookEndpoint.listen')}
              value={
                <Tooltip
                  arrow
                  title={
                    <ul style={{ padding: 0, margin: 0 }}>
                      {data.enabled_events.map((x) => (
                        <li key={x} style={{ fontSize: '0.7875rem' }}>
                          {x}
                        </li>
                      ))}
                    </ul>
                  }>
                  <Typography sx={{ backgroundColor: 'grey.100', paddingX: 0.5, borderRadius: 0.5 }}>
                    {data.enabled_events.length} events
                  </Typography>
                </Tooltip>
              }
              divider
            />
            <InfoMetric label={t('admin.webhookEndpoint.version')} value={data.api_version} divider />
            <InfoMetric label={t('common.createdAt')} value={formatTime(data.created_at)} divider />
            <InfoMetric label={t('common.updatedAt')} value={formatTime(data.updated_at)} />
          </Stack>
        </Box>
      </Box>
      <Box className="section">
        <SectionHeader title={t('admin.webhookEndpoint.attempts')} mb={0} />
        <Box className="section-body">
          <WebhookAttempts webhook_endpoint_id={data.id} />
        </Box>
      </Box>
    </Root>
  );
}

const Root = styled(Stack)``;
