import React from 'react';
import { useParams, Link as RouterLink } from 'react-router-dom';
import { useQuery } from '@tanstack/react-query';
import { getPlayer } from '../services/public';
import { assetUrl } from '../utils/url';
import { Box, Badge, Button, Container, Divider, Heading, HStack, Image, SimpleGrid, Skeleton, Stack, Text, VStack, useColorModeValue } from '@chakra-ui/react';
import MainLayout from '../components/layout/MainLayout';
import NewsletterCTA from '../components/common/NewsletterCTA';
import { translateNationality, getCountryFlag } from '../utils/nationality';

const PlayerDetailPage: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const { data, isLoading, isError } = useQuery({ queryKey: ['player', id], queryFn: () => getPlayer(String(id)) });
  const cardBg = useColorModeValue('white', 'gray.800');
  const borderColor = useColorModeValue('gray.200', 'gray.700');

  if (isLoading) {
    return (
      <MainLayout>
        <Container maxW="7xl" py={8}>
          <Skeleton height="320px" />
        </Container>
      </MainLayout>
    );
  }

 

  if (isError || !data) {
    return (
      <MainLayout>
        <Container maxW="7xl" py={8}>
          <Text color="red.500">Hráče se nepodařilo načíst.</Text>
        </Container>
      </MainLayout>
    );
  }

  const fullName = [data.first_name, data.last_name].filter(Boolean).join(' ');

  return (
    <MainLayout>
      <Box>
        <Container maxW="7xl" py={{ base: 6, md: 10 }}>
          <VStack align="stretch" spacing={6}>
            <HStack justify="space-between">
              <HStack spacing={3}>
                <Heading as="h1" size={{ base: 'xl', md: '2xl' }}>{fullName}</Heading>
                {typeof data.jersey_number === 'number' && (
                  <Badge colorScheme="blue" fontSize="md" px={3} py={1}>#{data.jersey_number}</Badge>
                )}
                {data.position && (
                  <Badge variant="subtle" colorScheme="purple" fontSize="md" px={3} py={1}>{data.position}</Badge>
                )}
                {!data.is_active && (
                  <Badge colorScheme="gray" fontSize="md" px={3} py={1}>Neaktivní</Badge>
                )}
              </HStack>
              <Button as={RouterLink} to="/hraci" variant="outline">Zpět na přehled</Button>
            </HStack>

            <SimpleGrid columns={{ base: 1, md: 2 }} spacing={6}>
              <Box>
                <Image
                  src={assetUrl(data.image_url) || '/logo512.png'}
                  alt={fullName}
                  borderRadius="lg"
                  objectFit="cover"
                  w="100%"
                  h={{ base: '300px', md: '400px' }}
                />
              </Box>
              <Stack spacing={3} bg={cardBg} borderWidth="1px" borderColor={borderColor} borderRadius="lg" p={6} shadow="sm">
                <Heading size="md" mb={2}>Informace o hráči</Heading>
                {data.position && (
                  <Text><b>Pozice:</b> {data.position}</Text>
                )}
                {typeof data.jersey_number === 'number' && (
                  <Text><b>Číslo dresu:</b> <Text as="span" color="brand.primary" fontWeight="700">#{data.jersey_number}</Text></Text>
                )}
                {data.nationality && (
                  <HStack>
                    <Text><b>Národnost:</b></Text>
                    <Text as="span" fontSize="xl">{getCountryFlag(data.nationality)}</Text>
                    <Text>{translateNationality(data.nationality)}</Text>
                  </HStack>
                )}
                {data.date_of_birth && (
                  <Text><b>Datum narození:</b> {new Date(data.date_of_birth).toLocaleDateString('cs-CZ')} — {(() => { const a = calculateAge(data.date_of_birth); return a != null ? `${a} ${czYears(a)}` : '' })()}</Text>
                )}
                {data.team?.name ? (
                  <Text><b>Tým:</b> {data.team.name}</Text>
                ) : (typeof data.team_id === 'number' && data.team_id > 0) ? (
                  <Text><b>Tým ID:</b> {data.team_id}</Text>
                ) : null}
                {(data.height || data.weight) && (
                  <Text>
                    <b>Výška/Váha:</b> {data.height ? `${data.height} cm` : '-'} / {data.weight ? `${data.weight} kg` : '-'}
                  </Text>
                )}
                {data.email && (
                  <Text><b>Email:</b> <a href={`mailto:${data.email}`}>{data.email}</a></Text>
                )}
                {data.phone && (
                  <Text><b>Telefon:</b> <a href={`tel:${normalizeTel(data.phone)}`}>{data.phone}</a></Text>
                )}
              </Stack>
            </SimpleGrid>

          </VStack>
        </Container>
        <NewsletterCTA />
      </Box>
    </MainLayout>
  );
};

function calculateAge(iso: string): number | null {
  try {
    const d = new Date(iso);
    if (isNaN(d.getTime())) return null;
    const today = new Date();
    let age = today.getFullYear() - d.getFullYear();
    const m = today.getMonth() - d.getMonth();
    if (m < 0 || (m === 0 && today.getDate() < d.getDate())) age--;
    return age;
  } catch {
    return null;
  }
}

function czYears(n: number): string {
  if (n === 1) return 'rok';
  if (n >= 2 && n <= 4) return 'roky';
  return 'let';
}

function normalizeTel(input: string): string {
  if (!input) return '';
  let s = String(input).trim();
  s = s.replace(/[\s\-()]/g, '');
  if (s.startsWith('00')) s = '+' + s.slice(2);
  s = s.replace(/(?!^)[^\d]/g, '');
  if (s[0] !== '+' && s.startsWith('+')) {
    // keep + if present
  }
  return s;
}

export default PlayerDetailPage;
