import React, { useState } from 'react';
import {
  Box,
  Button,
  HStack,
  Icon,
  Link as ChakraLink,
  Modal,
  ModalOverlay,
  ModalContent,
  ModalHeader,
  ModalBody,
  ModalCloseButton,
  ModalFooter,
  Text,
  useDisclosure,
  Image,
  VStack,
  Badge,
  useColorModeValue,
  AspectRatio,
} from '@chakra-ui/react';
import { 
  FiDownload, 
  FiEye, 
  FiFile, 
  FiFileText, 
  FiImage,
  FiVideo,
  FiMusic,
} from 'react-icons/fi';
import { assetUrl } from '../../utils/url';

export interface FilePreviewProps {
  url: string;
  name?: string;
  mimeType?: string;
  size?: number;
  showInline?: boolean;
}

const FilePreview: React.FC<FilePreviewProps> = ({
  url,
  name,
  mimeType = '',
  size,
  showInline = false,
}) => {
  const { isOpen, onOpen, onClose } = useDisclosure();
  const [imageError, setImageError] = useState(false);
  
  const fullUrl = assetUrl(url) || url;
  const fileName = name || url.split('/').pop() || 'file';
  const mime = mimeType.toLowerCase();
  
  const borderColor = useColorModeValue('gray.200', 'gray.700');
  const cardBg = useColorModeValue('white', 'gray.800');
  const mutedText = useColorModeValue('gray.600', 'gray.300');
  const linkColor = useColorModeValue('blue.600', 'blue.300');

  // Determine file type and icon
  const getFileInfo = () => {
    if (mime.startsWith('image/')) {
      return { type: 'image', icon: FiImage, color: 'purple.500', canPreview: true };
    }
    if (mime === 'application/pdf') {
      return { type: 'pdf', icon: FiFileText, color: 'red.500', canPreview: true };
    }
    if (mime.startsWith('video/')) {
      return { type: 'video', icon: FiVideo, color: 'pink.500', canPreview: true };
    }
    if (mime.startsWith('audio/')) {
      return { type: 'audio', icon: FiMusic, color: 'green.500', canPreview: true };
    }
    if (mime.includes('word') || mime.includes('document')) {
      return { type: 'document', icon: FiFileText, color: 'blue.500', canPreview: false };
    }
    if (mime.includes('sheet') || mime.includes('excel')) {
      return { type: 'spreadsheet', icon: FiFile, color: 'green.600', canPreview: false };
    }
    if (mime.includes('presentation') || mime.includes('powerpoint')) {
      return { type: 'presentation', icon: FiFile, color: 'orange.500', canPreview: false };
    }
    return { type: 'other', icon: FiFile, color: 'gray.500', canPreview: false };
  };

  const fileInfo = getFileInfo();
  const sizeKB = typeof size === 'number' ? Math.round(size / 1024) : undefined;
  const sizeMB = sizeKB && sizeKB > 1024 ? (sizeKB / 1024).toFixed(1) : undefined;
  const sizeStr = sizeMB ? `${sizeMB} MB` : sizeKB ? `${sizeKB} kB` : '';

  // Render preview content based on file type
  const renderPreviewContent = () => {
    if (fileInfo.type === 'image') {
      if (imageError) {
        return (
          <VStack spacing={4} py={10}>
            <Icon as={FiImage} boxSize={12} color="gray.400" />
            <Text color={mutedText}>Obrázek se nepodařilo načíst</Text>
            <Button 
              as={ChakraLink} 
              href={fullUrl} 
              isExternal 
              leftIcon={<FiDownload />}
              colorScheme="blue"
            >
              Stáhnout soubor
            </Button>
          </VStack>
        );
      }
      return (
        <Image
          src={fullUrl}
          alt={fileName}
          maxW="100%"
          maxH="70vh"
          objectFit="contain"
          onError={() => setImageError(true)}
        />
      );
    }

    if (fileInfo.type === 'pdf') {
      // Try multiple PDF viewing methods due to CSP restrictions
      return (
        <VStack spacing={4} w="100%" minH="70vh">
          {/* Primary: Try direct iframe embed */}
          <Box w="100%" h="70vh" borderWidth="1px" borderRadius="md" overflow="hidden">
            <iframe
              src={`${fullUrl}#view=FitH&toolbar=1`}
              title={fileName}
              style={{ border: 'none', width: '100%', height: '100%' }}
              onError={(e) => {
                console.error('PDF iframe load error:', e);
              }}
            />
          </Box>
          
          {/* Fallback options */}
          <VStack spacing={2} w="100%">
            <Text fontSize="sm" color={mutedText} textAlign="center">
              Pokud se PDF nezobrazuje, použijte jedno z tlačítek níže:
            </Text>
            <HStack spacing={3} flexWrap="wrap" justify="center">
              <Button
                as={ChakraLink}
                href={fullUrl}
                isExternal
                leftIcon={<FiEye />}
                colorScheme="blue"
                size="sm"
              >
                Otevřít v novém okně
              </Button>
              <Button
                as={ChakraLink}
                href={`https://mozilla.github.io/pdf.js/web/viewer.html?file=${encodeURIComponent(fullUrl)}`}
                isExternal
                leftIcon={<FiEye />}
                colorScheme="purple"
                size="sm"
              >
                Zobrazit pomocí PDF.js
              </Button>
              <Button
                as={ChakraLink}
                href={`https://docs.google.com/viewer?url=${encodeURIComponent(fullUrl)}&embedded=true`}
                isExternal
                leftIcon={<FiEye />}
                colorScheme="green"
                size="sm"
              >
                Zobrazit přes Google
              </Button>
              <Button
                as={ChakraLink}
                href={fullUrl}
                download
                leftIcon={<FiDownload />}
                colorScheme="gray"
                size="sm"
              >
                Stáhnout PDF
              </Button>
            </HStack>
          </VStack>
        </VStack>
      );
    }

    if (fileInfo.type === 'video') {
      return (
        <AspectRatio ratio={16 / 9} w="100%">
          <video controls style={{ width: '100%', height: '100%' }}>
            <source src={fullUrl} type={mime} />
            Váš prohlížeč nepodporuje přehrávání videa.
          </video>
        </AspectRatio>
      );
    }

    if (fileInfo.type === 'audio') {
      return (
        <VStack spacing={4} py={10}>
          <Icon as={FiMusic} boxSize={12} color={fileInfo.color} />
          <audio controls style={{ width: '100%', maxWidth: '500px' }}>
            <source src={fullUrl} type={mime} />
            Váš prohlížeč nepodporuje přehrávání zvuku.
          </audio>
        </VStack>
      );
    }

    // For Office documents, show info and download option
    return (
      <VStack spacing={4} py={10}>
        <Icon as={fileInfo.icon} boxSize={16} color={fileInfo.color} />
        <VStack spacing={2}>
          <Text fontSize="lg" fontWeight="medium">{fileName}</Text>
          {sizeStr && <Badge colorScheme="gray">{sizeStr}</Badge>}
          <Text color={mutedText} fontSize="sm" textAlign="center">
            {fileInfo.type === 'presentation' && 'PowerPoint prezentace'}
            {fileInfo.type === 'document' && 'Word dokument'}
            {fileInfo.type === 'spreadsheet' && 'Excel tabulka'}
          </Text>
        </VStack>
        <HStack spacing={3}>
          <Button 
            as={ChakraLink} 
            href={fullUrl} 
            isExternal 
            leftIcon={<FiDownload />}
            colorScheme="blue"
          >
            Stáhnout
          </Button>
          <Button 
            as={ChakraLink} 
            href={`https://view.officeapps.live.com/op/view.aspx?src=${encodeURIComponent(fullUrl)}`}
            isExternal
            leftIcon={<FiEye />}
            variant="outline"
          >
            Zobrazit online
          </Button>
        </HStack>
        <Text fontSize="xs" color={mutedText}>
          Pro zobrazení .pptx, .docx, .xlsx můžete použít "Zobrazit online"
        </Text>
      </VStack>
    );
  };

  // Inline preview for images
  if (showInline && fileInfo.type === 'image') {
    return (
      <Box
        borderWidth="1px"
        borderColor={borderColor}
        borderRadius="md"
        overflow="hidden"
        bg={cardBg}
      >
        <Image
          src={fullUrl}
          alt={fileName}
          w="100%"
          maxH="400px"
          objectFit="cover"
          cursor="pointer"
          onClick={onOpen}
          _hover={{ opacity: 0.9 }}
          onError={() => setImageError(true)}
        />
        {!imageError && (
          <HStack justify="space-between" p={3} borderTopWidth="1px">
            <Text fontSize="sm" color={mutedText} isTruncated maxW="60%">
              {fileName}
            </Text>
            <HStack spacing={2}>
              <Button size="sm" leftIcon={<FiEye />} onClick={onOpen}>
                Náhled
              </Button>
              <Button 
                as={ChakraLink} 
                href={fullUrl} 
                isExternal 
                size="sm" 
                variant="ghost"
                leftIcon={<FiDownload />}
              >
                Stáhnout
              </Button>
            </HStack>
          </HStack>
        )}
      </Box>
    );
  }

  // Compact button view
  return (
    <>
      <HStack
        justify="space-between"
        p={3}
        borderWidth="1px"
        borderColor={borderColor}
        borderRadius="md"
        bg={cardBg}
      >
        <HStack flex={1} minW={0}>
          <Icon as={fileInfo.icon} color={fileInfo.color} flexShrink={0} />
          <VStack align="start" spacing={0} flex={1} minW={0}>
            <ChakraLink 
              href={fullUrl} 
              isExternal 
              color={linkColor}
              fontWeight="medium"
              isTruncated
              maxW="100%"
              _hover={{ textDecoration: 'underline' }}
            >
              {fileName}
            </ChakraLink>
            {sizeStr && <Text fontSize="xs" color={mutedText}>{sizeStr}</Text>}
          </VStack>
        </HStack>
        <HStack spacing={2} flexShrink={0}>
          {fileInfo.canPreview && (
            <Button size="sm" leftIcon={<FiEye />} onClick={onOpen} variant="outline">
              Náhled
            </Button>
          )}
          <Button 
            as={ChakraLink} 
            href={fullUrl} 
            isExternal 
            size="sm" 
            leftIcon={<FiDownload />}
            colorScheme="blue"
          >
            Stáhnout
          </Button>
        </HStack>
      </HStack>

      {/* Preview Modal */}
      <Modal isOpen={isOpen} onClose={onClose} size="6xl" isCentered>
        <ModalOverlay bg="blackAlpha.800" />
        <ModalContent maxW="90vw" maxH="90vh">
          <ModalHeader>
            <HStack justify="space-between">
              <VStack align="start" spacing={0}>
                <Text>{fileName}</Text>
                {sizeStr && <Text fontSize="sm" fontWeight="normal" color={mutedText}>{sizeStr}</Text>}
              </VStack>
            </HStack>
          </ModalHeader>
          <ModalCloseButton />
          <ModalBody pb={6} overflow="auto">
            {renderPreviewContent()}
          </ModalBody>
          <ModalFooter>
            <Button 
              as={ChakraLink} 
              href={fullUrl} 
              isExternal 
              leftIcon={<FiDownload />}
              colorScheme="blue"
              mr={3}
            >
              Stáhnout
            </Button>
            <Button variant="ghost" onClick={onClose}>
              Zavřít
            </Button>
          </ModalFooter>
        </ModalContent>
      </Modal>
    </>
  );
};

export default FilePreview;
