import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import { formatTime } from '@blocklet/payment-react';
import { LockClockOutlined, TrendingUpOutlined } from '@mui/icons-material';
import { Box, Chip, Paper, Stack, Tooltip, Typography } from '@mui/material';

import Copyable from '../copyable';
import InfoRow from '../info-row';

interface QuoteMetadata {
  calculation?: {
    token_amount_raw?: string;
    unit_amount_raw?: string;
  };
  rounding?: {
    mode?: string;
    token_decimals?: number;
  };
  risk?: {
    anomaly_detected?: boolean;
    deviation_percent?: number;
    degraded?: boolean;
    degraded_reason?: string | null;
  };
  context?: Record<string, any>;
}

interface PriceQuote {
  id: string;
  price_id: string;
  base_currency: string;
  base_amount: string;
  target_currency_id: string;
  rate_currency_symbol: string;
  exchange_rate: string;
  quoted_amount: string;
  rate_provider_id: string;
  rate_provider_name: string;
  rate_timestamp_ms: number;
  expires_at: number;
  status: 'active' | 'used' | 'paid' | 'expired' | 'cancelled' | 'failed';
  metadata: QuoteMetadata | null;
  created_at: string;
}

interface QuoteInfoProps {
  quotes: PriceQuote[];
}

const getStatusColor = (status: string) => {
  switch (status) {
    case 'paid':
      return 'success';
    case 'used':
      return 'primary';
    case 'active':
      return 'info';
    case 'expired':
    case 'cancelled':
    case 'failed':
      return 'error';
    default:
      return 'default';
  }
};

export default function QuoteInfo({ quotes }: QuoteInfoProps) {
  const { t } = useLocaleContext();

  if (!quotes || quotes.length === 0) {
    return (
      <Typography variant="body2" color="text.secondary">
        {t('admin.quote.noQuotes')}
      </Typography>
    );
  }

  return (
    <Stack spacing={2}>
      {quotes.map((quote) => (
        <Paper key={quote.id} variant="outlined" sx={{ p: 2 }}>
          <Stack spacing={2}>
            {/* Header */}
            <Stack direction="row" justifyContent="space-between" alignItems="center">
              <Stack direction="row" spacing={1} alignItems="center">
                <LockClockOutlined fontSize="small" color="primary" />
                <Typography variant="subtitle2" fontWeight={600}>
                  {t('admin.quote.title')}
                </Typography>
              </Stack>
              <Chip label={t(`admin.quote.status.${quote.status}`)} color={getStatusColor(quote.status)} size="small" />
            </Stack>

            {/* Quote ID */}
            <InfoRow
              label={t('admin.quote.id')}
              value={<Copyable text={quote.id} />}
              direction="row"
              alignItems="center"
            />

            {/* Pricing Details */}
            <Box>
              <Typography variant="caption" color="text.secondary" gutterBottom>
                {t('admin.quote.pricingDetails')}
              </Typography>
              <Stack spacing={1} sx={{ mt: 1 }}>
                <InfoRow
                  label={t('admin.quote.baseAmount')}
                  value={
                    <Typography variant="body2">
                      {quote.base_amount} {quote.base_currency}
                    </Typography>
                  }
                  direction="row"
                  alignItems="center"
                />
                <InfoRow
                  label={t('admin.quote.exchangeRate')}
                  value={
                    <Stack direction="row" spacing={0.5} alignItems="center">
                      <Typography variant="body2">
                        1 {quote.rate_currency_symbol} = {quote.exchange_rate} {quote.base_currency}
                      </Typography>
                      {quote.metadata?.risk?.degraded && (
                        <Tooltip title={quote.metadata.risk.degraded_reason || ''}>
                          <Chip label={t('admin.quote.degraded')} color="warning" size="small" variant="outlined" />
                        </Tooltip>
                      )}
                    </Stack>
                  }
                  direction="row"
                  alignItems="center"
                />
                <InfoRow
                  label={t('admin.quote.quotedAmount')}
                  value={
                    <Typography variant="body2" fontWeight={500}>
                      {quote.metadata?.calculation?.token_amount_raw || '-'} {quote.rate_currency_symbol}
                    </Typography>
                  }
                  direction="row"
                  alignItems="center"
                />
              </Stack>
            </Box>

            {/* Rate Provider Info */}
            <Box>
              <Typography variant="caption" color="text.secondary" gutterBottom>
                {t('admin.quote.providerInfo')}
              </Typography>
              <Stack spacing={1} sx={{ mt: 1 }}>
                <InfoRow
                  label={t('admin.quote.provider')}
                  value={<Typography variant="body2">{quote.rate_provider_name}</Typography>}
                  direction="row"
                  alignItems="center"
                />
                <InfoRow
                  label={t('admin.quote.rateTimestamp')}
                  value={
                    <Tooltip title={formatTime(quote.rate_timestamp_ms)}>
                      <Typography variant="body2" color="text.secondary">
                        {formatTime(quote.rate_timestamp_ms, 'relative')}
                      </Typography>
                    </Tooltip>
                  }
                  direction="row"
                  alignItems="center"
                />
              </Stack>
            </Box>

            {/* Lifecycle */}
            <Box>
              <Typography variant="caption" color="text.secondary" gutterBottom>
                {t('admin.quote.lifecycle')}
              </Typography>
              <Stack spacing={1} sx={{ mt: 1 }}>
                <InfoRow
                  label={t('common.createdAt')}
                  value={
                    <Typography variant="body2" color="text.secondary">
                      {formatTime(quote.created_at)}
                    </Typography>
                  }
                  direction="row"
                  alignItems="center"
                />
                <InfoRow
                  label={t('admin.quote.expiresAt')}
                  value={
                    <Typography variant="body2" color="text.secondary">
                      {formatTime(quote.expires_at * 1000)}
                    </Typography>
                  }
                  direction="row"
                  alignItems="center"
                />
              </Stack>
            </Box>

            {/* Risk Information */}
            {quote.metadata?.risk && (
              <Box>
                <Typography variant="caption" color="text.secondary" gutterBottom>
                  {t('admin.quote.riskInfo')}
                </Typography>
                <Stack spacing={1} sx={{ mt: 1 }}>
                  {quote.metadata.risk.deviation_percent !== undefined && (
                    <InfoRow
                      label={t('admin.quote.deviation')}
                      value={
                        <Stack direction="row" spacing={0.5} alignItems="center">
                          <TrendingUpOutlined fontSize="small" />
                          <Typography variant="body2">{quote.metadata.risk.deviation_percent.toFixed(2)}%</Typography>
                        </Stack>
                      }
                      direction="row"
                      alignItems="center"
                    />
                  )}
                  {quote.metadata.risk.anomaly_detected && (
                    <Chip label={t('admin.quote.anomalyDetected')} color="warning" size="small" variant="outlined" />
                  )}
                </Stack>
              </Box>
            )}
          </Stack>
        </Paper>
      ))}
    </Stack>
  );
}
