import React from 'react';
import MainLayout from '../components/layout/MainLayout';
import { useParams, Link as RouterLink } from 'react-router-dom';
import { getEvent } from '../services/eventService';
import { Box, Container, Heading, Text, VStack, HStack, Badge, Spinner, Button, Image, Link as ChakraLink, Divider, Icon, useColorModeValue } from '@chakra-ui/react';
import { FiDownload, FiFile, FiImage, FiMapPin, FiClock } from 'react-icons/fi';
import DOMPurify from 'dompurify';
import { assetUrl } from '../utils/url';
import EventLocationMap from '../components/events/EventLocationMap';
import EmbeddedPoll from '../components/polls/EmbeddedPoll';
import FilePreview from '../components/common/FilePreview';

const ActivityDetailPage: React.FC = () => {
  const { id } = useParams();
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState<string | null>(null);
  const [data, setData] = React.useState<any>(null);

  React.useEffect(() => {
    let active = true;
    (async () => {
      try {
        if (!id) return;
        const ev = await getEvent(id);
        if (active) setData(ev);
      } catch (e: any) {
        if (active) setError(e?.message || 'Nelze načíst aktivitu');
      } finally {
        if (active) setLoading(false);
      }
    })();
    return () => { active = false; };
  }, [id]);

  const typeLabel = (t?: string) => t === 'match' ? 'Zápas' : t === 'training' ? 'Trénink' : t === 'meeting' ? 'Schůzka' : 'Jiné';
  const typeColor = (t?: string) => t === 'match' ? 'red' : t === 'training' ? 'blue' : t === 'meeting' ? 'green' : 'gray';

  // Extract YouTube video ID from various URL formats
  const getYouTubeEmbedUrl = (url: string): string | null => {
    if (!url) return null;
    
    // Already an embed URL
    if (url.includes('youtube.com/embed/')) {
      return url;
    }
    
    // Extract video ID from various formats
    let videoId: string | null = null;
    
    // Standard watch URL: https://www.youtube.com/watch?v=VIDEO_ID
    const watchMatch = url.match(/[?&]v=([^&#]+)/);
    if (watchMatch) {
      videoId = watchMatch[1];
    }
    
    // Short URL: https://youtu.be/VIDEO_ID
    const shortMatch = url.match(/youtu\.be\/([^?&#]+)/);
    if (shortMatch) {
      videoId = shortMatch[1];
    }
    
    // Embed URL: https://www.youtube.com/embed/VIDEO_ID
    const embedMatch = url.match(/youtube\.com\/embed\/([^?&#]+)/);
    if (embedMatch) {
      videoId = embedMatch[1];
    }
    
    if (videoId) {
      return `https://www.youtube.com/embed/${videoId}`;
    }
    
    return null;
  };

  const cardBg = useColorModeValue('white', 'gray.800');
  const borderColor = useColorModeValue('gray.200', 'gray.700');
  const mutedText = useColorModeValue('gray.600', 'gray.300');
  const linkColor = useColorModeValue('blue.600', 'blue.300');
  const linkHoverColor = useColorModeValue('blue.700', 'blue.200');

  return (
    <MainLayout>
      <Box py={10} bg="transparent">
        <Container maxW="3xl">
          {loading && (
            <HStack><Spinner size="sm" /><Text>Načítání…</Text></HStack>
          )}
          {!loading && error && (
            <Text color="red.500">{error}</Text>
          )}
          {!loading && !error && data && (
            <VStack align="stretch" spacing={5}>
              {/* Hero image */}
              {data.image_url && (
                <Box borderRadius="xl" overflow="hidden" borderWidth="1px">
                  <Image src={assetUrl(data.image_url) || data.image_url} alt={data.title} w="100%" maxH="420px" objectFit="cover" />
                </Box>
              )}

              {/* Title and meta */}
              <VStack align="stretch" spacing={1}>
                <HStack justify="space-between" align="start">
                  <Heading as="h1" size="lg" lineHeight={1.2}>{data.title}</Heading>
                  <Badge colorScheme={typeColor(data.type)}>{typeLabel(data.type)}</Badge>
                </HStack>
                <HStack spacing={4} color={mutedText} fontSize="sm">
                  <HStack>
                    <Icon as={FiClock} />
                    <Text>
                      {new Date(data.start_time).toLocaleString()} {data.end_time ? `– ${new Date(data.end_time).toLocaleString()}` : ''}
                    </Text>
                  </HStack>
                  {data.location && (
                    <HStack>
                      <Icon as={FiMapPin} />
                      <Text>{data.location}</Text>
                    </HStack>
                  )}
                </HStack>
              </VStack>

              {data.location && (
                <EventLocationMap 
                  location={data.location} 
                  title={data.title}
                  latitude={data.latitude}
                  longitude={data.longitude}
                />
              )}

              {/* YouTube Video */}
              {data.youtube_url && getYouTubeEmbedUrl(data.youtube_url) && (
                <Box borderRadius="lg" overflow="hidden" boxShadow="md">
                  <Box position="relative" paddingBottom="56.25%" height={0}>
                    <iframe
                      style={{ position: 'absolute', top: 0, left: 0, width: '100%', height: '100%' }}
                      src={getYouTubeEmbedUrl(data.youtube_url) || ''}
                      title={data.title}
                      frameBorder="0"
                      allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                      allowFullScreen
                    />
                  </Box>
                </Box>
              )}

              {/* Content */}
              {data.description && (
                <Box
                  bg={cardBg}
                  borderWidth="1px"
                  borderColor={borderColor}
                  borderRadius="lg"
                  p={5}
                  className="blog-content"
                  sx={{
                    ' h1, h2, h3, h4': { fontWeight: 'bold', mt: 3 },
                    ' p': { lineHeight: 1.8, mb: 3 },
                    ' ul, ol': { pl: 6, mb: 3 },
                    ' a': { color: linkColor, textDecoration: 'underline', _hover: { color: linkHoverColor } },
                    ' img': { maxWidth: '100%', borderRadius: 'md' },
                  }}
                  dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(String(data.description)) }}
                />
              )}

              {/* Attachments with Preview */}
              {(Array.isArray(data.attachments) && data.attachments.length > 0) && (
                <VStack align="stretch" spacing={3}>
                  <Heading as="h3" size="sm">Přílohy</Heading>
                  <VStack align="stretch" spacing={3}>
                    {data.attachments.map((att: any, idx: number) => (
                      <FilePreview
                        key={idx}
                        url={att.url}
                        name={att.name}
                        mimeType={att.mime_type}
                        size={att.size}
                        showInline={att.mime_type?.startsWith('image/')}
                      />
                    ))}
                  </VStack>
                </VStack>
              )}

              {/* Legacy single file_url */}
              {data.file_url && (
                <HStack>
                  <Button as={ChakraLink} href={assetUrl(data.file_url) || data.file_url} isExternal variant="outline" leftIcon={<FiDownload />}>
                    Stáhnout přílohu
                  </Button>
                </HStack>
              )}

              {/* Back links */}
              <Divider />
              <HStack>
                <Button as={RouterLink} to="/aktivity" variant="outline">Zpět na aktivity</Button>
                <Button as={RouterLink} to="/" variant="ghost">Domů</Button>
              </HStack>
            </VStack>
          )}
        </Container>
      </Box>
      
      {/* Embedded Poll - shows polls related to this event */}
      {data?.id && <EmbeddedPoll eventId={data.id} />}
    </MainLayout>
  );
};

export default ActivityDetailPage;
