import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import { api } from '@blocklet/payment-react';
import { Box, Typography, Chip, Stack, Card, CardContent } from '@mui/material';
import { styled } from '@mui/system';
import { useRequest } from 'ahooks';
import CustomerLink from '../../../../components/customer/link';

interface VerificationConfigProps {
  data: {
    verification_type: string;
    nft_config?: {
      nft_addresses?: string[];
      nft_tags?: string[];
      min_balance?: number | string;
    };
    vc_config?: {
      vc_roles?: string[];
      vc_trusted_issuers?: string[];
    };
    customer_dids?: string[];
  };
}

const fetchCustomers = (): Promise<{ list: any[]; count: number }> => {
  return api.get('/api/customers?limit=1000').then((res: any) => res.data);
};

export default function VerificationConfig({ data }: VerificationConfigProps) {
  const { t } = useLocaleContext();

  const { data: customersData } = useRequest(fetchCustomers, {
    ready: data.verification_type === 'user_restricted' && (data.customer_dids?.length ?? 0) > 0,
  });

  const customers = customersData?.list || [];

  const renderNftConfig = () => {
    if (!data.nft_config) {
      return (
        <Typography
          variant="body2"
          sx={{
            color: 'text.secondary',
          }}>
          {t('admin.promotionCode.noNftConfig')}
        </Typography>
      );
    }

    return (
      <Stack spacing={2}>
        {data.nft_config.nft_addresses && data.nft_config.nft_addresses.length > 0 && (
          <ConfigItem>
            <ConfigLabel>{t('admin.promotionCode.nftAddresses')}</ConfigLabel>
            <ChipContainer>
              {data.nft_config.nft_addresses.map((addr: string) => (
                <Chip
                  key={addr}
                  label={addr}
                  size="small"
                  variant="outlined"
                  color="default"
                  sx={{
                    backgroundColor: 'grey.50',
                    borderColor: 'grey.300',
                    fontFamily: 'monospace',
                    fontSize: '0.75rem',
                    maxWidth: 200,
                  }}
                />
              ))}
            </ChipContainer>
          </ConfigItem>
        )}
        {data.nft_config.nft_tags && data.nft_config.nft_tags.length > 0 && (
          <ConfigItem>
            <ConfigLabel>{t('admin.promotionCode.nftTags')}</ConfigLabel>
            <ChipContainer>
              {data.nft_config.nft_tags.map((tag: string) => (
                <Chip
                  key={tag}
                  label={tag}
                  size="small"
                  variant="outlined"
                  color="primary"
                  sx={{
                    backgroundColor: 'primary.50',
                    fontWeight: 500,
                  }}
                />
              ))}
            </ChipContainer>
          </ConfigItem>
        )}
        {data.nft_config.min_balance && (
          <ConfigItem>
            <ConfigLabel>{t('admin.promotionCode.minBalance')}</ConfigLabel>
            <Typography
              variant="body2"
              sx={{
                fontWeight: 'medium',
              }}>
              {data.nft_config.min_balance}
            </Typography>
          </ConfigItem>
        )}
      </Stack>
    );
  };

  const renderVcConfig = () => {
    if (!data.vc_config) {
      return (
        <Typography
          variant="body2"
          sx={{
            color: 'text.secondary',
          }}>
          {t('admin.promotionCode.noVcConfig')}
        </Typography>
      );
    }

    return (
      <Stack spacing={2}>
        {data.vc_config.vc_roles && data.vc_config.vc_roles.length > 0 && (
          <ConfigItem>
            <ConfigLabel>{t('admin.promotionCode.requiredRoles')}</ConfigLabel>
            <ChipContainer>
              {data.vc_config.vc_roles.map((role: string) => (
                <Chip
                  key={role}
                  label={role}
                  size="small"
                  variant="outlined"
                  color="secondary"
                  sx={{
                    backgroundColor: 'secondary.50',
                    fontWeight: 500,
                    textTransform: 'capitalize',
                  }}
                />
              ))}
            </ChipContainer>
          </ConfigItem>
        )}

        {data.vc_config.vc_trusted_issuers && data.vc_config.vc_trusted_issuers.length > 0 && (
          <ConfigItem>
            <ConfigLabel>{t('admin.promotionCode.trustedIssuers')}</ConfigLabel>
            <ChipContainer>
              {data.vc_config.vc_trusted_issuers.map((issuer: string) => (
                <Chip
                  key={issuer}
                  label={issuer}
                  size="small"
                  variant="outlined"
                  color="info"
                  sx={{
                    backgroundColor: 'info.50',
                    fontFamily: 'monospace',
                    fontSize: '0.75rem',
                    maxWidth: 200,
                  }}
                />
              ))}
            </ChipContainer>
          </ConfigItem>
        )}
      </Stack>
    );
  };

  const renderUserRestrictedConfig = () => {
    if (!data.customer_dids?.length) {
      return (
        <Typography
          variant="body2"
          sx={{
            color: 'text.secondary',
          }}>
          {t('admin.promotionCode.noUsersSpecified')}
        </Typography>
      );
    }

    return (
      <ConfigItem>
        <ConfigLabel>{t('admin.promotionCode.allowedUsers')}</ConfigLabel>
        <UserListContainer>
          {data.customer_dids.map((did: string) => {
            const customer = customers.find((c: any) => c.did === did || c.id === did);
            if (customer) {
              return (
                <CustomerLink
                  key={did}
                  customer={customer}
                  size="small"
                  cardProps={{
                    sx: {
                      border: 'none',
                      p: 0,
                      minWidth: 0,
                    },
                  }}
                />
              );
            }
            // 如果找不到客户信息，显示 DID
            return (
              <Chip
                key={did}
                label={did}
                size="small"
                variant="outlined"
                color="default"
                sx={{
                  maxWidth: 200,
                  backgroundColor: 'grey.50',
                  borderColor: 'grey.300',
                }}
              />
            );
          })}
        </UserListContainer>
      </ConfigItem>
    );
  };

  const renderConfig = () => {
    switch (data.verification_type) {
      case 'nft':
        return renderNftConfig();
      case 'vc':
        return renderVcConfig();
      case 'user_restricted':
        return renderUserRestrictedConfig();
      case 'code':
      default:
        return (
          <Typography
            variant="body2"
            sx={{
              color: 'text.secondary',
              fontStyle: 'italic',
            }}>
            {t('admin.promotionCode.codeVerificationOnly')}
          </Typography>
        );
    }
  };

  return (
    <VerificationCard>
      <CardContent>
        <Stack spacing={2}>
          <Box
            sx={{
              display: 'flex',
              flexDirection: {
                xs: 'column',
                sm: 'row',
              },
              gap: {
                xs: 1,
                sm: 2,
              },
              alignItems: {
                xs: 'flex-start',
                sm: 'center',
              },
            }}>
            <Typography
              variant="caption"
              sx={{
                color: 'text.secondary',
              }}>
              {t('admin.promotionCode.verificationType')}
            </Typography>
            <Typography
              variant="subtitle2"
              sx={{
                color: 'text.primary',
                fontWeight: 'medium',
              }}>
              {t(`admin.promotionCode.verificationTypeMap.${data.verification_type}`)}
            </Typography>
          </Box>
          {renderConfig()}
        </Stack>
      </CardContent>
    </VerificationCard>
  );
}

const VerificationCard = styled(Card)(({ theme }) => ({
  border: `1px solid ${theme.palette.divider}`,
  boxShadow: 'none',
  backgroundColor: theme.palette.background.paper,
}));

const ConfigItem = styled(Box)({
  display: 'flex',
  flexDirection: 'column',
  gap: 8,
});

const ConfigLabel = styled(Typography)(({ theme }) => ({
  fontSize: '0.875rem',
  fontWeight: 500,
  color: theme.palette.text.secondary,
}));

const ChipContainer = styled(Box)({
  display: 'flex',
  flexDirection: 'row',
  flexWrap: 'wrap',
  gap: 8,
});

const UserListContainer = styled(Box)({
  display: 'flex',
  flexDirection: 'row',
  flexWrap: 'wrap',
  gap: 8,
  alignItems: 'center',
});
