import { Box, Button, Stack, Typography } from '@mui/material';
import { alpha, useTheme } from '@mui/material/styles';
import ArrowBackIcon from '@mui/icons-material/ArrowBack';
import Header from '@blocklet/ui-react/lib/Header';
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import { primaryContrastColor } from '../utils/format';

interface ErrorViewProps {
  error: string;
  errorCode?: 'SESSION_EXPIRED' | 'EMPTY_LINE_ITEMS' | 'STOP_ACCEPTING_ORDERS' | null;
  mode?: string;
}

// Geometric decoration — organic blobs with embedded wireframe mesh
function GeometricDecoration() {
  const theme = useTheme();
  const gridColor = alpha(theme.palette.primary.main, 0.06);

  return (
    <Box
      sx={{
        position: 'relative',
        width: { xs: 200, md: 260 },
        height: { xs: 200, md: 260 },
        mb: { xs: 4, md: 6 },
      }}>
      {/* Blob layer 1 */}
      <Box
        sx={{
          position: 'absolute',
          inset: 0,
          borderRadius: '38% 62% 63% 37% / 41% 44% 56% 59%',
          background: (t) =>
            `linear-gradient(45deg, ${alpha(t.palette.primary.main, 0.1)}, ${alpha(t.palette.primary.main, 0.03)})`,
          filter: 'blur(1px)',
          animation: 'spin 20s linear infinite',
          '@keyframes spin': { from: { transform: 'rotate(0deg)' }, to: { transform: 'rotate(360deg)' } },
        }}
      />
      {/* Blob layer 2 */}
      <Box
        sx={{
          position: 'absolute',
          inset: 0,
          borderRadius: '38% 62% 63% 37% / 41% 44% 56% 59%',
          background: (t) =>
            `linear-gradient(135deg, ${alpha(t.palette.primary.main, 0.07)}, ${alpha(t.palette.primary.main, 0.01)})`,
          filter: 'blur(1px)',
          transform: 'scale(0.88)',
          opacity: 0.6,
          animation: 'spinReverse 15s linear infinite',
          '@keyframes spinReverse': {
            from: { transform: 'scale(0.88) rotate(0deg)' },
            to: { transform: 'scale(0.88) rotate(-360deg)' },
          },
        }}
      />
      {/* Wireframe mesh overlay — clipped to blob shape */}
      <Box
        sx={{
          position: 'absolute',
          inset: 0,
          borderRadius: '38% 62% 63% 37% / 41% 44% 56% 59%',
          overflow: 'hidden',
          animation: 'spin 20s linear infinite',
        }}>
        <svg
          width="100%"
          height="100%"
          viewBox="0 0 260 260"
          fill="none"
          xmlns="http://www.w3.org/2000/svg"
          style={{ position: 'absolute', inset: 0 }}>
          {/* Horizontal lines */}
          {[52, 87, 122, 157, 192].map((y) => (
            <line key={`h${y}`} x1="30" y1={y} x2="230" y2={y} stroke={gridColor} strokeWidth="0.5" />
          ))}
          {/* Vertical lines */}
          {[52, 87, 122, 157, 192].map((x) => (
            <line key={`v${x}`} x1={x} y1="30" x2={x} y2="230" stroke={gridColor} strokeWidth="0.5" />
          ))}
          {/* Diagonal accents — sparse, adds depth */}
          <line x1="52" y1="52" x2="192" y2="192" stroke={gridColor} strokeWidth="0.5" />
          <line x1="192" y1="52" x2="52" y2="192" stroke={gridColor} strokeWidth="0.5" />
          {/* Concentric circles — digital radar feel */}
          <circle cx="130" cy="130" r="40" stroke={gridColor} strokeWidth="0.5" />
          <circle cx="130" cy="130" r="75" stroke={gridColor} strokeWidth="0.5" />
          {/* Dot nodes at key intersections */}
          {[
            [122, 87],
            [157, 87],
            [87, 122],
            [122, 122],
            [157, 122],
            [192, 122],
            [87, 157],
            [122, 157],
            [157, 157],
            [122, 192],
            [157, 192],
          ].map(([cx, cy]) => (
            <circle key={`d${cx}-${cy}`} cx={cx} cy={cy} r="1.5" fill={gridColor} />
          ))}
        </svg>
      </Box>
    </Box>
  );
}

function getErrorConfig(
  errorCode: ErrorViewProps['errorCode'],
  error: string,
  t: (key: string) => string
): { title: string; description: string; color: string } {
  if (errorCode === 'SESSION_EXPIRED') {
    return {
      title: t('payment.checkout.expired.title'),
      description: t('payment.checkout.expired.description'),
      color: '#f59e0b',
    };
  }

  if (errorCode === 'EMPTY_LINE_ITEMS') {
    return {
      title: t('payment.checkout.emptyItems.title'),
      description: t('payment.checkout.emptyItems.description'),
      color: '#94a3b8',
    };
  }

  if (errorCode === 'STOP_ACCEPTING_ORDERS') {
    return {
      title: t('payment.checkout.stopAcceptingOrders.title'),
      description: t('payment.checkout.stopAcceptingOrders.description'),
      color: '#f59e0b',
    };
  }

  return {
    title: t('payment.checkout.error.title'),
    description: error,
    color: '#ef4444',
  };
}

function ErrorContent({ error, errorCode = undefined }: { error: string; errorCode?: ErrorViewProps['errorCode'] }) {
  const { t } = useLocaleContext();
  const theme = useTheme();
  const { title, description } = getErrorConfig(errorCode, error, t);
  const primaryColor = theme.palette.primary.main;

  const appUrl = typeof window !== 'undefined' ? (window as any).blocklet?.appUrl : '/';

  return (
    <Stack alignItems="center" justifyContent="center" sx={{ flex: 1, textAlign: 'center', px: 3 }}>
      {/* Geometric decoration */}
      <GeometricDecoration />

      {/* Title */}
      <Typography
        component="h1"
        sx={{
          fontWeight: 800,
          fontSize: { xs: 36, md: 52 },
          lineHeight: 1.05,
          letterSpacing: '-0.03em',
          color: 'text.primary',
          mb: 2,
        }}>
        {title}
      </Typography>

      {/* Description */}
      <Typography
        sx={{
          color: 'text.secondary',
          fontSize: { xs: 15, md: 17 },
          fontWeight: 300,
          lineHeight: 1.7,
          maxWidth: 420,
          letterSpacing: '0.01em',
        }}>
        {description}
      </Typography>

      {/* CTA button — large pill with primary bg */}
      {appUrl && (
        <Button
          href={appUrl}
          variant="contained"
          disableElevation
          startIcon={<ArrowBackIcon sx={{ fontSize: '20px !important' }} />}
          sx={{
            mt: 5,
            minWidth: 240,
            height: 56,
            px: 6,
            borderRadius: '9999px',
            textTransform: 'none',
            fontWeight: 600,
            fontSize: 16,
            letterSpacing: '0.02em',
            color: (th) => primaryContrastColor(th),
            boxShadow: `0 8px 32px -4px ${alpha(primaryColor, 0.3)}`,
            '&:hover': {
              boxShadow: `0 12px 40px -4px ${alpha(primaryColor, 0.4)}`,
              transform: 'translateY(-1px)',
            },
            transition: 'all 0.2s ease',
          }}>
          {t('common.back')}
        </Button>
      )}
    </Stack>
  );
}

export default function ErrorView({ error, errorCode = undefined, mode = 'inline' }: ErrorViewProps) {
  const theme = useTheme();
  const primaryColor = theme.palette.primary.main;
  const isFullScreen = mode === 'standalone';

  // Mesh gradient background (matching reference Version 2)
  const meshBg = {
    bgcolor: (t: any) => (t.palette.mode === 'dark' ? 'background.default' : '#f8faff'),
    backgroundImage: (t: any) =>
      t.palette.mode === 'dark'
        ? 'none'
        : `radial-gradient(at 0% 0%, ${alpha(primaryColor, 0.06)} 0px, transparent 50%),
           radial-gradient(at 100% 0%, ${alpha(primaryColor, 0.04)} 0px, transparent 50%),
           radial-gradient(at 100% 100%, ${alpha(primaryColor, 0.06)} 0px, transparent 50%),
           radial-gradient(at 0% 100%, rgba(203,213,225,0.3) 0px, transparent 50%)`,
  };

  if (!isFullScreen) {
    // Inline (card) mode
    return (
      <Box
        sx={{
          display: 'flex',
          width: '100%',
          minHeight: { xs: 400, md: 520 },
          maxWidth: 1120,
          mx: 'auto',
          borderRadius: '16px',
          overflow: 'hidden',
          boxShadow: 1,
          border: 1,
          borderColor: 'divider',
          ...meshBg,
        }}>
        <Box
          sx={{
            flex: 1,
            p: { xs: 4, md: 6 },
            display: 'flex',
            flexDirection: 'column',
            justifyContent: 'center',
            alignItems: 'center',
          }}>
          <ErrorContent error={error} errorCode={errorCode} />
        </Box>
      </Box>
    );
  }

  // Standalone (full-screen) mode
  return (
    <Box
      sx={{
        width: '100%',
        height: '100vh',
        minHeight: '100vh',
        display: 'flex',
        flexDirection: 'column',
        position: 'relative',
        overflow: 'hidden',
        ...meshBg,
      }}>
      {/* Header */}
      <Header
        sx={{
          position: 'absolute',
          top: 20,
          left: 0,
          right: 0,
          zIndex: 10,
          background: 'transparent',
          '& .header-container': { height: 'auto' },
        }}
        hideNavMenu
        brand={null}
        description={null}
        addons={(buildIns: any) =>
          buildIns.filter((addon: any) => ['locale-selector', 'theme-mode-toggle', 'session-user'].includes(addon.key))
        }
      />

      {/* Centered error content */}
      <ErrorContent error={error} errorCode={errorCode} />
    </Box>
  );
}
