import React from 'react';
import { Box, HStack, Text, Image } from '@chakra-ui/react';
import { ScoreboardState } from '@/services/scoreboard';

export const ScoreboardPreview: React.FC<{ state: ScoreboardState }> = ({ state }) => {
  const theme = state.theme || 'pill';

  switch (theme) {
    case 'pill':
      return (
        <HStack spacing={2} px={1.5} py={1} borderRadius="full" bg="white" borderWidth="1px" borderColor="gray.200" boxShadow="sm" width="max-content">
          <SegmentTeam colorA={state.primaryColor} left>
            {state.homeLogo ? <Image src={state.homeLogo} alt="home" boxSize="16px" objectFit="contain" /> : null}
            <Text textTransform="uppercase" fontSize="sm" lineHeight={1}>{state.homeShort || deriveShortLocal(state.homeName)}</Text>
          </SegmentTeam>
          <SegmentScore>{state.homeScore} – {state.awayScore}</SegmentScore>
          <SegmentTeam colorA={state.secondaryColor} right>
            <Text textTransform="uppercase" fontSize="sm" lineHeight={1}>{state.awayShort || deriveShortLocal(state.awayName)}</Text>
            {state.awayLogo ? <Image src={state.awayLogo} alt="away" boxSize="16px" objectFit="contain" /> : null}
          </SegmentTeam>
        </HStack>
      );
    case 'classic':
    case 'var1':
      return (
        <HStack spacing={3} bgGradient="linear(to-b, #c8d4dc, #a8b8c4)" px={5} py={3} borderRadius="lg" boxShadow="md" width="max-content">
          <Box bg="white" color="black" fontWeight="bold" px={3} py={1} borderRadius="md" fontSize="lg">{formatTimer(state.halfLength)}</Box>
          <Box bg={state.primaryColor || '#34495e'} color="white" px={4} py={2} borderRadius="md" fontWeight="bold">{state.homeShort || deriveShortLocal(state.homeName)}</Box>
          <Text fontWeight="bold" color="black">{state.homeScore}-{state.awayScore}</Text>
          <Box bg={state.secondaryColor || '#2c3e50'} color="white" px={4} py={2} borderRadius="md" fontWeight="bold">{state.awayShort || deriveShortLocal(state.awayName)}</Box>
        </HStack>
      );
    case 'var2':
      return (
        <HStack spacing={0} borderRadius="md" overflow="hidden" boxShadow="md" width="max-content">
          <Box bgGradient="linear(135deg, #4a5568, #2d3748)" color="white" px={3} py={2} fontWeight="bold">{formatTimer(state.halfLength)}</Box>
          <Box bgGradient="linear(135deg, #2c5282, #2a4365)" color="white" px={4} py={2} fontWeight="bold">{state.homeShort || deriveShortLocal(state.homeName)}</Box>
          <Box bgGradient="linear(135deg, #2c5282, #2a4365)" color="white" px={3} py={2} fontWeight="bold">{state.homeScore}-{state.awayScore}</Box>
          <Box bgGradient="linear(135deg, #2c5282, #2a4365)" color="white" px={4} py={2} fontWeight="bold">{state.awayShort || deriveShortLocal(state.awayName)}</Box>
        </HStack>
      );
    case 'var3':
      return (
        <Box textAlign="center" fontFamily="Poppins, Arial, sans-serif">
          <HStack spacing={0} justify="center">
            <Box w="102px" h="38px" bg="#F6F6F6" lineHeight="41px" position="relative">
              <Box position="absolute" left="-8px" top={0} w="6px" h="38px" bg={state.primaryColor || '#ea2212'} />
              <Text>{state.homeShort || deriveShortLocal(state.homeName)}</Text>
            </Box>
            <Box w="102px" h="38px" bg="#F6F6F6" lineHeight="41px" zIndex={2} boxShadow="0 3px 10px rgba(0,0,0,0.7)">
              <Text fontWeight="bold">{state.homeScore}-{state.awayScore}</Text>
            </Box>
            <Box w="102px" h="38px" bg="#F6F6F6" lineHeight="41px" position="relative">
              <Box position="absolute" right="-8px" top={0} w="6px" h="38px" bg={state.secondaryColor || '#ea2212'} />
              <Text>{state.awayShort || deriveShortLocal(state.awayName)}</Text>
            </Box>
          </HStack>
          <Box mt={2} w="306px" mx="auto" bg="#F6F6F6">
            <Text>{formatTimer(state.halfLength)}</Text>
          </Box>
        </Box>
      );
    case 'var4':
      return (
        <Box w="340px" borderWidth="1px" borderRadius="xl" boxShadow="xl" p={4} bg="white" color="gray.900">
          <HStack>
            <Text fontWeight="bold">{state.homeName}</Text>
            <Text ml="auto" fontWeight="extrabold">{state.homeScore}</Text>
          </HStack>
          <Box textAlign="center" fontWeight="extrabold" py={1}>VS</Box>
          <HStack>
            <Text fontWeight="bold">{state.awayName}</Text>
            <Text ml="auto" fontWeight="extrabold">{state.awayScore}</Text>
          </HStack>
          <HStack justify="flex-end" fontSize="sm" opacity={0.8} pt={2}>
            <Text>{formatTimer(state.halfLength)}</Text>
          </HStack>
        </Box>
      );
    default:
      return (
        <HStack spacing={3} bg="gray.900" color="white" px={4} py={3} borderRadius="lg" boxShadow="lg" width="max-content">
          <Text fontWeight="bold">{state.homeName}</Text>
          <Text fontWeight="black">{state.homeScore} : {state.awayScore}</Text>
          <Text fontWeight="bold">{state.awayName}</Text>
        </HStack>
      );
  }
};

// Small presentational helpers for the pill theme
const SegmentTeam: React.FC<{ colorA?: string; left?: boolean; right?: boolean; children: React.ReactNode }> = ({ colorA = '#1e3a8a', left, right, children }) => {
  return (
    <HStack
      px={2}
      py={0.5}
      borderRadius="full"
      bgGradient={`linear(to-r, ${colorA}, ${shadeColor(colorA, 20)})`}
      color="white"
      spacing={1.5}
      position="relative"
      _before={left ? { content: '""', position: 'absolute', left: '-10px', top: 0, bottom: 0, width: '14px', bgGradient: `linear(to-r, ${colorA}, ${shadeColor(colorA, 20)})`, borderTopLeftRadius: '999px', borderBottomLeftRadius: '999px' } : undefined}
      _after={right ? { content: '""', position: 'absolute', right: '-10px', top: 0, bottom: 0, width: '14px', bgGradient: `linear(to-r, ${colorA}, ${shadeColor(colorA, 20)})`, borderTopRightRadius: '999px', borderBottomRightRadius: '999px' } : undefined}
      minW="46px"
    >
      {children}
    </HStack>
  );
};

const SegmentScore: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  return (
    <Box px={2} py={0.5} borderRadius="md" bg="gray.50" borderWidth="1px" borderColor="gray.200" fontWeight="800" minW="58px" textAlign="center" fontSize="sm">
      {children}
    </Box>
  );
};

function formatTimer(halfLength: number): string {
  // Simple static mm:ss display using half length as baseline; real timer would come from backend
  const min = Math.max(0, Math.min(halfLength, 99));
  return `${String(min).padStart(2, '0')}:00`;
}

function deriveShortLocal(name?: string) {
  if (!name) return '---';
  const s = String(name).trim().toUpperCase();
  if (!s) return '---';
  const map: Record<string, string> = {
    'Á':'A','Ä':'A','Å':'A','Â':'A','À':'A',
    'Č':'C','Ć':'C','Ç':'C',
    'Ď':'D',
    'É':'E','Ě':'E','È':'E','Ë':'E','Ê':'E',
    'Í':'I','Ì':'I','Ï':'I','Î':'I',
    'Ň':'N','Ń':'N',
    'Ó':'O','Ö':'O','Ô':'O','Ò':'O',
    'Ř':'R',
    'Š':'S','Ś':'S',
    'Ť':'T',
    'Ú':'U','Ů':'U','Ù':'U','Ü':'U','Û':'U',
    'Ý':'Y',
    'Ž':'Z',
  };
  let out = '';
  for (const ch of s) {
    const c = map[ch] || ch;
    if (c >= 'A' && c <= 'Z') {
      out += c;
      if (out.length === 3) break;
    }
  }
  while (out.length < 3) out += '-';
  return out;
}

function shadeColor(hex: string, percent: number) {
  // Simple hex shade function
  try {
    const n = hex.replace('#','');
    const num = parseInt(n.length === 3 ? n.split('').map((c)=>c+c).join('') : n, 16);
    let r = (num >> 16) & 0xff;
    let g = (num >> 8) & 0xff;
    let b = num & 0xff;
    r = Math.min(255, Math.max(0, Math.round(r + (percent/100)*255)));
    g = Math.min(255, Math.max(0, Math.round(g + (percent/100)*255)));
    b = Math.min(255, Math.max(0, Math.round(b + (percent/100)*255)));
    return `#${[r,g,b].map(v=>v.toString(16).padStart(2,'0')).join('')}`;
  } catch {
    return hex;
  }
}

export default ScoreboardPreview;
